Skip to content
80 changes: 79 additions & 1 deletion apps/server/scripts/migrate-dev-db.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import * as SqlClient from "effect/sql/SqlClient";

import { runMigrations } from "../src/persistence/Migrations.ts";
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import { runMigrateDevDb } from "./migrate-dev-db.ts";
import { dropResumableFamilies, runMigrateDevDb } from "./migrate-dev-db.ts";

const withDatabase = <A, E, R>(
databasePath: string,
Expand Down Expand Up @@ -102,6 +102,8 @@ const createFixtureSource = Effect.fn("createMigrateDevDbFixtureSource")(functio
["subagent-parent", "project-kept", "completed", "{}", "2026-08-05"],
["subagent-child", "project-kept", "completed", subagentPayload, "2026-08-05"],
["deleted-project-thread", "project-deleted", "completed", "{}", "2026-08-05"],
// Finished, but startup recovery would deliver its unread steer and start a turn.
["steer-thread", "project-kept", "completed", "{}", "2026-08-09"],
] as const;
for (const [threadId, projectId, runStatus, payload, updatedAt] of threads) {
yield* sql`INSERT INTO orchestration_v2_projection_threads
Expand All @@ -114,6 +116,10 @@ const createFixtureSource = Effect.fn("createMigrateDevDbFixtureSource")(functio
(event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at, actor_kind, payload_json, metadata_json, application_event_version)
VALUES (${`event-${threadId}`}, 'thread', ${threadId}, 0, 'thread.created', '2026-08-01', 'user', '{}', '{}', 2)`;
}
yield* sql`INSERT INTO orchestration_v2_projection_turn_items
(turn_item_id, thread_id, run_id, ordinal, type, status, updated_at, payload_json)
VALUES ('steer-item', 'steer-thread', 'run-steer-thread', 2, 'user_message', 'pending',
'2026-08-09', '{"inputIntent":"steer"}')`;
// A V1 thread the server already imported must not trip the legacy guard.
yield* sql`INSERT INTO projection_threads
(thread_id, project_id, title, model_selection_json, runtime_mode, created_at, updated_at)
Expand Down Expand Up @@ -244,6 +250,78 @@ it.layer(NodeServices.layer)("migrate-dev-db", (it) => {
}),
);

it.effect("drops resumable families from a seed in place, the pending steer included", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-resumable-" });
const sharedHome = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-home-" });
const database = yield* createFixtureSource(dir);

assert.equal(yield* dropResumableFamilies(database, { sharedHome }), 4);
const { threads, sessions } = yield* withDatabase(
database,
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
return {
threads: yield* sql<{ thread_id: string }>`
SELECT thread_id FROM orchestration_v2_projection_threads ORDER BY thread_id`,
sessions: yield* sql<{ provider_session_id: string }>`
SELECT provider_session_id FROM orchestration_v2_projection_provider_sessions`,
};
}),
);
assert.deepStrictEqual(
threads.map((row) => row.thread_id),
[
"archived-thread",
"deleted-project-thread",
"fork-thread",
"settled-thread",
"stopped-thread",
],
);
assert.deepStrictEqual(
sessions.map((row) => row.provider_session_id),
["session-shared"],
"a session the kept stopped-thread still binds stays with it",
);
assert.equal(yield* dropResumableFamilies(database, { sharedHome }), 0);
}),
);

it.effect("refuses to drop from the shared database through a symlink or a hard link", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const sharedHome = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-shared-" });
const elsewhere = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-link-" });
const fixture = yield* createFixtureSource(sharedHome);
const live = path.join(sharedHome, "userdata", "statev2.sqlite");
yield* fs.makeDirectory(path.dirname(live), { recursive: true });
yield* fs.rename(fixture, live);
const symlink = path.join(elsewhere, "statev2.sqlite");
yield* fs.symlink(live, symlink);
// A hard link has its own path; only the file's identity gives it away.
const hardLink = path.join(elsewhere, "copy.sqlite");
yield* fs.link(live, hardLink);

for (const link of [symlink, hardLink]) {
const refused = yield* Effect.flip(dropResumableFamilies(link, { sharedHome }));
assert.equal(refused._tag, "MigrateDevDbSharedHomeError", link);
}
const threads = yield* withDatabase(
live,
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const [row] = yield* sql<{ n: number }>`
SELECT COUNT(*) AS n FROM orchestration_v2_projection_threads`;
return Number(row?.n ?? 0);
}),
);
assert.equal(threads, 10, "the shared database is untouched");
}),
);

it.effect("never copies an archived thread, and new events append after the source's", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
Expand Down
164 changes: 148 additions & 16 deletions apps/server/scripts/migrate-dev-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { Command, Flag } from "effect/cli";
import * as ProjectionStore from "../src/orchestration-v2/ProjectionStore.ts";
import { rebuildMessageSearch } from "../src/orchestration-v2/messageSearchIndex.ts";
import { runMigrations } from "../src/persistence/Migrations.ts";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";

export class MigrateDevDbNotInWorktreeError extends Schema.TaggedError<MigrateDevDbNotInWorktreeError>()(
Expand Down Expand Up @@ -195,12 +196,19 @@ const ensureNotInUse = Effect.fn("ensureDevDbNotInUse")(function* (databasePath:
}
});

const RECOVERY_KINDS: ReadonlyArray<ProjectionStore.ProjectionRecoveryKind> = [
"queued-runs",
"runtime",
"subagent-results",
"delegated-completions",
];
// Every kind startup recovery resumes, so a copied family never starts work by itself. The record
// fails typecheck when a kind is added and not listed here.
const RECOVERY_KIND_SET = {
"queued-runs": true,
runtime: true,
"restart-continuations": true,
"subagent-results": true,
"delegated-completions": true,
"unread-steers": true,
} satisfies Record<ProjectionStore.ProjectionRecoveryKind, true>;
const RECOVERY_KINDS = Object.keys(
RECOVERY_KIND_SET,
) as ReadonlyArray<ProjectionStore.ProjectionRecoveryKind>;

const CLEARED_TABLES: ReadonlyArray<string> = [
"scheduled_tasks",
Expand Down Expand Up @@ -322,26 +330,139 @@ const copySourceSlice = Effect.fn("copyDevDbSourceSlice")(function* (sourcePath:
yield* sql`DETACH DATABASE src`;
});

const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigrateDevDbInput) {
/**
* Threads a server started on this database would resume by itself: every startup recovery kind,
* plus latest-run failures and recovery choices, which usage-limit recovery can resume.
*/
export const resumableThreadIds = Effect.fn("resumableDevDbThreadIds")(function* () {
const sql = yield* SqlClient.SqlClient;

// Usage-limit recovery also depends on settings; exclude latest-run failures and recovery choices.
const projections = yield* ProjectionStore.ProjectionStoreV2;
const recoveryThreadIds = yield* Effect.forEach(RECOVERY_KINDS, (kind) =>
const recovery = yield* Effect.forEach(RECOVERY_KINDS, (kind) =>
projections.getRecoveryThreadIds(kind),
);
yield* sql`CREATE TEMP TABLE live_threads (thread_id TEXT PRIMARY KEY)`;
for (const threadId of new Set(recoveryThreadIds.flat())) {
yield* sql`INSERT INTO live_threads (thread_id) VALUES (${threadId})`;
}
yield* sql`INSERT OR IGNORE INTO live_threads (thread_id)
const failedOrRecovering = yield* sql<{ thread_id: string }>`
SELECT r.thread_id FROM orchestration_v2_projection_runs r
WHERE r.status = 'failed' AND r.ordinal = (
SELECT MAX(latest.ordinal) FROM orchestration_v2_projection_runs latest
WHERE latest.thread_id = r.thread_id)
UNION
SELECT thread_id FROM orchestration_v2_projection_threads
WHERE json_extract(payload_json, '$.limitRecovery') IS NOT NULL`;
return [
...new Set<string>([...recovery.flat(), ...failedOrRecovering.map((row) => row.thread_id)]),
];
});

export class MigrateDevDbResumableWorkError extends Schema.TaggedError<MigrateDevDbResumableWorkError>()(
"MigrateDevDbResumableWorkError",
{ databasePath: Schema.String, threads: Schema.Number },
) {
override get message() {
return `${this.databasePath} still holds ${this.threads} threads a server would resume.`;
}
}

/**
* Drops, in place, every thread family a server started on `databasePath` would resume, and fails
* if any remain. A database seeded by an older checkout can miss a recovery kind added since.
*/
export const dropResumableFamilies = Effect.fn("dropResumableDevDbFamilies")(function* (
databasePath: string,
options: RunMigrateDevDbOptions = {},
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const platform = yield* HostProcess.Platform;
// A symlink, `..` or another letter case can name the live database; compare where they lead.
const resolve = (file: string) =>
fs.realPath(file).pipe(
Effect.catch(() =>
fs
.realPath(path.dirname(file))
.pipe(Effect.map((dir) => path.join(dir, path.basename(file)))),
),
Effect.orElseSucceed(() => path.resolve(file)),
);
const comparable = (resolved: string) =>
platform === "linux" ? resolved : resolved.toLowerCase();
// A hard link has its own path, so the file itself is compared too.
const identity = (file: string) =>
fs.stat(file).pipe(
Effect.map((info) => Option.map(info.ino, (ino) => `${info.dev}:${ino}`)),
Effect.orElseSucceed(() => Option.none<string>()),
);
const sharedHome = path.resolve(options.sharedHome ?? path.join(NodeOS.homedir(), ".t3"));
const liveDatabase = path.join(sharedHome, "userdata", "statev2.sqlite");
const [target, live] = yield* Effect.all([resolve(databasePath), resolve(liveDatabase)]);
const targetIdentity = yield* identity(target);
const liveIdentities = yield* Effect.forEach(
[liveDatabase, `${liveDatabase}-wal`, `${liveDatabase}-shm`],
identity,
);
if (
comparable(target) === comparable(live) ||
(Option.isSome(targetIdentity) &&
liveIdentities.some(
(candidate) => Option.isSome(candidate) && candidate.value === targetIdentity.value,
))
) {
return yield* new MigrateDevDbSharedHomeError();
}
// Beside the real file, where a running server keeps its runtime state.
yield* ensureNotInUse(target);
return yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const resumable = yield* resumableThreadIds();
if (resumable.length > 0) {
yield* sql`CREATE TEMP TABLE resumable_families (thread_id TEXT PRIMARY KEY)`;
yield* sql`INSERT OR IGNORE INTO resumable_families
SELECT family.thread_id FROM orchestration_v2_projection_threads family
WHERE COALESCE(json_extract(family.payload_json, '$.lineage.rootThreadId'), family.thread_id) IN (
SELECT COALESCE(json_extract(payload_json, '$.lineage.rootThreadId'), thread_id)
FROM orchestration_v2_projection_threads WHERE thread_id IN ${sql.in(resumable)})`;
yield* sql.withTransaction(
Effect.gen(function* () {
for (const { name } of yield* sql<{ name: string }>`
SELECT m.name FROM sqlite_master m, pragma_table_info(m.name) c
WHERE m.type = 'table' AND c.name = 'thread_id'
AND m.name <> ${PROVIDER_SESSIONS_TABLE}`) {
yield* sql`DELETE FROM ${sql(name)}
WHERE thread_id IN (SELECT thread_id FROM resumable_families)`;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
// A session a kept thread still binds stays, as pruning keeps it.
yield* sql`DELETE FROM ${sql(PROVIDER_SESSIONS_TABLE)}
WHERE thread_id IN (SELECT thread_id FROM resumable_families)
AND provider_session_id NOT IN (
SELECT provider_session_id FROM orchestration_v2_projection_provider_session_bindings
WHERE thread_id NOT IN (SELECT thread_id FROM resumable_families)
)`;
yield* sql`DELETE FROM orchestration_v2_projection_context_transfers
WHERE source_thread_id IN (SELECT thread_id FROM resumable_families)
OR target_thread_id IN (SELECT thread_id FROM resumable_families)`;
yield* sql`DELETE FROM orchestration_events WHERE aggregate_kind = 'thread'
AND stream_id IN (SELECT thread_id FROM resumable_families)`;
}),
);
}
const left = yield* resumableThreadIds();
if (left.length > 0) {
return yield* new MigrateDevDbResumableWorkError({ databasePath, threads: left.length });
}
return resumable.length;
}).pipe(
Effect.provide(
ProjectionStore.layer.pipe(Layer.provideMerge(NodeSqliteClient.layer({ filename: target }))),
),
);
});

const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigrateDevDbInput) {
const sql = yield* SqlClient.SqlClient;

yield* sql`CREATE TEMP TABLE live_threads (thread_id TEXT PRIMARY KEY)`;
for (const threadId of yield* resumableThreadIds()) {
yield* sql`INSERT INTO live_threads (thread_id) VALUES (${threadId})`;
}

// Clone or drop whole thread families to preserve fork and subagent lineage reads.
yield* sql`CREATE TEMP TABLE thread_families AS
Expand Down Expand Up @@ -641,9 +762,20 @@ export const migrateDevDbCommand = Command.make(
Flag.optional,
Flag.withDescription("Source database. Defaults to ~/.t3/userdata/statev2.sqlite."),
),
dropResumable: Flag.String("drop-resumable").pipe(
Flag.optional,
Flag.withDescription(
"Only drop, in place, the thread families a server started on this database would resume, and fail if any remain. Copies only; never the live database.",
),
),
},
({ projects, threadsPerProject, baseDir, source }) =>
({ projects, threadsPerProject, baseDir, source, dropResumable }) =>
Effect.gen(function* () {
if (Option.isSome(dropResumable)) {
const dropped = yield* dropResumableFamilies(dropResumable.value);
yield* Console.log(`Dropped ${dropped} resumable threads.`);
return;
}
const result = yield* runMigrateDevDb({
projects,
threadsPerProject,
Expand Down
37 changes: 37 additions & 0 deletions scripts/server-metrics-report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,20 @@ export const Measured = Schema.Struct({
scaling: Schema.optional(Scaling),
streaming: Schema.optional(Window),
soak: Schema.optional(Soak),
/** A server on a copy of the developer's real database, its projects backed by clones. */
busy: Schema.optional(
Schema.Struct({
readyMs: Schema.Number,
projects: Schema.Number,
/** Off-heap MB the server held so its RSS is a long-lived server's; not compared. */
ballastMB: Schema.Number,
rest: Window,
shellMs: Spread,
shellKB: Schema.Number,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
/** Back-to-back turns in a clone, each ending in a checkpoint. */
git: Window,
}),
),
});
export type Measured = typeof Measured.Type;

Expand Down Expand Up @@ -156,6 +170,8 @@ function noiseFloor(metric: string) {
if (metric.endsWith("cpuPct")) return 1;
if (metric.endsWith("wakeupsPerSec")) return 20;
if (metric.endsWith("MB")) return 15;
if (metric.endsWith("KB")) return 20;
if (metric.includes(".shellMs.")) return 50;
if (metric.endsWith("loopDelayP50Ms")) return 2;
if (metric.endsWith("loopDelayP99Ms")) return 5;
if (metric.endsWith("loopDelayMaxMs")) return 20;
Expand Down Expand Up @@ -214,6 +230,8 @@ export function compareMetrics(before: ServerMetrics, after: ServerMetrics, thre
if (
metric === "soak.minutes" ||
metric.endsWith("loopSamples") ||
metric === "busy.projects" ||
metric === "busy.ballastMB" ||
metric.startsWith("scaling.points")
) {
continue;
Expand Down Expand Up @@ -374,3 +392,22 @@ export function heapGrowth(
.slice(0, 25)
.map(({ bytes, ...entry }) => ({ ...entry, MB: round(bytes / 1e6, 2) }));
}

const encodeJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.String));
const spellings: ReadonlyArray<(path: string) => string> = [
(path) => path,
// Inside a JSON string, with every escape JSON applies: backslashes, quotes, control characters.
(path) => encodeJsonString(path).slice(1, -1),
(path) => path.replaceAll("\\", "/"),
];

/** How a path can appear in a database's text: as written, JSON-escaped, with forward slashes. */
export function pathSpellings(path: string) {
return [...new Set(spellings.map((spell) => spell(path)))];
}

/** Each spelling of `from` with the same spelling of `to`, for a textual rewrite. */
export function pathRewrites(from: string, to: string) {
const pairs = new Map(spellings.map((spell) => [spell(from), spell(to)] as const));
return [...pairs];
}
Loading
Loading