Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Preserve recovery compatibility during releases

Joshua Francead9f0aea80b1
diff --git a/cli/src/backends/aws.ts b/cli/src/backends/aws.ts
index 5367aa0f0..1f681b6b8 100644
--- a/cli/src/backends/aws.ts
+++ b/cli/src/backends/aws.ts
@@ -2144,7 +2144,7 @@ function assertPredeployDbRestorePoint(config: QmConfig): string {
const instance = awsJson<{
DBInstances?: Array<{ DBInstanceStatus?: string; BackupRetentionPeriod?: number; LatestRestorableTime?: string }>;
}>(aws, ["rds", "describe-db-instances", "--db-instance-identifier", database]).DBInstances?.[0];
- if (instance?.DBInstanceStatus !== "available") {
+ if (instance?.DBInstanceStatus !== "available" && instance?.DBInstanceStatus !== "storage-optimization") {
throw new CliError(
`database ${database} is ${instance?.DBInstanceStatus ?? "missing"}; refusing to deploy without an available source for the pre-deploy restore point`,
);
@@ -4731,7 +4731,7 @@ export async function awsDoctor(config: QmConfig, configDir: string): Promise<vo
VpcSecurityGroups?: Array<{ VpcSecurityGroupId?: string }>;
}>;
}>(aws, ["rds", "describe-db-instances", "--db-instance-identifier", rdsInstanceIdentifier(aws)]).DBInstances?.[0];
- if (database?.DBInstanceStatus !== "available")
+ if (database?.DBInstanceStatus !== "available" && database?.DBInstanceStatus !== "storage-optimization")
throw new Error(`database is ${database?.DBInstanceStatus || "missing"}`);
const coreService = aws.services.core;
if (!coreService) throw new Error("aws.services.core is missing");
diff --git a/cli/test/aws.test.ts b/cli/test/aws.test.ts
index 306f71d72..c3b314438 100644
--- a/cli/test/aws.test.ts
+++ b/cli/test/aws.test.ts
@@ -1352,7 +1352,7 @@ test("AWS up reapplies the recorded layer after starting a stopped core", async
}
});
-test("AWS up records a restore point under the lease before any mutation and stamps it in the manifest", async () => {
+test("AWS up records a restore point before mutation during storage optimization", async () => {
const dir = mkdtempSync(join(tmpdir(), "qm-aws-db-restore-point-"));
const dockerBin = join(dir, "docker");
writeFileSync(dockerBin, `#!/usr/bin/env node\nconsole.log("Digest: sha256:${"a".repeat(64)}");\n`);
@@ -1361,6 +1361,8 @@ test("AWS up records a restore point under the lease before any mutation and sta
const fake = statefulAws(dir, single);
const priorPath = process.env.PATH;
process.env.PATH = `${dir}:${priorPath}`;
+ const priorStatus = process.env.AWS_FAKE_DB_STATUS;
+ process.env.AWS_FAKE_DB_STATUS = "storage-optimization";
const started = Date.now();
try {
await awsUp(single, dir, { dryRun: true });
@@ -1395,6 +1397,8 @@ test("AWS up records a restore point under the lease before any mutation and sta
"the manifest records the pre-deploy restore timestamp",
);
} finally {
+ if (priorStatus === undefined) delete process.env.AWS_FAKE_DB_STATUS;
+ else process.env.AWS_FAKE_DB_STATUS = priorStatus;
process.env.PATH = priorPath;
fake.restore();
rmSync(dir, { recursive: true, force: true });
@@ -1413,7 +1417,7 @@ test("AWS up refuses to mutate when the database is unavailable, keeps no automa
() => awsUp(single, dir, { yes: true }),
/database acme-qm-core is backing-up; refusing to deploy/,
);
- delete process.env.AWS_FAKE_DB_STATUS;
+ process.env.AWS_FAKE_DB_STATUS = "storage-optimization";
process.env.AWS_FAKE_DB_RETENTION = "0";
await assert.rejects(
() => awsUp(single, dir, { yes: true }),
diff --git a/scripts/aws/rds-restore-drill.ts b/scripts/aws/rds-restore-drill.ts
index 02dc852c0..348cf133d 100644
--- a/scripts/aws/rds-restore-drill.ts
+++ b/scripts/aws/rds-restore-drill.ts
@@ -109,7 +109,7 @@ function sourceFacts(config: QmConfig): {
group.VpcSecurityGroupId ? [group.VpcSecurityGroupId] : [],
);
if (
- db?.DBInstanceStatus !== "available" ||
+ (db?.DBInstanceStatus !== "available" && db?.DBInstanceStatus !== "storage-optimization") ||
!db.DBInstanceClass ||
!db.StorageEncrypted ||
db.PubliclyAccessible ||
diff --git a/src/core/orchestrator/compaction.ts b/src/core/orchestrator/compaction.ts
index bd6f81b47..c226aac52 100644
--- a/src/core/orchestrator/compaction.ts
+++ b/src/core/orchestrator/compaction.ts
@@ -22,6 +22,7 @@ import {
recentEntryCountWithinBudget,
} from "../../harness/context-compaction.ts";
import { goalSnapshotPayload, latestGoalEntry, latestGoalRecord } from "../../harness/goal.ts";
+import { coverageImportEvent } from "../../harness/replay.ts";
import { estimateCostUsd } from "../../ratelimit/budget.ts";
import { errMessage } from "../../util/errors.ts";
import { createKeyedQueue } from "../../util/async.ts";
@@ -154,6 +155,7 @@ export function createCompaction(deps: OrchestratorDeps): CompactionContext {
lease: Lease;
summarized: Summarized;
goalSource: SessionEntry | null;
+ recent?: SessionEntry[];
}): Promise<{ summary: SessionEntry; goalEntry?: SessionEntry }> {
const { text, summaryLabel, throughSeq, securityTainted, mode } = input.summarized;
const goal = latestGoalRecord(input.goalSource ? [input.goalSource] : []);
@@ -178,18 +180,22 @@ export function createCompaction(deps: OrchestratorDeps): CompactionContext {
},
scopeLabel: summaryLabel,
});
+ const covered = (await deps.sessions.tapeCoverage(input.session.id)) === (goalEntry?.seq ?? summary.seq) - 1;
+ const recoveredCoverage = covered ? summary.seq : undefined;
await deps.sessions.appendTape(input.lease, {
kind: "context_event",
- payload: { event: "compaction", text, ...(mode ? { mode } : {}) },
+ payload: mode
+ ? { ...coverageImportEvent([...(input.recent ?? []), ...(goalEntry ? [goalEntry] : []), summary]), mode }
+ : { event: "compaction", text },
scopeLabel: summaryLabel as ScopeId,
entrySeq: summary.seq,
- coversEntrySeq: throughSeq,
+ coversEntrySeq: mode ? recoveredCoverage : throughSeq,
meta: {
entryCreatedAt: summary.createdAt,
...(securityTainted ? { securityTainted: true } : {}),
},
});
- if ((await deps.sessions.tapeCoverage(input.session.id)) === (goalEntry?.seq ?? summary.seq) - 1) {
+ if (covered) {
await deps.sessions.appendTape(input.lease, {
kind: "annotation",
payload: tapeCheckpointPayload("turnEnd"),
@@ -316,6 +322,7 @@ export function createCompaction(deps: OrchestratorDeps): CompactionContext {
mode: "recent",
},
goalSource: goalSource && !recent.includes(goalSource) ? goalSource : null,
+ recent,
});
return [summary, ...recent, ...(goalEntry ? [goalEntry] : [])];
}
diff --git a/src/harness/replay.ts b/src/harness/replay.ts
index 72b9ec53b..2aa6c3e32 100644
--- a/src/harness/replay.ts
+++ b/src/harness/replay.ts
@@ -267,7 +267,7 @@ export async function appendCoverageImport(
});
}
-function coverageImportEvent(entries: readonly SessionEntry[]): {
+export function coverageImportEvent(entries: readonly SessionEntry[]): {
event: "legacy_import";
messages: PiReplayMessage[];
scopes: ScopeId[];
diff --git a/test/context-recovery.test.ts b/test/context-recovery.test.ts
index ff7eb27f7..f5267daef 100644
--- a/test/context-recovery.test.ts
+++ b/test/context-recovery.test.ts
@@ -12,6 +12,9 @@ import {
} from "../src/sessions/session-store.ts";
import { createGoalRecord, goalSnapshotPayload, latestGoalRecord } from "../src/harness/goal.ts";
import { filterHistoryForAudience } from "../src/resolution/context-filter.ts";
+import { foldTape, lintFold, tapeEventsEntitled } from "../src/harness/tape-fold.ts";
+import { reconstructMessagesFromHistory } from "../src/harness/replay.ts";
+import { countTokens } from "../src/util/tokens.ts";
async function fixture() {
const sessions = createMemorySessionStore();
@@ -236,6 +239,88 @@ test("recent recovery cannot recover an unauthorized summary or goal", async ()
const history = await f.compaction.compactRecent(f.input);
assert.equal(latestGoalRecord(history), null);
assert.doesNotMatch(JSON.stringify(history), /private sentinel/);
+ assert.doesNotMatch(JSON.stringify(foldTape(await f.sessions.getTape(f.input.session.id))), /private sentinel/);
+ } finally {
+ await f.sessions.releaseLease(f.input.lease);
+ }
+});
+
+test("recent recovery replaces the replay prefix even when the exclusion ends inside a completed turn", async () => {
+ const f = await fixture();
+ const goal = createGoalRecord({ objective: "verify result", source: "tool" });
+ try {
+ await f.sessions.append(f.input.lease, {
+ type: "system",
+ payload: goalSnapshotPayload(goal),
+ scopeLabel: "org:test",
+ });
+ await f.sessions.append(f.input.lease, {
+ type: "user",
+ payload: { text: "discarded oversized request ".repeat(1000) },
+ scopeLabel: "personal:test",
+ });
+ const last = await f.sessions.append(f.input.lease, {
+ type: "assistant",
+ payload: { text: "The action is complete." },
+ scopeLabel: "team:eng",
+ });
+ await refresh(f);
+ for (const entry of f.input.visibleHistory)
+ if (entry.type === "user" || entry.type === "assistant")
+ await f.sessions.appendTape(f.input.lease, {
+ kind: "message",
+ payload: {
+ role: entry.type,
+ content: [{ type: "text", text: (entry.payload as { text: string }).text }],
+ timestamp: entry.createdAt,
+ },
+ scopeLabel: entry.scopeLabel,
+ entrySeq: entry.seq,
+ harness: "pi",
+ });
+ await f.sessions.appendTape(f.input.lease, {
+ kind: "annotation",
+ payload: tapeCheckpointPayload("turnEnd"),
+ scopeLabel: "personal:test",
+ entrySeq: last.seq,
+ });
+ const history = await f.compaction.compactRecent(f.input);
+ const tape = await f.sessions.getTape(f.input.session.id);
+ const folded = foldTape(tape);
+ assert.deepEqual(folded, reconstructMessagesFromHistory(history));
+ assert.ok(countTokens(JSON.stringify(folded)) < 500);
+ assert.ok(lintFold(folded).ok);
+ assert.deepEqual(latestGoalRecord(history), goal);
+ assert.ok(history.at(-1)!.seq > last.seq);
+ assert.equal(await f.sessions.tapeCoverage(f.input.session.id), history[0]!.seq);
+ assert.equal(
+ tapeEventsEntitled(tape, [{ id: "test", type: "internal", teamIds: ["eng"] }], "personal:test", "org:test"),
+ true,
+ );
+ assert.equal(tapeEventsEntitled(tape, [{ id: "test", type: "internal" }], "personal:test", "org:test"), false);
+ } finally {
+ await f.sessions.releaseLease(f.input.lease);
+ }
+});
+
+test("a failed recent replay replacement cannot advance tape coverage", async () => {
+ const f = await fixture();
+ try {
+ await f.sessions.appendTape(f.input.lease, {
+ kind: "annotation",
+ payload: tapeCheckpointPayload("turnEnd"),
+ scopeLabel: "personal:test",
+ entrySeq: 11,
+ });
+ const appendTape = f.sessions.appendTape;
+ f.sessions.appendTape = async (lease, record) => {
+ if ((record.payload as { event?: string }).event === "legacy_import") throw new Error("import unavailable");
+ return appendTape(lease, record);
+ };
+ await assert.rejects(f.compaction.compactRecent(f.input), /import unavailable/);
+ assert.equal(await f.sessions.tapeCoverage(f.input.session.id), 11);
+ assert.equal(f.resets(), 0);
+ assert.ok((await f.sessions.latestEntrySeq(f.input.session.id)) > 11);
} finally {
await f.sessions.releaseLease(f.input.lease);
}
@@ -256,13 +341,45 @@ for (const covered of [false, true]) {
const history = await f.compaction.compactRecent(f.input);
assert.equal(await f.sessions.tapeCoverage(f.input.session.id), covered ? history[0]!.seq : before);
const tape = await f.sessions.getTape(f.input.session.id);
- assert.equal((tape.find((row) => row.kind === "context_event")!.payload as { mode: string }).mode, "recent");
+ const recovery = tape.find((row) => row.kind === "context_event")!;
+ assert.equal((recovery.payload as { mode: string }).mode, "recent");
+ assert.equal((recovery.payload as { event: string }).event, "legacy_import");
+ assert.equal(recovery.coversEntrySeq, covered ? history[0]!.seq : undefined);
} finally {
await f.sessions.releaseLease(f.input.lease);
}
});
}
+test("an incomplete recent replacement cannot label retained messages with an older replay boundary", async () => {
+ const f = await fixture();
+ try {
+ await f.sessions.append(f.input.lease, {
+ type: "assistant",
+ payload: { text: "Retained completed action." },
+ scopeLabel: "personal:test",
+ });
+ await f.sessions.appendTape(f.input.lease, {
+ kind: "annotation",
+ payload: tapeCheckpointPayload("turnEnd"),
+ scopeLabel: "personal:test",
+ entrySeq: 5,
+ });
+ await refresh(f);
+ await f.compaction.compactRecent(f.input);
+ assert.equal(await f.sessions.tapeCoverage(f.input.session.id), 5);
+ await f.sessions.appendTape(f.input.lease, {
+ kind: "context_event",
+ payload: { event: "compaction", text: "A later summary." },
+ scopeLabel: "personal:test",
+ coversEntrySeq: 11,
+ });
+ assert.match(JSON.stringify(foldTape(await f.sessions.getTape(f.input.session.id))), /Retained completed action/);
+ } finally {
+ await f.sessions.releaseLease(f.input.lease);
+ }
+});
+
for (const tainted of [false, true]) {
test(`a ${tainted ? "tainted" : "foreign"} summary still supplies the durable exclusion floor`, async () => {
const f = await fixture();
@@ -298,6 +415,10 @@ for (const tainted of [false, true]) {
assert.deepEqual(reloaded, history);
assert.ok(estimateHistoryTokens(reloaded) <= 300);
assert.doesNotMatch(JSON.stringify(reloaded), /old message|hidden summary sentinel/);
+ assert.doesNotMatch(
+ JSON.stringify(foldTape(await f.sessions.getTape(f.input.session.id))),
+ /old message|hidden summary sentinel/,
+ );
} finally {
await f.sessions.releaseLease(f.input.lease);
}