Skip to content

Commit 4994e1a

Browse files
author
hzq
committed
Scan retention candidates in bounded rowid windows
Advance past retained prefixes without dropping the per-page eligibility checks. Keep file reference snapshots valid across their own receipt writes while still rechecking external changes.
1 parent d9421e9 commit 4994e1a

6 files changed

Lines changed: 264 additions & 46 deletions

File tree

‎bench/prune-candidates.ts‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import assert from 'node:assert/strict';
2+
import { mkdtemp, rm } from 'node:fs/promises';
3+
import { tmpdir } from 'node:os';
4+
import path from 'node:path';
5+
import { setImmediate as nextTurn } from 'node:timers/promises';
6+
import { parseArgs } from 'node:util';
7+
import { pruneChannel } from '../src/store/prune-profile.js';
8+
import { prune } from '../src/store/retention.js';
9+
import { Store } from '../src/store/store.js';
10+
11+
const { values } = parseArgs({
12+
options: {
13+
kept: { type: 'string', default: '2500' },
14+
expired: { type: 'string', default: '1200' },
15+
trials: { type: 'string', default: '3' },
16+
foreign: { type: 'boolean' },
17+
},
18+
});
19+
const count = (value: string | undefined, min: number, max: number) => {
20+
const n = Number(value);
21+
assert.ok(Number.isInteger(n) && n >= min && n <= max);
22+
return n;
23+
};
24+
const kept = count(values.kept, 0, 10_000);
25+
const expired = count(values.expired, 1, 10_000);
26+
const trials = count(values.trials, 1, 10);
27+
28+
async function trial() {
29+
const dir = await mkdtemp(path.join(tmpdir(), 'oaa-prune-candidates-'));
30+
let store: Store | undefined;
31+
let profile: unknown;
32+
let yields = 0;
33+
const receive = (value: unknown) => {
34+
profile = value;
35+
};
36+
try {
37+
store = new Store(dir);
38+
const now = Date.now();
39+
const active = JSON.stringify({
40+
updatedAt: now,
41+
checkpoint: { messages: [{ content: 'x'.repeat(32 * 1024) }] },
42+
});
43+
const stale = JSON.stringify({ updatedAt: now - 120_000 });
44+
const insert = store.db.prepare(
45+
'INSERT INTO runs(id,owner,agent_id,session_id,status,payload) VALUES(?,?,?,?,?,?)',
46+
);
47+
store.db.exec('BEGIN IMMEDIATE');
48+
for (let i = 0; i < kept + expired; i++)
49+
insert.run(
50+
'run-' + i,
51+
i < kept && values.foreign ? 'foreign owner' : 'owner',
52+
'agent/fixture',
53+
'session-' + i,
54+
'completed',
55+
i < kept ? active : stale,
56+
);
57+
store.db.exec('COMMIT');
58+
pruneChannel.subscribe(receive);
59+
const report = await prune(store, {
60+
owner: 'owner',
61+
olderThanMs: 60_000,
62+
now,
63+
live: true,
64+
pause: async () => {
65+
yields++;
66+
await nextTurn();
67+
},
68+
});
69+
assert.equal(report.runs, expired);
70+
assert.equal(store.db.prepare('SELECT count(*) AS n FROM runs').get()!.n, kept);
71+
assert.ok(profile);
72+
return { yields, profile };
73+
} finally {
74+
pruneChannel.unsubscribe(receive);
75+
store?.close();
76+
await rm(dir, { recursive: true, force: true });
77+
}
78+
}
79+
80+
const samples = [];
81+
for (let i = 0; i < trials; i++) samples.push(await trial());
82+
console.log(JSON.stringify({ kept, expired, foreign: !!values.foreign, samples }));

‎docs/stability.md‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -555,9 +555,12 @@ settlement readback; delegated descendants of a kept ancestor; files still liste
555555
kept run. When a producer is pruned, a retained artifact keeps its original agent read requirement, owner and subject. Continuing a run that was pruned returns 404, like any
556556
unknown response ID.
557557

558-
How it runs: candidate runs are deleted in batches of 200 inside short `BEGIN IMMEDIATE`
559-
transactions, yielding to the event loop between batches, so requests keep being served. Each
560-
batch checks current readbacks, including internal runs without an API-key accounting record. Blobs
558+
How it runs: run selection advances in rowid windows of 200, including empty windows, up to
559+
the high-water mark at the start of the sweep. It does not scan retained prefixes again.
560+
Live deletion checks current age, scope, ancestry and readbacks inside each
561+
`BEGIN IMMEDIATE` transaction and yields between windows. A run that becomes eligible
562+
after its window was visited is picked up on a later sweep. Dry runs use the same windows
563+
without taking the writer lock. Blobs
561564
are removed after their rows commit; a crash in between leaves orphaned blobs, which the next
562565
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
563566
growing at the size of the retained window instead of shrinking.
@@ -566,6 +569,11 @@ A nonempty deletion batch writes a receipt in the same transaction. If the commi
566569
is lost, only the matching stored receipt lets the gateway publish the change, count the batch
567570
or unlink its blobs. Otherwise it reports `409 effect_outcome_unknown` and stops the sweep;
568571
earlier confirmed batches are not undone. It never reruns the uncertain delete.
572+
File pruning ignores its own receipt writes when tracking cached references, but still rechecks
573+
references when another writer has changed the database.
574+
575+
`node dist/bench/prune-candidates.js` measures candidate-query time on a temporary database
576+
with a large retained prefix ahead of expired rows. It does not invoke a model.
569577

570578
## 5. Known limits
571579

‎docs/zh-CN/stability.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -228,9 +228,12 @@ worker 已产出的文件共用同一个写锁探测器,按 owner 轮流取锁
228228

229229
预览和在线清理也会跳过正在核对检查点或结算回执的运行,无论是否有 API 密钥用量记录。每个删除批次都会重新核对,不沿用清理开始时的名单。
230230

231-
执行方式:候选运行按每批 200 个、在短的 `BEGIN IMMEDIATE` 事务里删除;在线争抢写锁时,在原 SQLite 超时预算内异步重试,只重试获取锁,不重放删除。保留祖先的委托后代也会保留;续接任务引用的产物仍可按原生产者授权下载,不因源运行过期而放宽权限。文件在对应的行提交后才删除;若中途崩溃,孤儿文件由下一次清理回收。在线删除后使用不等待读者退出的被动 WAL 检查点,WAL 可能保留空间供后续复用;离线清理仍使用 `wal_checkpoint(TRUNCATE)`。不加 `--vacuum` 不会主动缩小主数据库。
231+
执行方式:每次清理按 200 行的 rowid 窗口推进,跳过空窗口,不重复扫描已保留的前缀,也不越过开始时的行号上界。删除前在 `BEGIN IMMEDIATE` 事务内核对当前年龄、所有者、父子关系和待确认回执,窗口之间让出事件循环;已扫过的运行后来才符合条件,则等下一轮。预览用同样的窗口,不占写锁。在线争抢写锁时,在原 SQLite 超时预算内异步重试,只重试获取锁,不重放删除。保留祖先的委托后代也会保留;续接任务引用的产物仍可按原生产者授权下载,不因源运行过期而放宽权限。文件在对应的行提交后才删除;若中途崩溃,孤儿文件由下一次清理回收。在线删除后使用不等待读者退出的被动 WAL 检查点,WAL 可能保留空间供后续复用;离线清理仍使用 `wal_checkpoint(TRUNCATE)`。不加 `--vacuum` 不会主动缩小主数据库。
232232

233233
非空删除批次与回执在同一事务提交。提交确认丢失时,只有读回对应回执才计入结果、通知概览或删掉磁盘文件;无法核对则停止清理并返回 `409 effect_outcome_unknown`。已确认的前序批次不会撤销,也不会重做结果未知的删除。
234+
文件清理不会因本批自身写入回执就重扫引用;其他写入造成的变化仍会重新核对。
235+
236+
`node dist/bench/prune-candidates.js` 可在临时数据库里量化候选查询开销:前面是大量保留记录,后面是过期运行。不调用模型。
234237

235238
## 5. 已知限制
236239

‎src/store/prune-write.ts‎

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ export async function pruneWrite<T extends { ids: readonly string[] } | undefine
1212
live: boolean,
1313
profile: PruneProfile | undefined,
1414
mutate: () => T,
15-
committed?: (value: T, heldMs: number) => void,
15+
committed?: (value: T, heldMs: number, receiptChanges: number) => void,
1616
) {
1717
const started = performance.now();
1818
const budget = live ? Number(db.prepare('PRAGMA busy_timeout').get()!.timeout) : 0;
@@ -36,21 +36,24 @@ export async function pruneWrite<T extends { ids: readonly string[] } | undefine
3636
}
3737
const held = performance.now();
3838
let value: T;
39+
let receiptChanges = 0;
3940
try {
4041
value = mutate();
4142
// Keep one receipt in the same SQLite transaction as the deletes. A missing target row
4243
// or differently numbered receipt cannot prove which batch committed.
4344
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);
45+
if (receipt) {
46+
receiptChanges = Number(
47+
db
48+
.prepare(
49+
'INSERT INTO retention_batch_receipt(slot,receipt) VALUES(1,?) ' +
50+
'ON CONFLICT(slot) DO UPDATE SET receipt=excluded.receipt',
51+
)
52+
.run(receipt).changes,
53+
);
54+
if (receiptChanges !== 1)
55+
throw new Fault('persistence_failed', 'The maintenance receipt could not be written.', 500);
56+
}
5457
const phase = performance.now();
5558
try {
5659
db.exec('COMMIT');
@@ -73,7 +76,7 @@ export async function pruneWrite<T extends { ids: readonly string[] } | undefine
7376
}
7477
throw error;
7578
}
76-
committed?.(value, performance.now() - held);
79+
committed?.(value, performance.now() - held, receiptChanges);
7780
return value;
7881
}
7982

‎src/store/retention.ts‎

Lines changed: 58 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -101,8 +101,17 @@ function hasTable(db: DatabaseSync, name: string): boolean {
101101
return !!db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?").get(name);
102102
}
103103

104-
function candidateQuery(store: PrunableStore, cutoff: number, owner?: string) {
104+
function scanRunCandidates(store: PrunableStore, cutoff: number, batch: number, owner?: string) {
105105
const { db } = store;
106+
const ceiling = db.prepare('SELECT max(rowid) AS edge FROM runs');
107+
ceiling.setReadBigInts(true);
108+
const upper = ceiling.get()?.edge;
109+
let from = -(2n ** 63n);
110+
const endOfPage = db.prepare(`SELECT max(rowid) AS edge FROM (
111+
SELECT rowid FROM runs WHERE rowid BETWEEN :from AND :upper
112+
ORDER BY rowid LIMIT :batch
113+
)`);
114+
endOfPage.setReadBigInts(true);
106115
const readbacks = store.pendingRunReadbacks?.bind(store);
107116
const ledger = hasTable(db, 'platform_ledger'),
108117
workflows = hasTable(db, 'workflow_executions'),
@@ -121,23 +130,32 @@ function candidateQuery(store: PrunableStore, cutoff: number, owner?: string) {
121130
const parent = (a: string) =>
122131
`json_extract(CASE WHEN json_valid(${a}.payload) THEN ${a}.payload END,'$.metadata."oaa.parent_run_id"')`;
123132
// Follow only actual delegation chains, including protected grandparents. UNION terminates legacy cycles.
124-
const statement =
125-
db.prepare(`SELECT r.id,r.owner FROM runs r WHERE ${eligible('r')} ${owner === undefined ? '' : 'AND r.owner=:owner'}
133+
const statement = db.prepare(`SELECT r.id,r.owner FROM runs r NOT INDEXED
134+
WHERE r.rowid BETWEEN :from AND :edge ${owner === undefined ? '' : 'AND r.owner=:owner'}
135+
AND ${eligible('r')}
126136
AND (${parent('r')} IS NULL OR NOT EXISTS (
127137
WITH RECURSIVE ancestors(id) AS (SELECT ${parent('r')}
128138
UNION SELECT ${parent('p')} FROM runs p JOIN ancestors a ON p.id=a.id)
129139
SELECT 1 FROM ancestors a JOIN runs p ON p.id=a.id WHERE p.owner<>r.owner OR NOT coalesce((${eligible('p')}),0)
130-
)) ORDER BY r.rowid LIMIT :n`);
131-
return (n: number) =>
132-
statement
140+
)) ORDER BY r.rowid`);
141+
return () => {
142+
if (typeof upper !== 'bigint' || from > upper) return undefined;
143+
// Advance past raw rows, even if every row in this window must be kept.
144+
const edge = endOfPage.get({ from, upper, batch })?.edge;
145+
if (typeof edge !== 'bigint') return undefined;
146+
const runs = statement
133147
.all({
148+
from,
149+
edge,
134150
cutoff,
135-
n,
136151
...(owner === undefined ? {} : { owner }),
137152
// Snapshot current pins under the batch's write lock, not at the start of the sweep.
138153
...(readbacks ? { readbacks: JSON.stringify([...readbacks()]) } : {}),
139154
})
140155
.map((row) => ({ id: String(row.id), owner: String(row.owner) }));
156+
from = edge + 1n;
157+
return runs;
158+
};
141159
}
142160

143161
/** File ids still listed by a run that stays. */
@@ -210,18 +228,23 @@ async function executePrune(
210228
// Per-run rows of optional tables (present once their feature has been used).
211229
const runTables = ['api_key_run_tokens', 'webhook_announced'].filter((t) => hasTable(db, t));
212230
const dryIds = new Set<string>();
213-
const candidates = candidateQuery(store, cutoff, options.owner);
214-
if (dryRun) {
215-
// Count without deleting: walk the same candidate query to its end.
231+
const candidates = scanRunCandidates(store, cutoff, batch, options.owner);
232+
const scan = () => {
216233
const start = performance.now();
217-
const all = candidates(Number.MAX_SAFE_INTEGER);
218-
report.runs = all.length;
219-
for (const run of all) dryIds.add(run.id);
234+
const runs = candidates();
235+
profile?.add('candidate', start);
236+
return runs;
237+
};
238+
if (dryRun) {
220239
const count = db.prepare('SELECT count(*) AS n FROM events WHERE run_id=?');
221-
for (const run of all) {
222-
report.events += Number(count.get(run.id)!.n);
240+
for (let runs = scan(); runs; runs = scan()) {
241+
report.runs += runs.length;
242+
for (const run of runs) {
243+
dryIds.add(run.id);
244+
report.events += Number(count.get(run.id)!.n);
245+
}
246+
await pause();
223247
}
224-
profile?.add('candidate', start);
225248
} else {
226249
const preserveOrigins = prepareArtifactOrigins(db);
227250
for (;;) {
@@ -230,11 +253,10 @@ async function executePrune(
230253
!!options.live,
231254
profile,
232255
() => {
233-
const start = performance.now();
234-
const runs = candidates(batch);
235-
profile?.add('candidate', start);
236-
if (!runs.length) return undefined;
256+
const runs = scan();
257+
if (!runs) return undefined;
237258
const ids = runs.map((r) => r.id);
259+
if (!ids.length) return { ids, owners: [], events: 0 };
238260
const marks = ids.map(() => '?').join(',');
239261
const phase = performance.now();
240262
preserveOrigins.run(JSON.stringify(ids));
@@ -258,7 +280,7 @@ async function executePrune(
258280
return { ids, owners: [...new Set(runs.map((r) => r.owner))], events };
259281
},
260282
(result, held) => {
261-
if (!result) return;
283+
if (!result?.ids.length) return;
262284
pruneGeneration.value++;
263285
store.onRunsPruned?.(result.ids, result.owners);
264286
report.runs += result.ids.length;
@@ -286,13 +308,11 @@ async function executePrune(
286308
const revision = db.prepare(
287309
'SELECT total_changes() AS local, data_version AS external FROM pragma_data_version',
288310
);
311+
revision.setReadBigInts(true);
312+
const version = () => revision.get() as { local: bigint; external: bigint };
289313
let refs = new Set<string>(),
290-
refsAt: string | undefined,
314+
refsAt: ReturnType<typeof version> | undefined,
291315
position = 0;
292-
const version = () => {
293-
const r = revision.get()!;
294-
return `${r.local}:${r.external}`;
295-
};
296316
while (position < upper) {
297317
const scan = () => {
298318
const started = performance.now();
@@ -308,9 +328,12 @@ async function executePrune(
308328
? dryIds.has(String(r.run_id)) || !runExists.get(String(r.run_id))
309329
: Number(r.created) < cutoff,
310330
);
311-
if (candidates.length && refsAt !== version()) {
312-
refs = referencedFiles(db, dryIds, options.owner);
313-
refsAt = version();
331+
if (candidates.length) {
332+
const current = version();
333+
if (refsAt?.local !== current.local || refsAt?.external !== current.external) {
334+
refs = referencedFiles(db, dryIds, options.owner);
335+
refsAt = current;
336+
}
314337
}
315338
const doomed = candidates.filter((r) => !refs.has(`${r.owner}\0${r.id}`));
316339
const ids = doomed.map((r) => String(r.id));
@@ -332,7 +355,12 @@ async function executePrune(
332355
profile?.add('files', started);
333356
return { ids, bytes: doomed.reduce((n, r) => n + Number(r.bytes ?? 0), 0) };
334357
};
335-
const result = dryRun ? scan() : await pruneWrite(db, !!options.live, profile, scan);
358+
const result = dryRun
359+
? scan()
360+
: await pruneWrite(db, !!options.live, profile, scan, (_result, _held, receiptChanges) => {
361+
// The receipt is our own write. Do not absorb an external change after COMMIT.
362+
if (refsAt) refsAt.local += BigInt(receiptChanges);
363+
});
336364
report.files += result.ids.length;
337365
report.file_bytes += result.bytes;
338366
if (!dryRun) {

0 commit comments

Comments
 (0)