Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Index items call ids by digest so long gateway call ids fit (#2494)

Regan Bella53f817f019f
diff --git a/src/sessions/postgres-session-store.ts b/src/sessions/postgres-session-store.ts
index 8f1e1d7b5..bf2f53217 100644
--- a/src/sessions/postgres-session-store.ts
+++ b/src/sessions/postgres-session-store.ts
@@ -940,6 +940,21 @@ export function createPostgresSessionStore(connectionString: string, opts: Store
ON sessions(scope_id, (COALESCE(last_activity, created_at)) DESC, id DESC) WHERE origin NOT IN ('conversation', 'cron')`,
],
},
+ {
+ id: "sessions/store/0039-items-call-id-digest-index",
+ statements: [
+ `CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS items_one_call_per_kind_digest
+ ON items(tenant_id, session_id, kind, md5(call_id)) WHERE call_id IS NOT NULL`,
+ ],
+ },
+ {
+ id: "sessions/store/0040-items-call-id-digest-swap",
+ statements: [
+ `SET LOCAL lock_timeout = '3s'`,
+ `DROP INDEX IF EXISTS items_one_call_per_kind`,
+ `ALTER INDEX items_one_call_per_kind_digest RENAME TO items_one_call_per_kind`,
+ ],
+ },
],
[
{
diff --git a/src/sessions/tool-output.ts b/src/sessions/tool-output.ts
index 0e1ccdebb..de37a359f 100644
--- a/src/sessions/tool-output.ts
+++ b/src/sessions/tool-output.ts
@@ -12,6 +12,7 @@ const CHARS_PER_TOKEN = 4;
const TOOL_OUTPUT_RETENTION_MS = 30 * 24 * 60 * 60_000;
const SETTING_CACHE_MS = 30_000;
const TOOL_OUTPUT_PATH = "tool-output/";
+const DIGEST_DIR = "md5/";
export interface ToolOutputRef {
blob: string;
@@ -19,10 +20,15 @@ export interface ToolOutputRef {
shownChars: number;
}
+export interface ParkedOutputKey {
+ digest: string;
+ callId?: string;
+}
+
export interface ToolOutputStore {
inlineTokens(): Promise<number>;
save(text: string): Promise<string>;
- read(sessionId: string, callId: string): Promise<{ text: string } | { expired: true } | null>;
+ read(sessionId: string, key: ParkedOutputKey): Promise<{ text: string } | { expired: true } | null>;
}
export function inlineTokensFrom(value: unknown): number {
@@ -31,10 +37,16 @@ export function inlineTokensFrom(value: unknown): number {
return typeof n === "number" && Number.isFinite(n) && n >= 0 ? Math.floor(n) : DEFAULT_INLINE_TOKENS;
}
-export function toolOutputCallId(path: string): string | null {
+const md5Hex = (text: string): string => createHash("md5").update(text, "utf8").digest("hex");
+
+export function parkedOutputKey(path: string): ParkedOutputKey | null {
if (!path.startsWith(TOOL_OUTPUT_PATH)) return null;
- const callId = path.slice(TOOL_OUTPUT_PATH.length);
- return callId && !callId.includes("/") ? callId : null;
+ const name = path.slice(TOOL_OUTPUT_PATH.length);
+ if (name.startsWith(DIGEST_DIR)) {
+ const digest = name.slice(DIGEST_DIR.length);
+ return digest.length === 32 && Buffer.from(digest, "hex").toString("hex") === digest ? { digest } : null;
+ }
+ return name && !name.includes("/") ? { digest: md5Hex(name), callId: name } : null;
}
export function cutToolOutput(
@@ -49,7 +61,7 @@ export function cutToolOutput(
const tail = tailSlice(text, Math.floor(budget / 2));
const marker =
`\n…[output cut: showing the first ${head.length} and last ${tail.length} of ${text.length} chars. ` +
- `The full output is in ${TOOL_OUTPUT_PATH}${callId}; reading it with the files tool copies it onto the computer (kept 30 days)]…\n`;
+ `The full output is in ${TOOL_OUTPUT_PATH}${DIGEST_DIR}${md5Hex(callId)}; reading it with the files tool copies it onto the computer (kept 30 days)]…\n`;
return { text: head + marker + tail, shownChars: head.length + tail.length };
}
@@ -116,25 +128,26 @@ export function createPostgresToolOutputStore(opts: {
);
return put.sha256;
},
- async read(sessionId, callId) {
+ async read(sessionId, ref) {
const rows = await opts.pool.q(
`SELECT b.storage_key, i.created_at <= now() - interval '30 days' AS expired
FROM items i
LEFT JOIN blobs b ON b.tenant_id = i.tenant_id AND b.sha256 = i.blob_sha
- WHERE i.tenant_id = qm_tenant_id() AND i.session_id = $1 AND i.kind = 'ToolResult' AND i.call_id = $2
+ WHERE i.tenant_id = qm_tenant_id() AND i.session_id = $1 AND i.kind = 'ToolResult'
+ AND md5(i.call_id) = $2 AND ($3::text IS NULL OR i.call_id = $3)
AND i.blob_sha IS NOT NULL`,
- [sessionId, callId],
+ [sessionId, ref.digest, ref.callId ?? null],
);
const row = rows[0];
if (!row) return null;
if (row.expired === true) return { expired: true };
if (typeof row.storage_key !== "string")
- throw new Error(`tool output ${callId}: the result names a parked blob with no blobs row`);
+ throw new Error(`tool output ${ref.digest}: the result names a parked blob with no blobs row`);
const { bytes, id } = await tenantBytes();
const key = String(row.storage_key).slice(`${TOOL_OUTPUT_PATH}${id}/`.length);
const text = await readText(bytes, key);
if (text === null)
- throw new Error(`tool output ${callId}: parked bytes ${row.storage_key} are missing from storage`);
+ throw new Error(`tool output ${ref.digest}: parked bytes ${row.storage_key} are missing from storage`);
return { text };
},
};
@@ -158,15 +171,22 @@ export function createMemoryToolOutputStore(
parked.set(sha, text);
return sha;
},
- async read(sessionId, callId) {
+ async read(sessionId, ref) {
const entries = (await opts.sessions?.getEntries(sessionId)) ?? [];
- const result = entries.find(
- (e) => e.type === "tool_result" && (e.payload as { callId?: unknown } | null)?.callId === callId,
- );
- const blob = (result?.payload as { output?: { blob?: unknown } } | undefined)?.output?.blob;
+ const results = entries.filter((e) => {
+ const callId = (e.payload as { callId?: unknown } | null)?.callId;
+ return (
+ e.type === "tool_result" &&
+ typeof callId === "string" &&
+ md5Hex(callId) === ref.digest &&
+ (ref.callId === undefined || callId === ref.callId)
+ );
+ });
+ if (results.length > 1) throw new Error(`tool output ${ref.digest}: more than one call matches`);
+ const blob = (results[0]?.payload as { output?: { blob?: unknown } } | undefined)?.output?.blob;
if (typeof blob !== "string") return null;
const text = parked.get(blob);
- if (text === undefined) throw new Error(`tool output ${callId}: parked blob ${blob} is missing`);
+ if (text === undefined) throw new Error(`tool output ${ref.digest}: parked blob ${blob} is missing`);
return { text };
},
};
diff --git a/src/tools/primitives.ts b/src/tools/primitives.ts
index b36dcb582..3d96ce676 100644
--- a/src/tools/primitives.ts
+++ b/src/tools/primitives.ts
@@ -1,5 +1,5 @@
import type { AdminToolAccess } from "./admin.ts";
-import { toolOutputCallId, type ToolOutputStore } from "../sessions/tool-output.ts";
+import { parkedOutputKey, type ToolOutputStore } from "../sessions/tool-output.ts";
import { rankedSkills } from "../skills/materialize.ts";
import type { SkillResolution } from "../skills/skill-store.ts";
import {
@@ -987,12 +987,12 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
};
}
if (path.startsWith("shared/open-")) return { content: null, sourceScopeId: null };
- const parkedCallId = toolOutputCallId(path);
- if (parkedCallId && deps.toolOutput && deps.sessionId) {
- const parked = await withAbort(() => deps.toolOutput!.read(deps.sessionId!, parkedCallId), signal);
+ const parkedKey = parkedOutputKey(path);
+ if (parkedKey && deps.toolOutput && deps.sessionId) {
+ const parked = await withAbort(() => deps.toolOutput!.read(deps.sessionId!, parkedKey), signal);
if (parked && "expired" in parked)
return {
- content: `[the full output of ${parkedCallId} expired after 30 days; only the cut shown in the transcript remains]`,
+ content: `[the full output in ${path} expired after 30 days; only the cut shown in the transcript remains]`,
sourceScopeId: writableScopeId,
};
if (parked) {
diff --git a/test/agent-tools.test.ts b/test/agent-tools.test.ts
index ef53b2f5c..d31625161 100644
--- a/test/agent-tools.test.ts
+++ b/test/agent-tools.test.ts
@@ -13,7 +13,7 @@ import { resumeStrategy } from "../src/core/turn-resume.ts";
import { reconstructMessagesFromHistory } from "../src/harness/replay.ts";
import { createMemoryRunSignalStore, waitForClientResult } from "../src/runs/run-signal-store.ts";
import { CommandDenied, NeedsApproval, type ToolContext } from "../src/tools/primitives.ts";
-import { createMemoryToolOutputStore } from "../src/sessions/tool-output.ts";
+import { createMemoryToolOutputStore, parkedOutputKey } from "../src/sessions/tool-output.ts";
import type { ClientToolDeclaration, EntryType, SessionEntry } from "../src/types.ts";
import type { ComputerStatus } from "../src/sandbox/sandbox.ts";
@@ -729,9 +729,12 @@ test("a giant tool result is capped for the model, keeping the tail and matching
assert.equal(payload.stderr, undefined, "raw stderr is not stored beside the result");
});
-test("a result over the inline cap keeps its head and tail and parks the full text as tool-output/<call_id>", async () => {
+test("a result over the inline cap keeps its head and tail and parks the full text where its marker points", async () => {
const emitted: Emitted[] = [];
- const outputs = createMemoryToolOutputStore({ inlineTokens: 100 });
+ const outputs = createMemoryToolOutputStore({
+ inlineTokens: 100,
+ sessions: { getEntries: async () => emitted as unknown as SessionEntry[] },
+ });
const full = Array.from({ length: 2_000 }, (_, i) => `line ${i}`).join("\n");
const tc = {
...fakeToolContext(),
@@ -752,7 +755,12 @@ test("a result over the inline cap keeps its head and tail and parks the full te
assert.equal(payload.result, seen, "the item stores exactly what the model saw");
assert.ok(seen.startsWith("line 0\nline 1"), "head survives");
assert.ok(seen.includes("[exit 0]"), "tail survives");
- assert.ok(seen.includes(`tool-output/${payload.callId}`), "the marker names the parked file");
+ const marker = parkedOutputKey(/tool-output\/\S+(?=;)/.exec(seen)![0])!;
+ assert.deepEqual(
+ await outputs.read("s1", marker),
+ { text: outputs.parked.get(payload.output.blob) },
+ "the marker names the parked file",
+ );
assert.ok(payload.output.shownChars <= 400 && seen.length < 1_000, `cut to the 100-token budget (${seen.length})`);
assert.equal(outputs.parked.get(payload.output.blob)!.length, payload.output.chars);
assert.ok(outputs.parked.get(payload.output.blob)!.includes("line 1999"));
diff --git a/test/pi-harness-replay-fidelity.test.ts b/test/pi-harness-replay-fidelity.test.ts
index 09db23b82..b82dcf7c9 100644
--- a/test/pi-harness-replay-fidelity.test.ts
+++ b/test/pi-harness-replay-fidelity.test.ts
@@ -588,7 +588,7 @@ test(
const before = withoutCacheControl(first.bodies[1]!.messages) as unknown[];
const after = withoutCacheControl(second.bodies[0]!.messages) as unknown[];
assert.ok(!JSON.stringify(before).includes(bigResult.trim()));
- assert.match(JSON.stringify(before), /tool-output\/toolu_1/);
+ assert.match(JSON.stringify(before), /tool-output\/md5\/[0-9a-f]{32}/);
assert.equal(JSON.stringify(after.slice(0, before.length)), JSON.stringify(before));
assert.deepEqual(after.slice(before.length), [
{
diff --git a/test/postgres-items-contract.test.ts b/test/postgres-items-contract.test.ts
index 439836959..240367773 100644
--- a/test/postgres-items-contract.test.ts
+++ b/test/postgres-items-contract.test.ts
@@ -1,6 +1,6 @@
import { test } from "node:test";
import assert from "node:assert/strict";
-import { randomUUID } from "node:crypto";
+import { randomBytes, randomUUID } from "node:crypto";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -9,7 +9,12 @@ import { createLocalDurableByteStore } from "../src/files/durable-byte-store.ts"
import { applyPgMigrations, createPgPool, registeredPgMigrations } from "../src/persistence/pg-pool.ts";
import { createPostgresSessionStore } from "../src/sessions/postgres-session-store.ts";
import { DuplicateCallError } from "../src/sessions/session-store.ts";
-import { createPostgresToolOutputStore, DEFAULT_INLINE_TOKENS } from "../src/sessions/tool-output.ts";
+import {
+ createPostgresToolOutputStore,
+ cutToolOutput,
+ DEFAULT_INLINE_TOKENS,
+ parkedOutputKey,
+} from "../src/sessions/tool-output.ts";
import { scopeId } from "../src/types.ts";
const URL = process.env.DATABASE_URL;
@@ -151,7 +156,7 @@ test("pg items reject a second call with the same call id, leaving the log untou
});
test(
- "pg tool output: the inline cap comes from qm_settings and parked text reads back by call id",
+ "pg tool output: the inline cap comes from qm_settings and parked text reads back by a gateway call id carrying a large thought signature",
{ skip },
async () => {
await withSchema("items_tool_output", async ({ raw, url, store }) => {
@@ -176,27 +181,38 @@ test(
const full = "ünï line\n".repeat(10_000);
const blob = await outputs.save(full);
+ const callId = `call_${randomUUID()}__thought__${randomBytes(4_500).toString("base64")}`;
const { lease } = await store.acquireLease(session.id);
assert.ok(lease);
- await store.append(lease, {
- type: "tool_call",
- payload: { tool: "execute", callId: "big" },
- scopeLabel: scope,
- });
+ const call = { type: "tool_call" as const, payload: { tool: "execute", callId }, scopeLabel: scope };
+ await store.append(lease, call);
await store.append(lease, {
type: "tool_result",
payload: {
tool: "execute",
- callId: "big",
+ callId,
result: "head…tail",
output: { blob, chars: full.length, shownChars: 8 },
},
scopeLabel: scope,
});
+ await assert.rejects(store.append(lease, call), DuplicateCallError);
+ await store.append(lease, {
+ type: "tool_result",
+ payload: { tool: "execute", callId: "toolu_short", result: "head…tail", output: { blob } },
+ scopeLabel: scope,
+ });
await store.releaseLease(lease);
- assert.deepEqual(await outputs.read(session.id, "big"), { text: full });
- assert.equal(await outputs.read(session.id, "missing"), null);
- assert.equal(await outputs.read("other-session", "big"), null);
+ const entries = await store.getEntries(session.id);
+ assert.deepEqual(
+ entries.map((entry) => (entry.payload as { callId?: string }).callId),
+ [callId, callId, "toolu_short"],
+ );
+ const markerPath = /tool-output\/\S+(?=;)/.exec(cutToolOutput(full, 1, callId)!.text)![0];
+ assert.deepEqual(await outputs.read(session.id, parkedOutputKey(markerPath)!), { text: full });
+ assert.deepEqual(await outputs.read(session.id, parkedOutputKey("tool-output/toolu_short")!), { text: full });
+ assert.equal(await outputs.read(session.id, parkedOutputKey("tool-output/missing")!), null);
+ assert.equal(await outputs.read("other-session", parkedOutputKey(markerPath)!), null);
const row = (
await raw.query(
"SELECT size, storage_key, (extract(epoch FROM expires_at - created_at) / 86400)::int AS days FROM blobs",
diff --git a/test/tool-output-readback.test.ts b/test/tool-output-readback.test.ts
index 27649ddb7..000e157ca 100644
--- a/test/tool-output-readback.test.ts
+++ b/test/tool-output-readback.test.ts
@@ -2,10 +2,11 @@ import { test } from "node:test";
import assert from "node:assert/strict";
import { createToolContext } from "../src/tools/primitives.ts";
import type { Sandbox } from "../src/sandbox/sandbox.ts";
-import type { ToolOutputStore } from "../src/sessions/tool-output.ts";
+import { createMemoryToolOutputStore, parkIfOverCap, type ToolOutputStore } from "../src/sessions/tool-output.ts";
+import type { SessionEntry } from "../src/types.ts";
import { scopeId } from "../src/types.ts";
-function readBack(parked: Awaited<ReturnType<ToolOutputStore["read"]>>) {
+function readBack(parked: Awaited<ReturnType<ToolOutputStore["read"]>> | ToolOutputStore) {
const written: Array<[string, string]> = [];
const tc = createToolContext({
sandbox: {
@@ -22,7 +23,7 @@ function readBack(parked: Awaited<ReturnType<ToolOutputStore["read"]>>) {
acl: {} as never,
createdBy: "U1",
sessionId: "s1",
- toolOutput: { read: async () => parked } as unknown as ToolOutputStore,
+ toolOutput: (parked && "read" in parked ? parked : { read: async () => parked }) as ToolOutputStore,
});
return { tc, written };
}
@@ -42,3 +43,25 @@ test("an expired parked output says so and writes nothing", async () => {
assert.deepEqual(written, []);
assert.match(String(read.content), /expired after 30 days/);
});
+
+test("a cut result from a gateway call id with a thought signature reads back from its marker", async () => {
+ const callId = `call_1__thought__${"Q+/z".repeat(1_500)}`;
+ const entries: SessionEntry[] = [];
+ const store = createMemoryToolOutputStore({ inlineTokens: 10, sessions: { getEntries: async () => entries } });
+ const full = "x".repeat(1_000);
+ const parked = (await parkIfOverCap(store, full, callId))!;
+ entries.push({
+ sessionId: "s1",
+ seq: 0,
+ parentSeq: null,
+ type: "tool_result",
+ payload: { tool: "execute", callId, result: parked.text, output: parked.output },
+ scopeLabel: "personal:U1",
+ createdAt: 1,
+ });
+ const path = /tool-output\/\S+(?=;)/.exec(parked.text)![0];
+ assert.ok(path.length < 64);
+ const { tc, written } = readBack(store);
+ await tc.read(path);
+ assert.deepEqual(written, [[path, full]]);
+});
diff --git a/test/tool-output.test.ts b/test/tool-output.test.ts
index c59590ee9..8584c7e68 100644
--- a/test/tool-output.test.ts
+++ b/test/tool-output.test.ts
@@ -5,7 +5,7 @@ import {
createMemoryToolOutputStore,
DEFAULT_INLINE_TOKENS,
inlineTokensFrom,
- toolOutputCallId,
+ parkedOutputKey,
} from "../src/sessions/tool-output.ts";
import type { SessionEntry } from "../src/types.ts";
@@ -26,14 +26,19 @@ test("cutToolOutput keeps text within the budget untouched and halves the rest b
assert.equal(cut.shownChars, 200);
assert.ok(cut.text.startsWith("H".repeat(100)));
assert.ok(cut.text.endsWith("T".repeat(100)));
- assert.match(cut.text, /tool-output\/c1/);
+ const path = /tool-output\/\S+(?=;)/.exec(cut.text)![0];
+ assert.equal(path.length, "tool-output/md5/".length + 32);
+ assert.equal(parkedOutputKey(path)?.callId, undefined);
});
test("tool-output paths name one call", () => {
- assert.equal(toolOutputCallId("tool-output/toolu_1"), "toolu_1");
- assert.equal(toolOutputCallId("tool-output/"), null);
- assert.equal(toolOutputCallId("tool-output/a/b"), null);
- assert.equal(toolOutputCallId("notes/tool-output/a"), null);
+ assert.equal(parkedOutputKey("tool-output/toolu_1")?.callId, "toolu_1");
+ assert.equal(parkedOutputKey(`tool-output/md5/${"ab".repeat(16)}`)?.digest, "ab".repeat(16));
+ assert.equal(parkedOutputKey("tool-output/"), null);
+ assert.equal(parkedOutputKey("tool-output/a/b"), null);
+ assert.equal(parkedOutputKey(`tool-output/md5/${"AB".repeat(16)}`), null);
+ assert.equal(parkedOutputKey("tool-output/md5/abc"), null);
+ assert.equal(parkedOutputKey("notes/tool-output/a"), null);
});
test("a parked result reads back only through its own session's tool result", async () => {
@@ -49,7 +54,12 @@ test("a parked result reads back only through its own session's tool result", as
scopeLabel: "personal:u",
createdAt: 1,
});
- assert.deepEqual(await store.read("s1", "c1"), { text: "the whole thing" });
- assert.equal(await store.read("s2", "c1"), null);
- assert.equal(await store.read("s1", "c2"), null);
+ const markerPath = /tool-output\/\S+(?=;)/.exec(cutToolOutput("x".repeat(100), 1, "c1")!.text)![0];
+ for (const path of ["tool-output/c1", markerPath]) {
+ assert.deepEqual(await store.read("s1", parkedOutputKey(path)!), { text: "the whole thing" });
+ assert.equal(await store.read("s2", parkedOutputKey(path)!), null);
+ }
+ assert.equal(await store.read("s1", parkedOutputKey("tool-output/c2")!), null);
+ entries.push({ ...entries[0]!, seq: 1 });
+ await assert.rejects(store.read("s1", parkedOutputKey(markerPath)!), /more than one call matches/);
});