Skip to content

Commit d9421e9

Browse files
author
hzq
committed
Confirm retention batches after a lost commit acknowledgement
Record a bounded receipt in the deletion transaction so confirmed cleanup can invalidate views and remove blobs without repeating the delete. Report unknown outcomes when the receipt cannot be verified.
1 parent c31e0e6 commit d9421e9

6 files changed

Lines changed: 226 additions & 5 deletions

File tree

‎docs/stability.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -562,6 +562,11 @@ are removed after their rows commit; a crash in between leaves orphaned blobs, w
562562
prune removes. On a live gateway a contended write lock is retried between event-loop turns within the existing SQLite timeout. After deletion the gateway uses a passive WAL checkpoint rather than waiting for long-lived readers; the WAL may stay allocated for reuse. An offline prune still uses a truncating checkpoint. Without `--vacuum`, SQLite reuses the freed pages, so the file stops
563563
growing at the size of the retained window instead of shrinking.
564564

565+
A nonempty deletion batch writes a receipt in the same transaction. If the commit acknowledgement
566+
is lost, only the matching stored receipt lets the gateway publish the change, count the batch
567+
or unlink its blobs. Otherwise it reports `409 effect_outcome_unknown` and stops the sweep;
568+
earlier confirmed batches are not undone. It never reruns the uncertain delete.
569+
565570
## 5. Known limits
566571

567572
- The soak uses a fake model server and the offline sample agent. Real providers and real agent

‎docs/zh-CN/stability.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,8 @@ worker 已产出的文件共用同一个写锁探测器,按 owner 轮流取锁
230230

231231
执行方式:候选运行按每批 200 个、在短的 `BEGIN IMMEDIATE` 事务里删除;在线争抢写锁时,在原 SQLite 超时预算内异步重试,只重试获取锁,不重放删除。保留祖先的委托后代也会保留;续接任务引用的产物仍可按原生产者授权下载,不因源运行过期而放宽权限。文件在对应的行提交后才删除;若中途崩溃,孤儿文件由下一次清理回收。在线删除后使用不等待读者退出的被动 WAL 检查点,WAL 可能保留空间供后续复用;离线清理仍使用 `wal_checkpoint(TRUNCATE)`。不加 `--vacuum` 不会主动缩小主数据库。
232232

233+
非空删除批次与回执在同一事务提交。提交确认丢失时,只有读回对应回执才计入结果、通知概览或删掉磁盘文件;无法核对则停止清理并返回 `409 effect_outcome_unknown`。已确认的前序批次不会撤销,也不会重做结果未知的删除。
234+
233235
## 5. 已知限制
234236

235237
- 压测用的是假模型服务和离线示例智能体。真实的提供方和真实的智能体命令行会带来它测不到的延迟、内存与故障模式。

‎src/store/prune-write.ts‎

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1+
import { randomUUID } from 'node:crypto';
12
import { setTimeout as delay } from 'node:timers/promises';
23
import type { DatabaseSync } from 'node:sqlite';
4+
import { Fault } from '../core/util.js';
5+
import { isWriteUnavailable } from './checkpoint.js';
36
import type { PruneProfile } from './prune-profile.js';
47
import { tryBeginWrite } from './write-lock.js';
58

69
/** Retry only BEGIN, never a mutation. Restore the shared connection policy before yielding. */
7-
export async function pruneWrite<T>(
10+
export async function pruneWrite<T extends { ids: readonly string[] } | undefined>(
811
db: DatabaseSync,
912
live: boolean,
1013
profile: PruneProfile | undefined,
@@ -35,20 +38,65 @@ export async function pruneWrite<T>(
3538
let value: T;
3639
try {
3740
value = mutate();
41+
// Keep one receipt in the same SQLite transaction as the deletes. A missing target row
42+
// or differently numbered receipt cannot prove which batch committed.
43+
const receipt = value?.ids.length ? randomUUID() : undefined;
44+
if (
45+
receipt &&
46+
!db
47+
.prepare(
48+
'INSERT INTO retention_batch_receipt(slot,receipt) VALUES(1,?) ' +
49+
'ON CONFLICT(slot) DO UPDATE SET receipt=excluded.receipt',
50+
)
51+
.run(receipt).changes
52+
)
53+
throw new Fault('persistence_failed', 'The maintenance receipt could not be written.', 500);
3854
const phase = performance.now();
3955
try {
4056
db.exec('COMMIT');
57+
} catch (error) {
58+
if (db.isTransaction || !receipt) throw error;
59+
if (!isWriteUnavailable(error) || !hasReceipt(db, receipt)) throw unconfirmed();
4160
} finally {
4261
profile?.add('commit', phase);
4362
}
63+
if (db.isTransaction)
64+
throw new Fault('persistence_failed', 'The maintenance transaction is still open.', 500);
4465
} catch (error) {
45-
if (db.isTransaction) db.exec('ROLLBACK');
66+
if (db.isTransaction) {
67+
try {
68+
db.exec('ROLLBACK');
69+
} catch {
70+
throw unconfirmed();
71+
}
72+
if (db.isTransaction) throw unconfirmed();
73+
}
4674
throw error;
4775
}
4876
committed?.(value, performance.now() - held);
4977
return value;
5078
}
5179

80+
function hasReceipt(db: DatabaseSync, expected: string): boolean {
81+
try {
82+
return (
83+
db.prepare('SELECT receipt FROM retention_batch_receipt WHERE slot=1').get()?.receipt ===
84+
expected
85+
);
86+
} catch {
87+
return false;
88+
}
89+
}
90+
91+
function unconfirmed() {
92+
return new Fault(
93+
'effect_outcome_unknown',
94+
'The maintenance batch could not be confirmed. Check the stored state before pruning again.',
95+
409,
96+
true,
97+
);
98+
}
99+
52100
function isBusy(error: unknown) {
53101
return (
54102
error instanceof Error &&

‎src/store/retention.ts‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
import { lstat, opendir, readdir, rm, stat } from 'node:fs/promises';
2323
import path from 'node:path';
2424
import type { DatabaseSync } from 'node:sqlite';
25-
import { sha } from '../core/util.js';
25+
import { Fault, sha } from '../core/util.js';
2626
import { RECOVERABLE_WORKFLOW_STATES } from './task-workflows.js';
2727
import { isStagingArtifact } from './large-artifacts.js';
2828
import { PruneProfile, pruneChannel } from './prune-profile.js';
@@ -245,7 +245,15 @@ async function executePrune(
245245
db.prepare(`DELETE FROM ${table} WHERE run_id IN (${marks})`).run(...ids);
246246
for (const table of runTables)
247247
db.prepare(`DELETE FROM ${table} WHERE run_id IN (${marks})`).run(...ids);
248-
db.prepare(`DELETE FROM runs WHERE id IN (${marks})`).run(...ids);
248+
if (
249+
Number(db.prepare(`DELETE FROM runs WHERE id IN (${marks})`).run(...ids).changes) !==
250+
ids.length
251+
)
252+
throw new Fault(
253+
'persistence_failed',
254+
'The maintenance batch did not delete all planned runs.',
255+
500,
256+
);
249257
profile?.add('delete', phase);
250258
return { ids, owners: [...new Set(runs.map((r) => r.owner))], events };
251259
},
@@ -307,7 +315,18 @@ async function executePrune(
307315
const doomed = candidates.filter((r) => !refs.has(`${r.owner}\0${r.id}`));
308316
const ids = doomed.map((r) => String(r.id));
309317
if (!dryRun && ids.length) {
310-
db.prepare(`DELETE FROM files WHERE id IN (${ids.map(() => '?').join(',')})`).run(...ids);
318+
if (
319+
Number(
320+
db
321+
.prepare(`DELETE FROM files WHERE id IN (${ids.map(() => '?').join(',')})`)
322+
.run(...ids).changes,
323+
) !== ids.length
324+
)
325+
throw new Fault(
326+
'persistence_failed',
327+
'The maintenance batch did not delete all planned files.',
328+
500,
329+
);
311330
refsAt = version();
312331
}
313332
profile?.add('files', started);

‎src/store/store.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,7 @@ export class Store {
225225
CREATE TABLE IF NOT EXISTS bundles (digest TEXT PRIMARY KEY, owner TEXT NOT NULL, agent_id TEXT NOT NULL, payload TEXT NOT NULL, created_at INTEGER NOT NULL);
226226
CREATE TABLE IF NOT EXISTS agents (owner TEXT NOT NULL, id TEXT NOT NULL, digest TEXT NOT NULL REFERENCES bundles(digest), PRIMARY KEY(owner,id));
227227
CREATE TABLE IF NOT EXISTS runs (id TEXT PRIMARY KEY, owner TEXT NOT NULL, agent_id TEXT NOT NULL, session_id TEXT NOT NULL, status TEXT NOT NULL, payload TEXT NOT NULL, idem TEXT, fingerprint TEXT, subject TEXT, UNIQUE(owner,idem));
228+
CREATE TABLE IF NOT EXISTS retention_batch_receipt (slot INTEGER PRIMARY KEY CHECK(slot=1), receipt TEXT NOT NULL);
228229
CREATE UNIQUE INDEX IF NOT EXISTS active_session ON runs(owner,session_id) WHERE status IN ('queued','in_progress','requires_action');
229230
CREATE TABLE IF NOT EXISTS events (id INTEGER PRIMARY KEY AUTOINCREMENT, run_id TEXT NOT NULL REFERENCES runs(id), type TEXT NOT NULL, time INTEGER NOT NULL, payload TEXT NOT NULL, wire_json INTEGER NOT NULL DEFAULT 0);
230231
CREATE INDEX IF NOT EXISTS event_run ON events(run_id,id);

‎test/prune-receipt.test.ts‎

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
import assert from 'node:assert/strict';
2+
import { readFile } from 'node:fs/promises';
3+
import path from 'node:path';
4+
import test from 'node:test';
5+
import { makeBundle } from '../src/lang/bundle.js';
6+
import { pruneGeneration } from '../src/store/retention.js';
7+
import { agent, setup } from './helpers.js';
8+
9+
const readReceipt = 'SELECT receipt FROM retention_batch_receipt WHERE slot=1';
10+
const io = () =>
11+
Object.assign(new Error('fixture lost maintenance commit acknowledgement'), {
12+
code: 'ERR_SQLITE_ERROR',
13+
errcode: 10,
14+
});
15+
16+
for (const kind of ['runs', 'files'] as const)
17+
for (const mode of ['committed', 'rollback', 'unreadable', 'different receipt'] as const)
18+
test(`prune ${kind} acknowledges only its own committed batch: ${mode}`, async (t) => {
19+
const s = await setup();
20+
const db = s.store.db;
21+
const exec = db.exec.bind(db);
22+
const prepare = db.prepare.bind(db);
23+
let deletes = 0,
24+
lost = false,
25+
summaries = 0;
26+
try {
27+
s.store.publish('owner', makeBundle(agent()));
28+
const older = Date.now() - 120_000;
29+
const ids: string[] = [];
30+
for (const n of [1, 2]) {
31+
if (kind === 'runs') {
32+
const reply = await s.request('POST', '/v1/responses', {
33+
model: 'agent/test',
34+
input: 'fixture ' + n,
35+
});
36+
assert.equal(reply.statusCode, 200, reply.body);
37+
const id = String(reply.json().id);
38+
db.prepare("UPDATE runs SET payload=json_set(payload,'$.updatedAt',?) WHERE id=?").run(
39+
older,
40+
id,
41+
);
42+
ids.push(id);
43+
} else {
44+
const file = await s.store.addFile('owner', `fixture-${n}.txt`, Buffer.from('fixture'));
45+
db.prepare("UPDATE files SET payload=json_set(payload,'$.createdAt',?) WHERE id=?").run(
46+
older,
47+
file.id,
48+
);
49+
ids.push(file.id);
50+
}
51+
}
52+
db.prepare('INSERT INTO retention_batch_receipt(slot,receipt) VALUES(1,?)').run(
53+
'previous fixture receipt',
54+
);
55+
const exists = db.prepare(`SELECT 1 FROM ${kind} WHERE id=?`);
56+
const events = db.prepare('SELECT count(*) AS n FROM events WHERE run_id=?');
57+
const expectedEvents = ids.reduce((count, id) => count + Number(events.get(id)!.n), 0);
58+
const overview = await s.request('GET', '/v1/overview');
59+
const generation = pruneGeneration.value;
60+
s.store.events.on('summary', () => summaries++);
61+
db.function('arm_prune_ack', () => ++deletes);
62+
db.exec(`CREATE TEMP TRIGGER arm_prune_ack AFTER DELETE ON main.${kind}
63+
BEGIN SELECT arm_prune_ack(); END`);
64+
t.mock.method(db, 'exec', (sql: string) => {
65+
if (!deletes || lost || sql !== 'COMMIT') return exec(sql);
66+
lost = true;
67+
if (mode !== 'rollback') exec(sql);
68+
if (mode === 'different receipt')
69+
prepare('UPDATE retention_batch_receipt SET receipt=? WHERE slot=1').run(
70+
'previous fixture receipt',
71+
);
72+
throw io();
73+
});
74+
t.mock.method(db, 'prepare', (sql: string) => {
75+
if (lost && mode === 'unreadable' && sql === readReceipt) throw io();
76+
return prepare(sql);
77+
});
78+
const prune = () => s.request('POST', '/v1/maintenance/prune', { older_than_ms: 60_000 });
79+
const result = await prune();
80+
assert.equal(lost, true);
81+
assert.equal(deletes, ids.length, 'the DELETE was not re-executed');
82+
assert.equal(db.isTransaction, false);
83+
if (mode === 'committed') {
84+
assert.equal(result.statusCode, 200, result.body);
85+
const report = result.json();
86+
assert.equal(report[kind], ids.length);
87+
assert.equal(report.events, expectedEvents);
88+
assert.equal(report.file_bytes, kind === 'files' ? 14 : 0);
89+
const retry = await prune();
90+
assert.equal(retry.statusCode, 200, retry.body);
91+
assert.equal(retry.json()[kind], 0);
92+
assert.equal(deletes, ids.length);
93+
} else if (mode === 'rollback') {
94+
assert.equal(result.statusCode, 500);
95+
assert.equal(prepare(readReceipt).get()?.receipt, 'previous fixture receipt');
96+
} else {
97+
assert.equal(result.statusCode, 409, result.body);
98+
assert.equal(result.json().error.code, 'effect_outcome_unknown');
99+
assert.equal(result.headers['x-should-retry'], 'false');
100+
}
101+
const published = kind === 'runs' && mode === 'committed';
102+
assert.equal(summaries, published ? 1 : 0);
103+
assert.equal(pruneGeneration.value, generation + (published ? 1 : 0));
104+
const checked = await s.request('GET', '/v1/overview', undefined, undefined, {
105+
'if-none-match': String(overview.headers.etag),
106+
});
107+
assert.equal(checked.statusCode, published ? 200 : 304);
108+
for (const id of ids) {
109+
assert.equal(Boolean(exists.get(id)), mode === 'rollback');
110+
if (kind === 'files') {
111+
const blob = readFile(path.join(s.store.root, 'files', id), 'utf8');
112+
if (mode === 'committed') await assert.rejects(blob, { code: 'ENOENT' });
113+
else assert.equal(await blob, 'fixture');
114+
}
115+
}
116+
} finally {
117+
await s.cleanup();
118+
}
119+
});
120+
121+
test('a partial file delete rolls back instead of unlinking a still-listed file', async () => {
122+
const s = await setup();
123+
try {
124+
const ignored = await s.store.addFile('owner', 'ignored.txt', Buffer.from('keep')),
125+
other = await s.store.addFile('owner', 'other.txt', Buffer.from('also keep'));
126+
const db = s.store.db;
127+
db.prepare("UPDATE files SET payload=json_set(payload,'$.createdAt',?)").run(
128+
Date.now() - 120_000,
129+
);
130+
db.exec(`CREATE TEMP TRIGGER ignore_fixture_file BEFORE DELETE ON files
131+
WHEN json_extract(OLD.payload,'$.name')='ignored.txt' BEGIN SELECT RAISE(IGNORE); END`);
132+
const result = await s.request('POST', '/v1/maintenance/prune', { older_than_ms: 60_000 });
133+
assert.equal(result.statusCode, 500);
134+
assert.equal(result.json().error.code, 'persistence_failed');
135+
assert.equal(db.prepare(readReceipt).get(), undefined);
136+
for (const [file, text] of [
137+
[ignored, 'keep'],
138+
[other, 'also keep'],
139+
] as const) {
140+
assert.ok(db.prepare('SELECT 1 FROM files WHERE id=?').get(file.id));
141+
assert.equal(await readFile(path.join(s.store.root, 'files', file.id), 'utf8'), text);
142+
}
143+
} finally {
144+
await s.cleanup();
145+
}
146+
});

0 commit comments

Comments
 (0)