Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Drop session_tape once its step metadata has been copied out (#2281)

Regan Bell3b1b34636429
diff --git a/docs/SPEC.md b/docs/SPEC.md
index 5fde3c21b..815f2a2d6 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -174,7 +174,7 @@ Keeping old endpoints, data shapes, and code paths alive next to their replaceme
- **Credential capture redesign** (2026-10-08): The login-as-a-skill handoff planned that "a stale skill calling /v1/keychain/use gets a clear refusal" and that "logins saved under the old capture system still load." Both keep the old system on life support. Remove the endpoint and the old capture system outright; stale skills fail and get fixed. _Status:_ [qm#2146](https://github.com/yc-software/qm/pull/2146) deletes `/v1/keychain/use` (open).
- **Sandbox routing retirement** (2026-10-02): Retiring `sandbox_routing` came with a locked, marker-guarded one-time upgrade import that preserved legacy IDs, explicit nulls, and machine IDs, kept the old table as rollback input, and told operators to keep credentials for legacy-mapped providers. A plain migration would have done. _Status:_ merged in [qm#2019](https://github.com/yc-software/qm/pull/2019).
-- **Session tape beside session entries** (2026-09-16): The tape was meant to replace `session_entries`, but caution kept both. `SESSION_TAPE_MODE` shadow/serve chose between them, exact-transcript annotations were added so the tape could reproduce every historical field, and a verifying, lease-aware operator backfill with dry runs and partial-scan statuses guarded the cutover. We got stuck here for weeks; one migration and a hard cutover would have left one system instead of two. _Status:_ code reads and writes only `session_entries` since [qm#2273](https://github.com/yc-software/qm/pull/2273); `session_tape` is dropped by hand once no older code runs.
+- **Session tape beside session entries** (2026-09-16): The tape was meant to replace `session_entries`, but caution kept both. `SESSION_TAPE_MODE` shadow/serve chose between them, exact-transcript annotations were added so the tape could reproduce every historical field, and a verifying, lease-aware operator backfill with dry runs and partial-scan statuses guarded the cutover. We got stuck here for weeks; one migration and a hard cutover would have left one system instead of two. _Status:_ code reads and writes only `session_entries` since [qm#2273](https://github.com/yc-software/qm/pull/2273); `session_tape` is dropped by a gated migration once its step metadata has been copied out ([qm#2280](https://github.com/yc-software/qm/pull/2280)).
- **Legacy Inbox loop:** `src/loops/inbox-migration.ts` migrates each owner's legacy Inbox loop at runtime, with its own phase record in UI-state preferences, a pause-and-disable sequence, and a repair path for half-finished runs. _Status:_ still on main; deletion approved for the loops rebuild.
### Over-testing
diff --git a/src/sessions/legacy-tape-steps.ts b/src/sessions/legacy-tape-steps.ts
index 3bafde009..f3b945d63 100644
--- a/src/sessions/legacy-tape-steps.ts
+++ b/src/sessions/legacy-tape-steps.ts
@@ -272,3 +272,63 @@ ${batchSql(true)} DROP TABLE pg_temp.legacy_batch_blocks;
END $batch$`,
skippingProcedure(),
];
+
+export const DROP_SESSION_TAPE_SQL = [
+ `SET LOCAL lock_timeout = '5s'`,
+ `DO $tape_drop_gate$
+DECLARE
+ started BIGINT;
+ finished BOOLEAN;
+ cursor_at TEXT;
+ skipped BIGINT;
+ last_tape_session TEXT;
+ writes BIGINT;
+ first_write BIGINT;
+ reset TEXT := 'reset with DROP TRIGGER legacy_tape_frozen ON session_tape; TRUNCATE legacy_tape_steps, legacy_turn_runs, legacy_tape_writes, legacy_tape_skipped; '
+ || 'UPDATE legacy_tape_steps_progress SET started_at = NULL, last_session = NULL, done = false, invalid_messages = 0, '
+ || 'keyed_blocks = 0, copied_steps = 0, copied_turns = 0, skipped_sessions = 0; then CALL prepare_legacy_tape_steps() again';
+BEGIN
+ IF to_regclass('session_tape') IS NULL THEN
+ RETURN;
+ END IF;
+ LOCK TABLE session_tape IN ACCESS EXCLUSIVE MODE;
+ IF to_regclass('legacy_tape_steps_progress') IS NOT NULL THEN
+ SELECT started_at, done, last_session, skipped_sessions INTO started, finished, cursor_at, skipped
+ FROM legacy_tape_steps_progress;
+ END IF;
+ IF started IS NULL OR NOT COALESCE(finished, false) THEN
+ IF NOT EXISTS (SELECT 1 FROM session_tape WHERE kind = 'message') THEN
+ RETURN;
+ END IF;
+ RAISE EXCEPTION 'session_tape still holds model messages: run CALL prepare_legacy_tape_steps() to completion before this migration, or if legacy_tape_frozen already exists, %',
+ reset;
+ END IF;
+ skipped := GREATEST(skipped, (SELECT count(*) FROM legacy_tape_skipped));
+ IF skipped > ${MAX_SKIPPED_SESSIONS} THEN
+ RAISE EXCEPTION '% sessions were skipped during the preparation, more than ${MAX_SKIPPED_SESSIONS}: review legacy_tape_skipped, then %',
+ skipped, reset;
+ END IF;
+ SELECT max(session_id) INTO last_tape_session FROM session_tape WHERE kind = 'message';
+ IF cursor_at IS NULL OR cursor_at < last_tape_session THEN
+ RAISE EXCEPTION 'the preparation is marked done but its cursor % is before the last tape session %, so not every session was copied: %',
+ COALESCE(cursor_at, '(none)'), last_tape_session, reset;
+ END IF;
+ SELECT count(*), min(at) INTO writes, first_write FROM legacy_tape_writes;
+ IF writes > 0 THEN
+ RAISE EXCEPTION 'session_tape was written % times after prepare_legacy_tape_steps() started, first at % (ms since epoch): stop every writer, %',
+ writes, first_write, reset;
+ END IF;
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_trigger
+ WHERE tgname = 'legacy_tape_frozen' AND tgrelid = 'session_tape'::regclass AND tgenabled = 'A'
+ ) THEN
+ RAISE EXCEPTION 'legacy_tape_frozen is missing or not always enabled, so tape writes since the preparation are unproven: %', reset;
+ END IF;
+END $tape_drop_gate$`,
+ `DROP VIEW IF EXISTS session_transcript_entries`,
+ `DROP TABLE IF EXISTS session_tape`,
+ `DROP PROCEDURE IF EXISTS prepare_legacy_tape_steps(INT)`,
+ `DROP FUNCTION IF EXISTS legacy_tape_written()`,
+ `DROP FUNCTION IF EXISTS legacy_tape_steps_batch(TEXT[], BIGINT)`,
+ `DROP TABLE IF EXISTS legacy_prep_runs, legacy_tape_writes`,
+];
diff --git a/src/sessions/postgres-session-store.ts b/src/sessions/postgres-session-store.ts
index 765ece405..2a31decc1 100644
--- a/src/sessions/postgres-session-store.ts
+++ b/src/sessions/postgres-session-store.ts
@@ -39,7 +39,7 @@ import type {
StoreOptions,
} from "./session-store.ts";
import { tsPrefixQuery } from "./entry-search.ts";
-import { LEGACY_TAPE_STEPS_SIZE_GUARD_SQL, LEGACY_TAPE_STEPS_SQL } from "./legacy-tape-steps.ts";
+import { DROP_SESSION_TAPE_SQL, LEGACY_TAPE_STEPS_SIZE_GUARD_SQL, LEGACY_TAPE_STEPS_SQL } from "./legacy-tape-steps.ts";
import {
cronIdOf,
legacyOriginPattern,
@@ -812,6 +812,10 @@ export function createPostgresSessionStore(connectionString: string, opts: Store
id: "sessions/store/0030-legacy-tape-steps-size-guard",
statements: LEGACY_TAPE_STEPS_SIZE_GUARD_SQL,
},
+ {
+ id: "sessions/store/0031-drop-session-tape",
+ statements: DROP_SESSION_TAPE_SQL,
+ },
],
[
{
diff --git a/test/postgres-legacy-tape-steps.test.ts b/test/postgres-legacy-tape-steps.test.ts
index 2a03e0789..d5a628c42 100644
--- a/test/postgres-legacy-tape-steps.test.ts
+++ b/test/postgres-legacy-tape-steps.test.ts
@@ -9,7 +9,9 @@ import { scopeId } from "../src/types.ts";
const URL = process.env.DATABASE_URL;
const skip = URL ? false : "set DATABASE_URL (a Postgres) to run the legacy tape steps test";
-async function withSchema(fn: (raw: import("pg").Pool) => Promise<void>): Promise<void> {
+const beforeTapeDrop = (id: string) => !id.startsWith("sessions/store/") || id < "sessions/store/0031";
+
+async function withSchema(fn: (raw: import("pg").Pool, url: string) => Promise<void>): Promise<void> {
const pg = (await import("pg")).default;
const admin = new pg.Pool({ connectionString: URL });
const schema = `tape_steps_${randomUUID().replaceAll("-", "")}`;
@@ -20,8 +22,11 @@ async function withSchema(fn: (raw: import("pg").Pool) => Promise<void>): Promis
try {
createPostgresSessionStore(url.toString());
createPostgresRunStore(url.toString());
- await applyPgMigrations(raw, registeredPgMigrations(url.toString()));
- await fn(raw);
+ await applyPgMigrations(
+ raw,
+ registeredPgMigrations(url.toString()).filter((migration) => beforeTapeDrop(migration.id)),
+ );
+ await fn(raw, url.toString());
} finally {
await raw.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
@@ -204,6 +209,63 @@ test(
},
);
+test(
+ "pg migrations drop the tape only after a completed preparation that saw no later tape write",
+ { skip },
+ async () => {
+ await withSchema(async (raw, url) => {
+ await seedSession(
+ raw,
+ "legacy",
+ [message([{ type: "toolCall", id: "c1", name: "execute", arguments: { b: 1, a: 2 } }])],
+ [["tool_call", { tool: "execute", callId: "c1", a: 2, b: 1 }]],
+ );
+ const migrations = registeredPgMigrations(url);
+ await assert.rejects(applyPgMigrations(raw, migrations), /run CALL prepare_legacy_tape_steps\(\) to completion/);
+
+ await raw.query("CALL prepare_legacy_tape_steps()");
+ await raw.query("UPDATE legacy_tape_steps_progress SET skipped_sessions = 101");
+ await assert.rejects(
+ applyPgMigrations(raw, migrations),
+ /101 sessions were skipped during the preparation, more than 100/,
+ );
+ await raw.query("UPDATE legacy_tape_steps_progress SET skipped_sessions = 0, last_session = 'a'");
+ await assert.rejects(
+ applyPgMigrations(raw, migrations),
+ /marked done but its cursor a is before the last tape session legacy/,
+ );
+ await raw.query("UPDATE legacy_tape_steps_progress SET last_session = 'legacy'");
+ await raw.query("UPDATE session_tape SET harness = 'pi'");
+ await assert.rejects(
+ applyPgMigrations(raw, migrations),
+ /written 1 times after prepare_legacy_tape_steps\(\) started, first at \d+/,
+ );
+
+ await raw.query("DELETE FROM legacy_tape_writes");
+ await raw.query("ALTER TABLE session_tape ENABLE TRIGGER legacy_tape_frozen");
+ await assert.rejects(applyPgMigrations(raw, migrations), /missing or not always enabled/);
+
+ await raw.query("ALTER TABLE session_tape ENABLE ALWAYS TRIGGER legacy_tape_frozen");
+ await applyPgMigrations(raw, migrations);
+ assert.deepEqual(
+ (
+ await raw.query(
+ `SELECT to_regclass('session_tape') AS tape, to_regclass('session_transcript_entries') AS view,
+ to_regclass('legacy_tape_writes') AS writes,
+ to_regprocedure('prepare_legacy_tape_steps(int)') AS prepare, to_regprocedure('legacy_tape_written()') AS written,
+ to_regprocedure('legacy_tape_steps_batch(text[], bigint)') AS batch, to_regclass('legacy_tape_skipped') IS NOT NULL AS skipped`,
+ )
+ ).rows[0],
+ { tape: null, view: null, writes: null, prepare: null, written: null, batch: null, skipped: true },
+ );
+ assert.deepEqual((await raw.query("SELECT seq, wire FROM legacy_tape_steps")).rows, [
+ { seq: 0, wire: { argumentsJson: '{"b":1,"a":2}' } },
+ ]);
+ assert.equal((await raw.query("SELECT copied_steps::int AS n FROM legacy_tape_steps_progress")).rows[0].n, 1);
+ });
+ },
+);
+
test("pg legacy tape step preparation skips oversized payloads and sessions it cannot parse", { skip }, async () => {
await withSchema(async (raw) => {
await seedSession(
diff --git a/test/postgres-tapeless-store.test.ts b/test/postgres-tapeless-store.test.ts
index dcde15b75..1bb8e4e91 100644
--- a/test/postgres-tapeless-store.test.ts
+++ b/test/postgres-tapeless-store.test.ts
@@ -8,7 +8,7 @@ import { scopeId } from "../src/types.ts";
const URL = process.env.DATABASE_URL;
const skip = URL ? false : "set DATABASE_URL (a Postgres) to run the tapeless store test";
-test("the session store keeps working once session_tape and its view are dropped", { skip }, async () => {
+test("migrations drop an empty session_tape and the store keeps working without it", { skip }, async () => {
const pg = (await import("pg")).default;
const admin = new pg.Pool({ connectionString: URL });
const schema = `tapeless_${randomUUID().replaceAll("-", "")}`;
@@ -29,8 +29,7 @@ test("the session store keeps working once session_tape and its view are dropped
scopeLabel: scope,
});
- await raw.query("DROP VIEW session_transcript_entries");
- await raw.query("DROP TABLE session_tape");
+ assert.equal((await raw.query("SELECT to_regclass('session_tape') AS t")).rows[0].t, null);
await applyPgMigrations(raw, registeredPgMigrations(url.toString()));
assert.equal((await raw.query("SELECT to_regclass('session_tape') AS t")).rows[0].t, null);