Harden dev:seed against state it cannot settle
Review of the seeding path found five ways a seeded database could describe something the copy cannot back up: - Nothing stopped `dev:seed` from running against a live server. SQLite locking lets the seed take the write lock between the server's own writes and commit cleanly; what it cannot do is tell that server its projections and event log were replaced underneath it. Refuse instead, via a pid probe over both state directories. - A thread copied mid-turn kept `state = 'running'`. The session override did not cover it — the turn is read independently, and an unsettled one leaves the thread spinning and its timeline unfoldable forever. Settle those to "interrupted", matching what the server does when a session leaves "running". Streaming messages are finished for the same reason. - Attachment metadata was copied without the files behind it, so a seeded thread rendered an image whose request 404s. Report the referenced ids and copy the matching files alongside the rows. - Orphaned `provider_session_runtime` rows survived the seed naming threads it had just deleted, which the session reaper then tried to stop against a provider instance the worktree may not define. - `--threads` had no upper bound, so a large enough value died with "too many SQL variables" after the target was already emptied. Also corrects the projector-cursor comment: `orchestration_events.sequence` is AUTOINCREMENT, so emptying the log does not reset its high-water mark and sequence does not restart at 1. Zero remains the right cursor, for the reason now stated. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
1 parent
180070865e
commit
373e7919d1
9 files changed
+500
-24
No files matched your search
+92
-5
@@ -18,14 +18,17 @@ import { Command, Flag } from "effect/unstable/cli";
|
||||
import { resolveWorktreeT3Home } from "@t3tools/shared/devHome";
|
||||
|
||||
import { DevSeedError, seedDevDatabase } from "./lib/dev-seed.ts";
|
||||
import { findRunningServerPid } from "./lib/server-runtime-probe.ts";
|
||||
|
||||
const DEFAULT_THREAD_LIMIT = 25;
|
||||
const DEFAULT_ACTIVITY_LIMIT = 200;
|
||||
/** SQLite's default SQLITE_MAX_VARIABLE_NUMBER; one bound parameter per thread. */
|
||||
const MAX_THREAD_LIMIT = 32_766;
|
||||
|
||||
class DevSeedTargetError extends Schema.TaggedErrorClass<DevSeedTargetError>()(
|
||||
"DevSeedTargetError",
|
||||
{
|
||||
reason: Schema.Literals(["shared-home", "missing-target", "not-a-worktree"]),
|
||||
reason: Schema.Literals(["shared-home", "missing-target", "not-a-worktree", "server-running"]),
|
||||
detail: Schema.String,
|
||||
},
|
||||
) {
|
||||
@@ -46,6 +49,13 @@ class DevSeedTargetError extends Schema.TaggedErrorClass<DevSeedTargetError>()(
|
||||
"Not inside a git worktree, so there is no worktree-local data directory to seed.",
|
||||
"Pass --to <base-dir> to choose one explicitly.",
|
||||
].join("\n");
|
||||
case "server-running":
|
||||
return [
|
||||
`A T3 Code server (pid ${this.detail}) is running against this data directory.`,
|
||||
"Seeding replaces its projections and empties its event log while it holds them open,",
|
||||
"which leaves the running server's in-memory read model describing rows that no longer exist.",
|
||||
"Stop it, run the seed, then start it again.",
|
||||
].join("\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,6 +63,54 @@ class DevSeedTargetError extends Schema.TaggedErrorClass<DevSeedTargetError>()(
|
||||
const stateDbPath = (path: Path.Path, baseDir: string) =>
|
||||
path.join(baseDir, "userdata", "state.sqlite");
|
||||
|
||||
/**
|
||||
* Copies the files behind the copied messages' attachment references.
|
||||
*
|
||||
* The rows carry only metadata; the bytes sit in a flat directory beside the
|
||||
* database as `<attachmentId><ext>` (apps/server/src/attachmentStore.ts). Copy
|
||||
* the rows alone and a seeded thread renders an image whose request 404s.
|
||||
*
|
||||
* Matched by directory listing rather than by reconstructing the extension: the
|
||||
* server infers it from mime type and file name at upload, and duplicating that
|
||||
* inference here would rot independently of it.
|
||||
*/
|
||||
const copyAttachments = Effect.fn("devSeed.copyAttachments")(function* (input: {
|
||||
readonly sourceDir: string;
|
||||
readonly targetDir: string;
|
||||
readonly attachmentIds: ReadonlyArray<string>;
|
||||
}) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
if (input.attachmentIds.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const entries = yield* fileSystem
|
||||
.readDirectory(input.sourceDir)
|
||||
.pipe(Effect.orElseSucceed(() => [] as Array<string>));
|
||||
if (entries.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const wanted = new Set(input.attachmentIds);
|
||||
const matches = entries.filter((entry) => wanted.has(path.parse(entry).name));
|
||||
if (matches.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
yield* fileSystem.makeDirectory(input.targetDir, { recursive: true });
|
||||
// Attachments are decoration on a dev fixture: one unreadable file should
|
||||
// leave the rest of the seed intact rather than fail a completed copy.
|
||||
const copied = yield* Effect.forEach(matches, (entry) =>
|
||||
fileSystem.copyFile(path.join(input.sourceDir, entry), path.join(input.targetDir, entry)).pipe(
|
||||
Effect.as(1),
|
||||
Effect.orElseSucceed(() => 0),
|
||||
),
|
||||
);
|
||||
return copied.reduce((total, one) => total + one, 0);
|
||||
});
|
||||
|
||||
const devSeedCli = Command.make("dev-seed", {
|
||||
from: Flag.string("from").pipe(
|
||||
Flag.withDescription(
|
||||
@@ -68,12 +126,17 @@ const devSeedCli = Command.make("dev-seed", {
|
||||
Flag.optional,
|
||||
Flag.map(Option.getOrUndefined),
|
||||
),
|
||||
// Bounded: SQLite reads a negative LIMIT as "no limit", which would quietly
|
||||
// turn a capped copy into a full-table one.
|
||||
// Bounded below: SQLite reads a negative LIMIT as "no limit", which would
|
||||
// quietly turn a capped copy into a full-table one. Bounded above because
|
||||
// every selected thread becomes one bound parameter in the copy's `IN (...)`,
|
||||
// and SQLite's compiled-in ceiling is 32766 — past it the seed dies with
|
||||
// "too many SQL variables" after the target has already been emptied.
|
||||
threads: Flag.integer("threads").pipe(
|
||||
Flag.withSchema(Schema.Int.check(Schema.isGreaterThan(0))),
|
||||
Flag.withSchema(
|
||||
Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(MAX_THREAD_LIMIT)),
|
||||
),
|
||||
Flag.withDescription(
|
||||
`How many recent threads to copy (default ${String(DEFAULT_THREAD_LIMIT)}).`,
|
||||
`How many recent threads to copy (default ${String(DEFAULT_THREAD_LIMIT)}, max ${String(MAX_THREAD_LIMIT)}).`,
|
||||
),
|
||||
Flag.withDefault(DEFAULT_THREAD_LIMIT),
|
||||
),
|
||||
@@ -117,6 +180,19 @@ const devSeedCli = Command.make("dev-seed", {
|
||||
return yield* new DevSeedTargetError({ reason: "missing-target", detail: targetDbPath });
|
||||
}
|
||||
|
||||
// SQLite locking is not enough on its own: the seed's transaction can take
|
||||
// the write lock between a running server's own writes and commit cleanly.
|
||||
// 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);
|
||||
if (Option.isSome(runningPid)) {
|
||||
return yield* new DevSeedTargetError({
|
||||
reason: "server-running",
|
||||
detail: String(runningPid.value),
|
||||
});
|
||||
}
|
||||
|
||||
const seededAt = yield* Effect.map(DateTime.now, DateTime.formatIso);
|
||||
const summary = yield* Effect.try({
|
||||
try: () =>
|
||||
@@ -130,6 +206,12 @@ const devSeedCli = Command.make("dev-seed", {
|
||||
catch: (cause) => cause as DevSeedError,
|
||||
});
|
||||
|
||||
const copiedAttachments = yield* copyAttachments({
|
||||
sourceDir: path.join(sourceBaseDir, "userdata", "attachments"),
|
||||
targetDir: path.join(targetBaseDir, "userdata", "attachments"),
|
||||
attachmentIds: summary.attachmentIds,
|
||||
});
|
||||
|
||||
yield* Console.log(
|
||||
[
|
||||
`Seeded ${targetDbPath}`,
|
||||
@@ -139,6 +221,11 @@ const devSeedCli = Command.make("dev-seed", {
|
||||
` messages ${String(summary.messages)}`,
|
||||
` activity ${String(summary.activities)}`,
|
||||
` turns ${String(summary.turns)} sessions ${String(summary.sessions)}`,
|
||||
...(summary.attachmentIds.length > 0
|
||||
? [
|
||||
` files ${String(copiedAttachments)}/${String(summary.attachmentIds.length)} attachment(s)`,
|
||||
]
|
||||
: []),
|
||||
...(summary.skippedColumns.length > 0
|
||||
? [
|
||||
` note: skipped ${String(summary.skippedColumns.length)} column(s) absent from the target schema`,
|
||||
|
||||
@@ -31,7 +31,7 @@ function createSchema(
|
||||
${options.withMonitor ? ", monitor_json TEXT" : ""})`);
|
||||
database.exec(`CREATE TABLE projection_thread_messages (
|
||||
message_id TEXT PRIMARY KEY, thread_id TEXT NOT NULL, role TEXT NOT NULL,
|
||||
text TEXT NOT NULL, is_streaming INTEGER NOT NULL,
|
||||
text TEXT NOT NULL, is_streaming INTEGER NOT NULL, attachments_json TEXT,
|
||||
created_at TEXT NOT NULL, updated_at TEXT NOT NULL)`);
|
||||
database.exec(`CREATE TABLE projection_thread_activities (
|
||||
activity_id TEXT PRIMARY KEY, thread_id TEXT NOT NULL, tone TEXT NOT NULL,
|
||||
@@ -42,7 +42,8 @@ function createSchema(
|
||||
active_turn_id TEXT, last_error TEXT, updated_at TEXT NOT NULL)`);
|
||||
database.exec(`CREATE TABLE projection_turns (
|
||||
row_id INTEGER PRIMARY KEY AUTOINCREMENT, thread_id TEXT NOT NULL, turn_id TEXT,
|
||||
state TEXT NOT NULL, requested_at TEXT NOT NULL, checkpoint_files_json TEXT NOT NULL,
|
||||
state TEXT NOT NULL, requested_at TEXT NOT NULL, completed_at TEXT,
|
||||
checkpoint_files_json TEXT NOT NULL,
|
||||
UNIQUE (thread_id, turn_id))`);
|
||||
database.exec(`CREATE TABLE projection_thread_proposed_plans (
|
||||
plan_id TEXT PRIMARY KEY, thread_id TEXT NOT NULL, plan_markdown TEXT NOT NULL,
|
||||
@@ -55,6 +56,9 @@ function createSchema(
|
||||
database.exec(`CREATE TABLE orchestration_events (
|
||||
sequence INTEGER PRIMARY KEY AUTOINCREMENT, event_id TEXT NOT NULL UNIQUE,
|
||||
stream_id TEXT NOT NULL, event_type TEXT NOT NULL, payload_json TEXT NOT NULL)`);
|
||||
database.exec(`CREATE TABLE provider_session_runtime (
|
||||
thread_id TEXT PRIMARY KEY, provider_name TEXT NOT NULL, adapter_key TEXT NOT NULL,
|
||||
status TEXT NOT NULL, last_seen_at TEXT NOT NULL)`);
|
||||
}
|
||||
|
||||
/** Source DB with `threadCount` threads, oldest first so recency ordering is testable. */
|
||||
@@ -95,18 +99,35 @@ function makeSource(
|
||||
)
|
||||
.run(threadId, "p1", `Thread ${String(index)}`, `turn-${threadId}`, at, at, at, 4, 2, "{}");
|
||||
}
|
||||
// The newest thread is left mid-turn, as a copy taken while an agent is
|
||||
// working would be: a running turn with no completion, and a message still
|
||||
// streaming into it.
|
||||
const midFlight = index === threadCount - 1;
|
||||
database
|
||||
.prepare(
|
||||
`INSERT INTO projection_turns (thread_id, turn_id, state, requested_at, checkpoint_files_json)
|
||||
VALUES (?,?,?,?,'[]')`,
|
||||
`INSERT INTO projection_turns (thread_id, turn_id, state, requested_at, completed_at, checkpoint_files_json)
|
||||
VALUES (?,?,?,?,?,'[]')`,
|
||||
)
|
||||
.run(threadId, `turn-${threadId}`, "completed", at);
|
||||
.run(
|
||||
threadId,
|
||||
`turn-${threadId}`,
|
||||
midFlight ? "running" : "completed",
|
||||
at,
|
||||
midFlight ? null : at,
|
||||
);
|
||||
database
|
||||
.prepare(`INSERT INTO projection_thread_sessions VALUES (?,'running','claude',?,'boom',?)`)
|
||||
.run(threadId, `turn-${threadId}`, at);
|
||||
database
|
||||
.prepare(`INSERT INTO projection_thread_messages VALUES (?,?, 'user','hello',0,?,?)`)
|
||||
.run(`m-${threadId}`, threadId, at, at);
|
||||
.prepare(`INSERT INTO projection_thread_messages VALUES (?,?, 'user','hello',?,?,?,?)`)
|
||||
.run(
|
||||
`m-${threadId}`,
|
||||
threadId,
|
||||
midFlight ? 1 : 0,
|
||||
JSON.stringify([{ type: "image", id: `${threadId}-image`, name: "shot.png" }]),
|
||||
at,
|
||||
at,
|
||||
);
|
||||
for (let a = 0; a < activitiesPerThread; a += 1) {
|
||||
database
|
||||
.prepare(`INSERT INTO projection_thread_activities VALUES (?,?,'neutral','tool','ran',?,?)`)
|
||||
@@ -130,6 +151,11 @@ function makeTarget(path: string, options?: { readonly dropProposedPlans?: boole
|
||||
.prepare(`INSERT INTO orchestration_events (event_id, stream_id, event_type, payload_json)
|
||||
VALUES ('old-event','stale-thread','thread.created','{}')`)
|
||||
.run();
|
||||
// A binding for a thread the seed is about to delete.
|
||||
database
|
||||
.prepare(`INSERT INTO provider_session_runtime
|
||||
VALUES ('stale-thread','claude','claude-code','running','${SEEDED_AT}')`)
|
||||
.run();
|
||||
if (options?.dropProposedPlans) {
|
||||
// A target far enough behind that a whole table is missing (migration 013).
|
||||
database.exec("DROP TABLE projection_thread_proposed_plans");
|
||||
@@ -271,6 +297,87 @@ describe("seedDevDatabase", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// A copied running turn has no agent left to finish it. The session override
|
||||
// alone does not cover this: the turn is read independently, and an unsettled
|
||||
// one keeps the thread spinning and its timeline unfoldable forever.
|
||||
it("settles turns copied mid-flight", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 3,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
const turns = query<{ state: string; completed_at: string | null }>(
|
||||
target,
|
||||
"SELECT state, completed_at FROM projection_turns",
|
||||
);
|
||||
assert.isAbove(turns.length, 0);
|
||||
for (const turn of turns) {
|
||||
assert.notEqual(turn.state, "running");
|
||||
assert.isNotNull(turn.completed_at);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Nothing will ever stream into a copied message, so a carried-over flag
|
||||
// renders a caret that never resolves.
|
||||
it("clears the streaming flag on copied messages", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 3,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
const streaming = query<{ count: number }>(
|
||||
target,
|
||||
"SELECT COUNT(*) count FROM projection_thread_messages WHERE is_streaming <> 0",
|
||||
);
|
||||
assert.equal(streaming[0]?.count, 0);
|
||||
});
|
||||
});
|
||||
|
||||
// The rows carry attachment metadata but the bytes live on disk, so the
|
||||
// caller has to be told which files to bring along.
|
||||
it("reports the attachment ids the copied messages reference", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
const summary = seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 2,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual([...summary.attachmentIds].sort(), ["t3-image", "t4-image"]);
|
||||
});
|
||||
});
|
||||
|
||||
// Bindings are keyed by thread id and are not copied; left behind they name
|
||||
// threads the seed just deleted, which the session reaper then tries to stop.
|
||||
it("clears provider runtime bindings the seed orphans", () => {
|
||||
withDatabases(({ source, target }) => {
|
||||
seedDevDatabase({
|
||||
sourceDbPath: source,
|
||||
targetDbPath: target,
|
||||
threadLimit: 1,
|
||||
activityLimit: 10,
|
||||
seededAt: SEEDED_AT,
|
||||
});
|
||||
|
||||
const [bindings] = query<{ count: number }>(
|
||||
target,
|
||||
"SELECT COUNT(*) count FROM provider_session_runtime",
|
||||
);
|
||||
assert.equal(bindings?.count, 0);
|
||||
});
|
||||
});
|
||||
|
||||
it("caps activities per thread, keeping the newest", () => {
|
||||
withDatabases(
|
||||
({ source, target }) => {
|
||||
|
||||
+120
-9
@@ -8,9 +8,13 @@
|
||||
* target recorded, so replaying its retained events over them would resurrect
|
||||
* threads and projects it had deleted; copying a *partial* source range is
|
||||
* worse still, since the projector would replay a tail whose creating events
|
||||
* are missing. With the log empty and every projector cursor at 0 (the cursor
|
||||
* is exclusive), bootstrap streams nothing and leaves the copied rows alone.
|
||||
* See .agents/skills/test-t3-app/references/sqlite-fixtures.md.
|
||||
* are missing. With the log empty and every projector cursor at 0, bootstrap
|
||||
* streams nothing and leaves the copied rows alone.
|
||||
*
|
||||
* Everything that would otherwise wait on an agent is settled too — sessions,
|
||||
* turns, streaming messages, badge counts, provider bindings — because no agent
|
||||
* process comes with the copy. See
|
||||
* .agents/skills/test-t3-app/references/sqlite-fixtures.md.
|
||||
*/
|
||||
|
||||
import * as NodeSqlite from "node:sqlite";
|
||||
@@ -40,6 +44,12 @@ export interface DevSeedSummary {
|
||||
readonly turns: number;
|
||||
readonly sessions: number;
|
||||
readonly skippedColumns: ReadonlyArray<string>;
|
||||
/**
|
||||
* Attachment ids the copied messages reference. The rows carry the metadata
|
||||
* but the bytes live on disk beside the database, so the caller has to copy
|
||||
* those files too — otherwise a seeded thread renders an image that 404s.
|
||||
*/
|
||||
readonly attachmentIds: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
export class DevSeedError extends Error {
|
||||
@@ -86,6 +96,52 @@ const hasTable = (database: NodeSqlite.DatabaseSync, table: string): boolean =>
|
||||
const hasColumn = (database: NodeSqlite.DatabaseSync, table: string, column: string): boolean =>
|
||||
columnsOf(database, table).includes(column);
|
||||
|
||||
/**
|
||||
* Attachment ids referenced by the copied messages, so the caller can copy the
|
||||
* files that back them. `attachments_json` is a JSON array of ChatAttachment
|
||||
* (packages/contracts/src/orchestration.ts); anything unparseable is skipped
|
||||
* rather than failing the seed, since a missing image is a cosmetic problem and
|
||||
* an aborted seed is not.
|
||||
*/
|
||||
function collectAttachmentIds(
|
||||
target: NodeSqlite.DatabaseSync,
|
||||
threadIds: ReadonlyArray<string>,
|
||||
): ReadonlyArray<string> {
|
||||
if (
|
||||
threadIds.length === 0 ||
|
||||
!hasColumn(target, "projection_thread_messages", "attachments_json")
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
const ids = new Set<string>();
|
||||
const rows = target
|
||||
.prepare(
|
||||
`SELECT attachments_json FROM projection_thread_messages
|
||||
WHERE attachments_json IS NOT NULL AND thread_id IN (${placeholders(threadIds.length)})`,
|
||||
)
|
||||
.iterate(...threadIds) as Iterable<{ attachments_json: unknown }>;
|
||||
for (const row of rows) {
|
||||
if (typeof row.attachments_json !== "string") {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(row.attachments_json);
|
||||
if (!Array.isArray(parsed)) {
|
||||
continue;
|
||||
}
|
||||
for (const attachment of parsed) {
|
||||
const id: unknown = (attachment as { id?: unknown } | null)?.id;
|
||||
if (typeof id === "string" && id.length > 0) {
|
||||
ids.add(id);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// A row whose JSON does not parse cannot name a file to copy.
|
||||
}
|
||||
}
|
||||
return [...ids];
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies rows for `table` whose `keyColumn` is in `keys`, optionally keeping
|
||||
* only the newest `perKeyLimit` rows per key.
|
||||
@@ -160,6 +216,35 @@ function copyRows(input: {
|
||||
return { copied, skipped };
|
||||
}
|
||||
|
||||
/**
|
||||
* Settles turns copied mid-flight, matching what the server does to a turn
|
||||
* whose session leaves "running": `settledTurnStateForSessionStatus` in
|
||||
* apps/server/src/orchestration/Layers/ProjectionPipeline.ts maps the "stopped"
|
||||
* status the sessions are copied with to "interrupted".
|
||||
*
|
||||
* An UPDATE rather than a copy override, because only the rows that were
|
||||
* actually running should change; the rest keep their real recorded state.
|
||||
*/
|
||||
function settleRunningTurns(
|
||||
target: NodeSqlite.DatabaseSync,
|
||||
threadIds: ReadonlyArray<string>,
|
||||
): void {
|
||||
if (threadIds.length === 0 || !hasColumn(target, "projection_turns", "state")) {
|
||||
return;
|
||||
}
|
||||
// completed_at is what marks a turn settled alongside its state; a running
|
||||
// turn has none, and leaving it null keeps the thread unsettled regardless.
|
||||
const setCompletedAt = hasColumn(target, "projection_turns", "completed_at")
|
||||
? `, completed_at = COALESCE(completed_at, requested_at)`
|
||||
: "";
|
||||
target
|
||||
.prepare(
|
||||
`UPDATE projection_turns SET state = 'interrupted'${setCompletedAt}
|
||||
WHERE state = 'running' AND thread_id IN (${placeholders(threadIds.length)})`,
|
||||
)
|
||||
.run(...threadIds);
|
||||
}
|
||||
|
||||
export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary {
|
||||
let source: NodeSqlite.DatabaseSync;
|
||||
try {
|
||||
@@ -249,6 +334,15 @@ export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary {
|
||||
if (hasTable(target, "orchestration_command_receipts")) {
|
||||
target.exec("DELETE FROM orchestration_command_receipts");
|
||||
}
|
||||
// Provider bindings are keyed by thread id and are not copied (no agent
|
||||
// process comes with the seed). Left in place they outlive the threads they
|
||||
// name: ProviderSessionReaper sweeps every non-stopped binding, finds no
|
||||
// thread behind it, and so never hits its active-turn guard — it just tries
|
||||
// to stop a session for a thread that no longer exists, against a provider
|
||||
// instance this worktree may not even define.
|
||||
if (hasTable(target, "provider_session_runtime")) {
|
||||
target.exec("DELETE FROM provider_session_runtime");
|
||||
}
|
||||
|
||||
const projects = record(
|
||||
copyRows({
|
||||
@@ -281,6 +375,12 @@ export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary {
|
||||
omitColumns: ["row_id"],
|
||||
}),
|
||||
);
|
||||
// A thread copied mid-turn has no agent to finish it. The session status is
|
||||
// forced to "stopped" below, but the turn is read independently: a
|
||||
// `state = 'running'` turn keeps the thread unsettled and unfoldable
|
||||
// forever (deriveUnsettledTurnId in MessagesTimeline.logic.ts). Interrupted
|
||||
// is what the server itself settles an abandoned turn to.
|
||||
settleRunningTurns(target, threadIds);
|
||||
const messages = record(
|
||||
copyRows({
|
||||
source,
|
||||
@@ -288,6 +388,9 @@ export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary {
|
||||
table: "projection_thread_messages",
|
||||
keyColumn: "thread_id",
|
||||
keys: threadIds,
|
||||
// Same reason: a message copied while streaming has nothing left to
|
||||
// stream into it, so it would render with a caret that never resolves.
|
||||
overrides: { is_streaming: 0 },
|
||||
}),
|
||||
);
|
||||
const activities = record(
|
||||
@@ -329,12 +432,15 @@ export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary {
|
||||
// Required: computeSnapshotSequence returns 0 unless every projector has a
|
||||
// row, which makes every shell snapshot advertise sequence 0.
|
||||
//
|
||||
// The cursor is exclusive (`WHERE sequence > cursor`) and the event log was
|
||||
// just emptied, so `sequence` restarts at 1. Any positive cursor would make
|
||||
// each projector skip that many of the user's first real events — and a
|
||||
// different count per projector, leaving the projections permanently
|
||||
// inconsistent. Every projector starts at 0: nothing to skip, nothing to
|
||||
// replay.
|
||||
// Zero, not the source's cursors. `orchestration_events.sequence` is
|
||||
// AUTOINCREMENT, so emptying the log does not reset its high-water mark and
|
||||
// the next real event continues from wherever the target left off. A cursor
|
||||
// carried over from the source is unrelated to that number: it could sit
|
||||
// above it (each projector then silently skipping a different count of the
|
||||
// user's first real events, desynchronizing the projections for good) or
|
||||
// below it (replaying events over rows they never produced). Zero is below
|
||||
// every future sequence, so bootstrap streams the empty log, finds nothing,
|
||||
// and leaves the copied rows exactly as they are.
|
||||
const insertState = target.prepare(
|
||||
`INSERT OR REPLACE INTO projection_state (projector, last_applied_sequence, updated_at)
|
||||
VALUES (?, 0, ?)`,
|
||||
@@ -343,6 +449,10 @@ export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary {
|
||||
insertState.run(projector, options.seededAt);
|
||||
}
|
||||
|
||||
// Read back inside the transaction: these are the rows that were just
|
||||
// written, not the source's, so a column the target lacks is already gone.
|
||||
const attachmentIds = collectAttachmentIds(target, threadIds);
|
||||
|
||||
target.exec("COMMIT");
|
||||
|
||||
return {
|
||||
@@ -353,6 +463,7 @@ export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary {
|
||||
turns,
|
||||
sessions,
|
||||
skippedColumns: [...new Set(skipped)].sort(),
|
||||
attachmentIds,
|
||||
};
|
||||
} catch (cause) {
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
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 { findRunningServerPid } from "./server-runtime-probe.ts";
|
||||
|
||||
/** A pid that cannot belong to a live process (above the usual pid_max). */
|
||||
const DEAD_PID = 0x7ffffffe;
|
||||
|
||||
const writeRuntimeState = Effect.fn(function* (input: {
|
||||
readonly baseDir: string;
|
||||
readonly stateDir: "dev" | "userdata";
|
||||
readonly contents: string;
|
||||
}) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const directory = path.join(input.baseDir, input.stateDir);
|
||||
yield* fileSystem.makeDirectory(directory, { recursive: true });
|
||||
yield* fileSystem.writeFileString(path.join(directory, "server-runtime.json"), input.contents);
|
||||
});
|
||||
|
||||
const runtimeStateJson = (pid: number) =>
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
pid,
|
||||
port: 16_602,
|
||||
origin: "http://127.0.0.1:16602",
|
||||
startedAt: "2026-07-20T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const makeBaseDir = Effect.fnUntraced(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
return yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-runtime-probe-test-" });
|
||||
});
|
||||
|
||||
describe("findRunningServerPid", () => {
|
||||
it.effect("reports the pid of a live server in the dev state directory", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = yield* makeBaseDir();
|
||||
yield* writeRuntimeState({
|
||||
baseDir,
|
||||
stateDir: "dev",
|
||||
contents: runtimeStateJson(process.pid),
|
||||
});
|
||||
|
||||
assert.equal(Option.getOrThrow(yield* findRunningServerPid(baseDir)), process.pid);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
// An explicit --home-dir puts runtime state in userdata instead, and the
|
||||
// caller of a seed has no reason to know which of the two was used.
|
||||
it.effect("also finds a live server in the userdata state directory", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = yield* makeBaseDir();
|
||||
yield* writeRuntimeState({
|
||||
baseDir,
|
||||
stateDir: "userdata",
|
||||
contents: runtimeStateJson(process.pid),
|
||||
});
|
||||
|
||||
assert.equal(Option.getOrThrow(yield* findRunningServerPid(baseDir)), process.pid);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
// A server killed with SIGKILL never clears its state file. Treating that as
|
||||
// "running" would block seeding for good, with nothing to clear it.
|
||||
it.effect("ignores a state file whose process is gone", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = yield* makeBaseDir();
|
||||
yield* writeRuntimeState({ baseDir, stateDir: "dev", contents: runtimeStateJson(DEAD_PID) });
|
||||
|
||||
assert.isTrue(Option.isNone(yield* findRunningServerPid(baseDir)));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
// A half-written file says nothing about liveness either way.
|
||||
it.effect("ignores a state file it cannot parse", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = yield* makeBaseDir();
|
||||
yield* writeRuntimeState({ baseDir, stateDir: "dev", contents: "{not json" });
|
||||
|
||||
assert.isTrue(Option.isNone(yield* findRunningServerPid(baseDir)));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("reports nothing when no state files exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const baseDir = yield* makeBaseDir();
|
||||
assert.isTrue(Option.isNone(yield* findRunningServerPid(baseDir)));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* Whether a T3 Code server is currently running against a data directory.
|
||||
*
|
||||
* A maintained copy of the parts of `apps/server/src/serverRuntimeState.ts` that
|
||||
* host scripts need: that package exposes no importable surface to `scripts/`,
|
||||
* the same reason `./projection-tables.ts` exists. Only the fields read here are
|
||||
* modelled, so a server that adds a field stays readable.
|
||||
*/
|
||||
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({
|
||||
pid: Schema.Int,
|
||||
});
|
||||
|
||||
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
|
||||
* permission and existence checks without delivering a signal, which is what
|
||||
* distinguishes "still running" from "left this here on the way out".
|
||||
*
|
||||
* PIDs are reused eventually, so a false positive is possible in principle. For
|
||||
* a guard on a destructive local-dev command that errs the safe way: the worst
|
||||
* case is being told to stop a server that is already stopped.
|
||||
*/
|
||||
const isPidLive = (pid: number): boolean => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (cause) {
|
||||
// EPERM means the process exists but belongs to another user.
|
||||
return (cause as NodeJS.ErrnoException).code === "EPERM";
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* The pid of a live server under `baseDir`, if any.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
return Option.none<number>();
|
||||
});
|
||||
Reference in new issue
Block a user