Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion apps/server/src/orchestration-v2/ProjectionStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,19 @@ const assertShellIndexCoversShells = Effect.fnUntraced(function* () {
const store = yield* ProjectionStore.ProjectionStoreV2;
const snapshot = yield* store.getShellSnapshot();
const shells = snapshot.threads;
const index = yield* store.listActiveShellIndex();
const indexRead = traceSqlStatements();
const index = yield* store.listActiveShellIndex().pipe(Effect.withTracer(indexRead.tracer));
// Migration 132's index answers every payload field the read selects, so no row is parsed.
const indexProgram = yield* (yield* SqlClient.SqlClient).unsafe<{
readonly opcode: string;
readonly p4: unknown;
}>(`EXPLAIN ${indexRead.statements[0]}`);
assert.deepEqual(
indexProgram
.filter((op) => op.opcode.startsWith("Function") && String(op.p4).startsWith("json_extract"))
.map((op) => op.p4),
[],
);
const { tracer, statements, queryTransactions } = traceSqlStatements();
const activity = yield* store.getAgentAwarenessSnapshot().pipe(Effect.withTracer(tracer));
assert.equal(activity.snapshotSequence, snapshot.snapshotSequence);
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/persistence/Migrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ import Migration0128 from "./Migrations/128_WorkflowRunSubject.ts";
import Migration0129 from "./Migrations/129_EscapedLinkLabelsAsText.ts";
import Migration0130 from "./Migrations/130_PeerLinkReachabilityErrors.ts";
import Migration0131 from "./Migrations/131_ScheduledSessionRuns.ts";
import Migration0132 from "./Migrations/132_ActiveShellIndexDelegatedFrom.ts";

const migrationEntries = [
[1, "OrchestrationEvents", Migration0001],
Expand Down Expand Up @@ -276,6 +277,7 @@ const migrationEntries = [
[129, "EscapedLinkLabelsAsText", Migration0129],
[130, "PeerLinkReachabilityErrors", Migration0130],
[131, "ScheduledSessionRuns", Migration0131],
[132, "ActiveShellIndexDelegatedFrom", Migration0132],
] as const;

export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/sql/SqlClient";

export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;

// Migration 118's index, with the delegatedFrom fields ProjectionStore.listActiveShellIndex now
// reads too. Keep the expressions identical to that query's.
yield* sql`DROP INDEX IF EXISTS orchestration_v2_projection_threads_active_shell_idx`;
yield* sql`
CREATE INDEX orchestration_v2_projection_threads_active_shell_idx
ON orchestration_v2_projection_threads(
updated_at,
thread_id,
project_id,
CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.lineage.relationshipToParent') END,
CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.lineage.parentThreadId') END,
CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.lineage.rootThreadId') END,
CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.lineage.sideChat') END,
CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.lineage.workflowStep') END,
CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.delegatedFrom.environmentId') END,
CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.delegatedFrom.threadId') END,
CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.delegatedFrom.title') END,
CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.settledOverride') END,
CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.settledAt') END,
CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.pinnedAt') END,
CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.pinOrderKey') END,
CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.snoozedUntil') END,
CASE WHEN json_valid(payload_json) THEN json_type(payload_json, '$.pullRequests[0]') END
)
WHERE deleted_at IS NULL AND archived_at IS NULL
`;
});
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ describe("V2 preview upgrade", () => {
[129, "EscapedLinkLabelsAsText"],
[130, "PeerLinkReachabilityErrors"],
[131, "ScheduledSessionRuns"],
[132, "ActiveShellIndexDelegatedFrom"],
]);
assert.deepStrictEqual(yield* runMigrations(), []);
assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports);
Expand Down Expand Up @@ -265,6 +266,7 @@ describe("V2 preview upgrade", () => {
[129, "EscapedLinkLabelsAsText"],
[130, "PeerLinkReachabilityErrors"],
[131, "ScheduledSessionRuns"],
[132, "ActiveShellIndexDelegatedFrom"],
]);
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
);
Expand Down
100 changes: 43 additions & 57 deletions apps/server/src/vcs/VcsStatusBroadcaster.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2295,63 +2295,49 @@ describe("VcsStatusBroadcaster", () => {
}).pipe(Effect.provide(NodeServices.layer)),
);

it("refreshes once per checkout in either event order, and on every soft reset", () => {
// Each event says whether HEAD's identity was already the one last seen.
const cases = [
{
events: [
["lock", false],
["head", true],
],
refreshes: [true, false],
},
{
events: [
["head", false],
["lock", true],
],
refreshes: [true, false],
},
{
events: [
["lock", true],
["lock", true],
],
refreshes: [true, true],
},
{
events: [
["head", false],
["lock", true],
["lock", true],
],
refreshes: [true, false, true],
},
{
events: [
["poll", false],
["lock", true],
],
refreshes: [true, true],
},
{
events: [
["head", true],
["lock", true],
],
refreshes: [false, true],
},
] as const;
for (const { events, refreshes } of cases) {
let checkoutAwaitsLock = false;
const seen = events.map(([kind, reported]) => {
const next = VcsStatusBroadcaster.nextHeadWatch(kind, reported, checkoutAwaitsLock);
checkoutAwaitsLock = next.checkoutAwaitsLock;
return next.refresh;
});
assert.deepStrictEqual(seen, [...refreshes], JSON.stringify(events));
}
});
it.effect(
"a repeated event for one ref move sees no change, and each soft reset or commit does",
() =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const commonDir = yield* fs.makeTempDirectoryScoped({ prefix: "vcs-checkout-state-" });
const gitDir = path.join(commonDir, "worktrees", "wt");
const headPath = path.join(gitDir, "HEAD");
const refPath = path.join(commonDir, "refs", "heads", "main");
yield* fs.makeDirectory(gitDir, { recursive: true });
yield* fs.makeDirectory(path.dirname(refPath), { recursive: true });
yield* fs.writeFileString(headPath, "ref: refs/heads/main\n");
yield* fs.writeFileString(refPath, "88a38bfa\n");
const replace = (file: string, content: string) =>
fs
.writeFileString(`${file}.lock`, content)
.pipe(Effect.andThen(fs.rename(`${file}.lock`, file)));
const state = VcsStatusBroadcaster.checkoutState("head", headPath, commonDir);

const before = yield* state;
assert.equal(yield* state, before);
// `git reset --soft`: only the branch ref in the common directory moves.
yield* replace(refPath, "4b825dc6\n");
const reset = yield* state;
assert.notEqual(reset, before);
assert.equal(yield* state, reset);
yield* replace(refPath, "88a38bfa\n");
const resetAgain = yield* state;
assert.notEqual(resetAgain, reset);
// `git commit` or `git add` rewrites the worktree's index.
yield* replace(path.join(gitDir, "index"), "index");
const committed = yield* state;
assert.notEqual(committed, resetAgain);
// A branch that lives only in packed-refs moves when packed-refs is rewritten.
yield* fs.remove(refPath);
yield* replace(path.join(commonDir, "packed-refs"), "88a38bfa refs/heads/main\n");
const packed = yield* state;
assert.notEqual(packed, committed);
yield* replace(path.join(commonDir, "packed-refs"), "4b825dc6 refs/heads/main\n");
assert.notEqual(yield* state, packed);
}).pipe(Effect.provide(NodeServices.layer)),
);

it.live("a terminal commit or soft reset refreshes local-only Changes totals", () =>
Effect.gen(function* () {
Expand Down
111 changes: 57 additions & 54 deletions apps/server/src/vcs/VcsStatusBroadcaster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,18 +59,37 @@ const UNREADABLE_HEAD = "unreadable";
// Edits outside a turn move no ref, so idle polls still re-read local status this often.
const POLLS_PER_FORCED_LOCAL_READ = 4;

// A checkout raises HEAD and HEAD.lock events in either order and refreshes once; a soft reset
// leaves HEAD as it was and raises only the HEAD.lock one.
export function nextHeadWatch(
kind: "head" | "poll" | "lock",
reported: boolean,
checkoutAwaitsLock: boolean,
): { readonly refresh: boolean; readonly checkoutAwaitsLock: boolean } {
if (kind === "lock")
return { refresh: !(reported && checkoutAwaitsLock), checkoutAwaitsLock: false };
if (reported) return { refresh: false, checkoutAwaitsLock };
return { refresh: true, checkoutAwaitsLock: kind === "head" };
}
const fileIdentity = (info: FileSystem.File.Info) =>
`${info.dev}:${Option.getOrUndefined(info.ino)}:${Option.getOrUndefined(info.mtime)?.getTime()}:${info.size}`;

// What a ref move changes: HEAD for a checkout, the branch ref for a soft reset, ref and index for a
// commit. One move raises several events (Linux reports HEAD.lock's create and unlink as two
// Removes), so an event refreshes only when this differs from what the previous event saw.
export const checkoutState = Effect.fnUntraced(function* (
headIdentity: string,
headPath: string,
commonDirectory: string,
) {
if (headIdentity === UNREADABLE_HEAD) return UNREADABLE_HEAD;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const ref = yield* fs.readFileString(headPath).pipe(
Effect.map((head) => /^ref: (refs\/\S+)/u.exec(head)?.[1]),
Effect.orElseSucceed(() => undefined),
);
const files = [
path.join(path.dirname(headPath), "index"),
path.join(commonDirectory, "packed-refs"),
...(ref ? [path.join(commonDirectory, ref)] : []),
];
const identities = yield* Effect.forEach(files, (file) =>
fs.stat(file).pipe(
Effect.map(fileIdentity),
Effect.orElseSucceed(() => "absent"),
),
);
return [headIdentity, ...identities].join("|");
});

function boundedDiagnosticValue(value: string): string {
return value.slice(0, MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH);
Expand Down Expand Up @@ -1366,29 +1385,32 @@ export const make = Effect.gen(function* () {
Effect.map((info) => info.type === "Directory"),
Effect.orElseSucceed(() => false),
);
const commonDirectory = yield* fs.readFileString(path.join(headDirectory, "commondir")).pipe(
Effect.map((v) => (v.trim() ? path.resolve(headDirectory, v.trim()) : headDirectory)),
Effect.orElseSucceed(() => headDirectory),
);
const reftableDirs: Array<string> = [];
const headReftable = path.resolve(headDirectory, "reftable");
if (yield* isDir(headReftable)) {
reftableDirs.push(headReftable);
const common = yield* fs.readFileString(path.join(headDirectory, "commondir")).pipe(
Effect.map((v) => (v.trim() ? path.resolve(headDirectory, v.trim(), "reftable") : null)),
Effect.orElseSucceed(() => null),
);
if (common && common !== headReftable && (yield* isDir(common))) reftableDirs.push(common);
const common = path.resolve(commonDirectory, "reftable");
if (common !== headReftable && (yield* isDir(common))) reftableDirs.push(common);
}
// Reftable repos keep a static HEAD placeholder, so the check also covers each tables.list.
const identityFiles = [headPath, ...reftableDirs.map((dir) => path.join(dir, "tables.list"))];
const headIdentity = Effect.forEach(identityFiles, (file) =>
fs.stat(file).pipe(
Effect.map(
(info) =>
`${info.dev}:${Option.getOrUndefined(info.ino)}:${Option.getOrUndefined(info.mtime)?.getTime()}:${info.size}`,
),
Effect.map(fileIdentity),
Effect.orElseSucceed(() => UNREADABLE_HEAD),
),
).pipe(Effect.map((ids) => (ids.includes(UNREADABLE_HEAD) ? UNREADABLE_HEAD : ids.join("|"))));
const readCheckoutState = (head: string) =>
checkoutState(head, headPath, commonDirectory).pipe(
withFileSystem,
Effect.provideService(Path.Path, path),
);
const seenHead = yield* SubscriptionRef.make(yield* headIdentity);
let checkoutAwaitsLock = false;
let seenState = yield* readCheckoutState(yield* SubscriptionRef.get(seenHead));
const watching = yield* Deferred.make<void>();
// Subscribers wait for the watch and for the check that covers its start.
const covered = Deferred.await(watching).pipe(
Expand Down Expand Up @@ -1445,25 +1467,13 @@ export const make = Effect.gen(function* () {
name === "HEAD" || name === "index" || (name === "HEAD.lock" && event._tag === "Remove")
);
}),
Stream.map((event) => {
const name = path.basename(event.path);
return name === "HEAD"
? ("head" as const)
: name === "index"
? ("index" as const)
: ("lock" as const);
}),
// A checkout made as the watch starts raises no event on macOS. Reftable repos keep a static
// HEAD placeholder and replace tables.list (and commondir's in worktrees) instead.
Stream.merge(
Stream.mergeAll(
[
pollUnreportedChanges(headIdentity, seenHead, covered).pipe(
Stream.map(() => "poll" as const),
),
...reftableDirs.map((dir) =>
watchReftable(dir).pipe(Stream.map(() => "reftable" as const)),
),
pollUnreportedChanges(headIdentity, seenHead, covered),
...reftableDirs.map(watchReftable),
],
{ concurrency: "unbounded" },
),
Expand All @@ -1476,24 +1486,17 @@ export const make = Effect.gen(function* () {
headGenerations.set(cwd, (headGenerations.get(cwd) ?? 0) + 1);
}),
),
// An event for a HEAD or tables.list change the check above already published is dropped
// here; index updates always refresh.
Stream.filterEffect((kind) =>
kind === "index"
? Effect.succeed(true)
: Effect.gen(function* () {
const head = yield* headIdentity;
const reported =
head !== UNREADABLE_HEAD && head === (yield* SubscriptionRef.get(seenHead));
if (!reported) yield* SubscriptionRef.set(seenHead, head);
const next = nextHeadWatch(
kind === "reftable" ? "poll" : kind,
reported,
checkoutAwaitsLock,
);
checkoutAwaitsLock = next.checkoutAwaitsLock;
return next.refresh;
}),
Stream.filterEffect(() =>
Effect.gen(function* () {
const head = yield* headIdentity;
const reported =
head !== UNREADABLE_HEAD && head === (yield* SubscriptionRef.get(seenHead));
if (!reported) yield* SubscriptionRef.set(seenHead, head);
const state = yield* readCheckoutState(head);
const changed = state === UNREADABLE_HEAD || state !== seenState;
seenState = state;
return changed;
}),
),
// A rebase moves HEAD many times; refresh once for whatever arrived during a refresh.
Stream.buffer({ capacity: 1, strategy: "sliding" }),
Expand Down
Loading