From 6045ce23d0bd5a51b1a65ed9c5aeb42ca9050312 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sun, 26 Jul 2026 15:20:42 -0700 Subject: [PATCH] Rank activities by sequence, scope the seed guard, unify the probes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two Cursor Bugbot findings on the merge, plus the simplification they enabled: - The activity cap ordered `created_at` before `sequence`; the app ranks `sequence` first. The keys disagree outright under clock skew — a higher-sequence activity can carry an older timestamp — and then the cap keeps rows the timeline treats as oldest. Reordered to match, with the regression test now covering a skewed row, not just a tied one. - The running-server guard blocked on a live server in either state directory while the seed touches exactly one. A server using only the other directory's database now no longer refuses the seed; both the pre-copy check and the pre-commit re-check take the resolved state dir. - Scoping the probe meant threading one rule through both variants, so they now share a single implementation: the sync function reads and checks, and the Effect wrapper just lifts it. That deletes the schema decoder the Effect path used, removes the duplicated parsing, and makes the parity the tests pin structural rather than incidental. Co-Authored-By: Claude Opus 5 (1M context) --- scripts/dev-seed.ts | 8 +- scripts/lib/dev-seed.test.ts | 23 +++--- scripts/lib/dev-seed.ts | 11 +-- scripts/lib/server-runtime-probe.test.ts | 31 ++++++++ scripts/lib/server-runtime-probe.ts | 94 ++++++++++-------------- 5 files changed, 94 insertions(+), 73 deletions(-) diff --git a/scripts/dev-seed.ts b/scripts/dev-seed.ts index 270dab10c5..c527e0d1d4 100644 --- a/scripts/dev-seed.ts +++ b/scripts/dev-seed.ts @@ -264,7 +264,11 @@ const devSeedCli = Command.make("dev-seed", { // What it cannot do is tell that server the projections it is holding in // memory, and the event log it is appending to, were both replaced under // it. Its next write then lands on top of a read model it never built. - const runningPid = yield* findRunningServerPid(targetBaseDir); + // + // Scoped to the state directory being seeded: a server using only the + // other directory's database is not touching this one, and blocking on it + // would refuse seeds that are perfectly safe. + const runningPid = yield* findRunningServerPid(targetBaseDir, targetStateDir); if (Option.isSome(runningPid)) { return yield* new DevSeedTargetError({ reason: "server-running", @@ -284,7 +288,7 @@ const devSeedCli = Command.make("dev-seed", { // The check above happens before the copy, which can take seconds. // Re-checked just before the commit so a server that started in // between aborts the seed instead of having its database swapped. - findRunningServerPid: () => findRunningServerPidSync(targetBaseDir), + findRunningServerPid: () => findRunningServerPidSync(targetBaseDir, targetStateDir), }), catch: (cause) => cause as DevSeedError, }); diff --git a/scripts/lib/dev-seed.test.ts b/scripts/lib/dev-seed.test.ts index 0fe78e271e..b2cf49394e 100644 --- a/scripts/lib/dev-seed.test.ts +++ b/scripts/lib/dev-seed.test.ts @@ -404,15 +404,19 @@ describe("seedDevDatabase", () => { withDatabases(({ source, target }) => { const sourceDatabase = new NodeSqlite.DatabaseSync(source); sourceDatabase.exec("DELETE FROM projection_thread_activities"); + const insert = sourceDatabase.prepare( + `INSERT INTO projection_thread_activities + VALUES (?, 't4', 'neutral', 'tool', 'ran', '{}', ?, ?)`, + ); const tied = "2026-07-10T00:00:00.000Z"; - for (const sequence of [1, 2, 3, 4]) { - sourceDatabase - .prepare( - `INSERT INTO projection_thread_activities - VALUES (?, 't4', 'neutral', 'tool', 'ran', '{}', ?, ?)`, - ) - .run(`tie-${String(sequence)}`, sequence, tied); + // Timestamps tie within a burst... + for (const sequence of [1, 2, 3]) { + insert.run(`tie-${String(sequence)}`, sequence, tied); } + // ...and can disagree with sequence outright under clock skew. The app + // ranks by sequence first, so this row outranks every tied one despite + // its older timestamp. + insert.run("skewed-4", 4, "2026-07-09T00:00:00.000Z"); sourceDatabase.close(); seedDevDatabase({ @@ -427,8 +431,9 @@ describe("seedDevDatabase", () => { target, "SELECT activity_id FROM projection_thread_activities ORDER BY sequence DESC", ).map((row) => row.activity_id); - // The two highest sequences, not whichever two the storage order yielded. - assert.deepStrictEqual(kept, ["tie-4", "tie-3"]); + // The two highest sequences — not the two newest timestamps, and not + // whichever two the storage order yielded. + assert.deepStrictEqual(kept, ["skewed-4", "tie-3"]); }); }); diff --git a/scripts/lib/dev-seed.ts b/scripts/lib/dev-seed.ts index fa05af6489..644cb9cfd2 100644 --- a/scripts/lib/dev-seed.ts +++ b/scripts/lib/dev-seed.ts @@ -554,16 +554,17 @@ export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary { keyColumn: "thread_id", keys: threadIds, // Ordered the way the app reads these back — `sequence` first, then - // `created_at` (ProjectionSnapshotQuery). Capping on `created_at` - // alone cuts arbitrarily among rows sharing a timestamp, which is the - // common case for a burst of tool activity: the "newest N" kept can be - // the oldest N in the order the timeline actually displays. + // `created_at` (ProjectionSnapshotQuery). Any other key order can keep + // rows the timeline treats as oldest: timestamps tie within a burst of + // tool activity, and can even disagree with `sequence` outright when + // events arrive with skewed clocks. Descending, a NULL `sequence` + // sorts last, mirroring where the app's ascending reads place it. // // `sequence` arrived in migration 008, so a source without it falls // back to the timestamp — same drift tolerance as the rest of the copy. perKeyLimit: { orderBy: hasColumn(source, "projection_thread_activities", "sequence") - ? `"created_at" DESC, "sequence"` + ? `"sequence" DESC, "created_at"` : `"created_at"`, limit: options.activityLimit, }, diff --git a/scripts/lib/server-runtime-probe.test.ts b/scripts/lib/server-runtime-probe.test.ts index c501878fa7..9b8a645995 100644 --- a/scripts/lib/server-runtime-probe.test.ts +++ b/scripts/lib/server-runtime-probe.test.ts @@ -153,3 +153,34 @@ describe("findRunningServerPidSync agrees with the Effect probe", () => { }).pipe(Effect.provide(NodeServices.layer)), ); }); + +// A caller that has resolved which database it is about to touch must not be +// blocked by a server using only the other one. +describe("scoping to one state directory", () => { + it.effect("ignores a live server in the other directory", () => + Effect.gen(function* () { + const baseDir = yield* makeBaseDir(); + yield* writeRuntimeState({ + baseDir, + stateDir: "dev", + contents: runtimeStateJson(process.pid), + }); + + assert.isUndefined(findRunningServerPidSync(baseDir, "userdata")); + assert.isTrue(Option.isNone(yield* findRunningServerPid(baseDir, "userdata"))); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("still reports a live server in the named directory", () => + Effect.gen(function* () { + const baseDir = yield* makeBaseDir(); + yield* writeRuntimeState({ + baseDir, + stateDir: "dev", + contents: runtimeStateJson(process.pid), + }); + + assert.equal(findRunningServerPidSync(baseDir, "dev"), process.pid); + }).pipe(Effect.provide(NodeServices.layer)), + ); +}); diff --git a/scripts/lib/server-runtime-probe.ts b/scripts/lib/server-runtime-probe.ts index e2b7bd052c..e525afecdf 100644 --- a/scripts/lib/server-runtime-probe.ts +++ b/scripts/lib/server-runtime-probe.ts @@ -11,23 +11,11 @@ import * as NodeFS from "node:fs"; import * as NodePath from "node:path"; import * as Effect from "effect/Effect"; -import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; -import * as Path from "effect/Path"; -import * as Schema from "effect/Schema"; /** The two state directories `deriveServerPaths` can select. */ const STATE_DIRS = ["dev", "userdata"] as const; -const RuntimeStateProbe = Schema.Struct({ - /** Positive, for the reason `isPidLive` explains. */ - pid: Schema.Int.check(Schema.isGreaterThan(0)), -}); - -const decodeRuntimeStateProbe = Schema.decodeUnknownEffect( - Schema.fromJsonString(RuntimeStateProbe), -); - /** * The runtime-state file is removed by a release finalizer, so a server killed * with SIGKILL — or one that crashed — leaves it behind. Signal 0 runs the @@ -60,59 +48,51 @@ const isPidLive = (pid: number): boolean => { }; /** - * The pid of a live server under `baseDir`, if any. + * The pid of a live server whose state file sits in one directory. * - * Both state directories are checked because which one a given server chose - * depends on flags the caller of this should not have to reason about — the - * same reason `auth pairing url` checks both. + * Synchronous because its main caller runs inside `seedDevDatabase`'s open + * SQLite transaction, where nothing can await. Applies one rule everywhere: a + * positive live pid counts, anything unparseable does not — a malformed or + * half-written file says nothing about liveness, and treating it as "a server + * is up" would block seeding with no way to clear it. */ -export const findRunningServerPid = Effect.fn("findRunningServerPid")(function* (baseDir: string) { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - - for (const stateDir of STATE_DIRS) { - const statePath = path.join(baseDir, stateDir, "server-runtime.json"); - const raw = yield* fileSystem.readFileString(statePath).pipe(Effect.option); - if (Option.isNone(raw)) { - continue; - } - // A malformed or half-written file says nothing about liveness; treating it - // as "a server is up" would block seeding with no way to clear it. - const state = yield* decodeRuntimeStateProbe(raw.value).pipe(Effect.option); - if (Option.isSome(state) && isPidLive(state.value.pid)) { - return Option.some(state.value.pid); - } +function findPidInStateDir(baseDir: string, stateDir: string): number | undefined { + let raw: string; + try { + raw = NodeFS.readFileSync(NodePath.join(baseDir, stateDir, "server-runtime.json"), "utf8"); + } catch { + return undefined; } - - return Option.none(); -}); + try { + const parsed: unknown = JSON.parse(raw); + const pid: unknown = (parsed as { pid?: unknown } | null)?.pid; + return typeof pid === "number" && isPidLive(pid) ? pid : undefined; + } catch { + return undefined; + } +} /** - * The same probe, synchronously. + * The pid of a live server under `baseDir`, if any. * - * `seedDevDatabase` is synchronous — it holds an open SQLite transaction — so - * its last-moment re-check cannot await an Effect. Reads the file directly - * rather than through the platform layer for that reason, and applies the same - * rules: a positive live pid counts, anything unparseable does not. + * `stateDir` scopes the probe to one state directory when the caller has + * already resolved which database it is about to touch — a server using only + * the *other* directory's database is not a conflict and must not block it. + * Omitted, both directories count, for callers guarding the base as a whole. */ -export function findRunningServerPidSync(baseDir: string): number | undefined { - for (const stateDir of STATE_DIRS) { - const statePath = NodePath.join(baseDir, stateDir, "server-runtime.json"); - let raw: string; - try { - raw = NodeFS.readFileSync(statePath, "utf8"); - } catch { - continue; - } - try { - const parsed: unknown = JSON.parse(raw); - const pid: unknown = (parsed as { pid?: unknown } | null)?.pid; - if (typeof pid === "number" && isPidLive(pid)) { - return pid; - } - } catch { - // Half-written or malformed: says nothing about liveness either way. +export function findRunningServerPidSync(baseDir: string, stateDir?: string): number | undefined { + for (const candidate of stateDir === undefined ? STATE_DIRS : [stateDir]) { + const pid = findPidInStateDir(baseDir, candidate); + if (pid !== undefined) { + return pid; } } return undefined; } + +/** {@link findRunningServerPidSync} for Effect callers. */ +export const findRunningServerPid = ( + baseDir: string, + stateDir?: string, +): Effect.Effect> => + Effect.sync(() => Option.fromNullishOr(findRunningServerPidSync(baseDir, stateDir)));