Skip to content

Commit 0b799d2

Browse files
author
hzq
committed
Stream orphaned blobs during the retention sweep
Bound directory buffering while preserving the final catalog and writer checks. Verify late claims, an active artifact stream, and memory use with a large directory fixture.
1 parent dca3bf1 commit 0b799d2

5 files changed

Lines changed: 240 additions & 7 deletions

File tree

‎bench/prune-orphan-sweep.ts‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import assert from 'node:assert/strict';
2+
import { mkdir, mkdtemp, rm, stat, utimes, writeFile } from 'node:fs/promises';
3+
import { tmpdir } from 'node:os';
4+
import path from 'node:path';
5+
import { parseArgs } from 'node:util';
6+
import { pruneChannel } from '../src/store/prune-profile.js';
7+
import { prune } from '../src/store/retention.js';
8+
import { Store } from '../src/store/store.js';
9+
10+
const { values } = parseArgs({
11+
options: {
12+
files: { type: 'string', default: '16384' },
13+
trials: { type: 'string', default: '3' },
14+
},
15+
});
16+
const files = Number(values.files);
17+
const trials = Number(values.trials);
18+
assert.ok(Number.isInteger(files) && files > 0 && files <= 65_536);
19+
assert.ok(Number.isInteger(trials) && trials > 0 && trials <= 10);
20+
const gc = global.gc;
21+
assert.ok(gc, 'Run with node --expose-gc');
22+
const name = (index: number) => 'file_' + index.toString(16).padStart(32, '0');
23+
24+
async function trial() {
25+
const root = await mkdtemp(path.join(tmpdir(), 'oaa-orphan-sweep-'));
26+
let store: Store | undefined;
27+
let sweepMs: number | undefined;
28+
const profile = (value: unknown) => {
29+
sweepMs = (value as { phase_ms: { sweep: number } }).phase_ms.sweep;
30+
};
31+
try {
32+
store = new Store(root);
33+
const db = store.db;
34+
const dir = path.join(root, 'files');
35+
await mkdir(dir, { recursive: true });
36+
const now = Date.now();
37+
const payload = JSON.stringify({ createdAt: now, bytes: 0 });
38+
const insert = db.prepare('INSERT INTO files(id,owner,subject,payload) VALUES(?,?,?,?)');
39+
db.exec('BEGIN IMMEDIATE');
40+
for (let i = 0; i < files; i++) insert.run(name(i), 'owner', 'fixture', payload);
41+
db.exec('COMMIT');
42+
for (let i = 0; i < files; i += 64)
43+
await Promise.all(
44+
Array.from({ length: Math.min(64, files - i) }, (_, n) =>
45+
writeFile(path.join(dir, name(i + n)), ''),
46+
),
47+
);
48+
const orphan = path.join(dir, name(files));
49+
const past = new Date(now - 120_000);
50+
await writeFile(orphan, 'old');
51+
await utimes(orphan, past, past);
52+
53+
gc!();
54+
const baseline = process.memoryUsage().heapUsed;
55+
let firstLookupHeap: number | undefined;
56+
let lookups = 0;
57+
const prepare = db.prepare.bind(db);
58+
db.prepare = (sql) => {
59+
const stmt = prepare(sql);
60+
if (sql === 'SELECT 1 FROM files WHERE id=?') {
61+
const get = stmt.get.bind(stmt);
62+
stmt.get = (...args: unknown[]) => {
63+
if (lookups++ === 0) {
64+
gc!();
65+
firstLookupHeap = process.memoryUsage().heapUsed - baseline;
66+
}
67+
return Reflect.apply(get, stmt, args) as ReturnType<typeof get>;
68+
};
69+
}
70+
return stmt;
71+
};
72+
pruneChannel.subscribe(profile);
73+
assert.equal((await prune(store, { olderThanMs: 60_000, now })).files, 0);
74+
assert.equal(lookups, files + 2);
75+
await assert.rejects(stat(orphan), { code: 'ENOENT' });
76+
assert.equal(db.prepare('SELECT count(*) AS n FROM files').get()!.n, files);
77+
assert.notEqual(firstLookupHeap, undefined);
78+
return { post_gc_heap_delta_at_first_lookup: firstLookupHeap, sweep_ms: sweepMs, lookups };
79+
} finally {
80+
pruneChannel.unsubscribe(profile);
81+
store?.close();
82+
await rm(root, { recursive: true, force: true });
83+
}
84+
}
85+
86+
const samples = [];
87+
for (let i = 0; i < trials; i++) samples.push(await trial());
88+
console.log(JSON.stringify({ files, samples }));

‎docs/stability.md‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -561,8 +561,10 @@ Live deletion checks current age, scope, ancestry and readbacks inside each
561561
`BEGIN IMMEDIATE` transaction and yields between windows. A run that becomes eligible
562562
after its window was visited is picked up on a later sweep. Dry runs use the same windows
563563
without taking the writer lock. Blobs
564-
are removed after their rows commit; a crash in between leaves orphaned blobs, which the next
565-
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
564+
are removed after their rows commit; a crash in between leaves orphaned blobs. A global prune
565+
walks the directory with a bounded read buffer instead of collecting all names and rechecks
566+
catalog rows, pending input claims and active writers before removing an old blob.
567+
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
566568
growing at the size of the retained window instead of shrinking.
567569

568570
A nonempty deletion batch writes a receipt in the same transaction. If the commit acknowledgement
@@ -577,6 +579,8 @@ sweep checks references again instead of trusting its cache.
577579

578580
`node dist/bench/prune-candidates.js` measures candidate-query time on a temporary database
579581
with a large retained prefix ahead of expired rows. It does not invoke a model.
582+
`node --expose-gc dist/bench/prune-orphan-sweep.js` measures the global directory sweep
583+
and retained heap at its first catalog lookup on a temporary directory.
580584

581585
## 5. Known limits
582586

‎docs/zh-CN/stability.md‎

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

233233
非空删除批次与回执在同一事务提交。提交确认丢失时,只有读回对应回执才计入结果、通知概览或删掉磁盘文件;无法核对则停止清理并返回 `409 effect_outcome_unknown`。已确认的前序批次不会撤销,也不会重做结果未知的删除。
234234
文件清理期间,本连接的运行或工作流写入与引用版本在同一事务提交,回滚不推进版本;回执和无关计费写入不再使缓存失效。其他连接写入时仍按 SQLite 的数据库版本保守重扫;临时跟踪失效或数据库结构变化时,也重新核对,不沿用旧引用。
235+
全局清理用有界缓冲逐步遍历孤立文件目录,不一次性载入文件名;删除旧文件前仍重新核对目录记录、待登记输入和正在写入的文件。
235236

236237
`node dist/bench/prune-candidates.js` 可在临时数据库里量化候选查询开销:前面是大量保留记录,后面是过期运行。不调用模型。
238+
`node --expose-gc dist/bench/prune-orphan-sweep.js` 可在临时目录测量全局清理耗时和首次核对目录记录时的堆内存保留量。
237239

238240
## 5. 已知限制
239241

‎src/store/retention.ts‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
* - blobs are removed after their rows are committed; a crash in between leaves orphan blobs,
2020
* which the next prune sweeps.
2121
*/
22-
import { lstat, opendir, readdir, rm, stat } from 'node:fs/promises';
22+
import { lstat, opendir, rm, stat } from 'node:fs/promises';
2323
import path from 'node:path';
2424
import type { DatabaseSync } from 'node:sqlite';
2525
import { Fault, sha } from '../core/util.js';
@@ -398,18 +398,20 @@ async function executePrune(
398398
/** Blobs left behind by an interrupted prune (row gone, file still on disk). */
399399
async function sweepOrphanBlobs(db: DatabaseSync, root: string, cutoff: number): Promise<void> {
400400
const dir = path.join(root, 'files');
401-
const names = await readdir(dir).catch(() => [] as string[]);
402401
const known = db.prepare('SELECT 1 FROM files WHERE id=?');
403402
const pending = hasTable(db, 'oaa_inline_inputs')
404403
? db.prepare('SELECT 1 FROM oaa_inline_inputs WHERE file_id=?')
405404
: undefined;
406405
const protectedBlob = (name: string) =>
407406
known.get(name) || pending?.get(name) || isStagingArtifact(db, name);
408-
for (const name of names) {
407+
const entries = await opendir(dir, { bufferSize: 128 }).catch(() => undefined);
408+
if (!entries) return;
409+
for await (const { name } of entries) {
409410
if (protectedBlob(name)) continue;
410-
const info = await stat(path.join(dir, name)).catch(() => undefined);
411+
const file = path.join(dir, name);
412+
const info = await stat(file).catch(() => undefined);
411413
if (info?.isFile() && info.mtimeMs < cutoff && !protectedBlob(name))
412-
await rm(path.join(dir, name), { force: true });
414+
await rm(file, { force: true });
413415
}
414416
}
415417

‎test/prune-orphans.test.ts‎

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
import assert from 'node:assert/strict';
2+
import { mkdir, readFile, readdir, utimes, writeFile } from 'node:fs/promises';
3+
import path from 'node:path';
4+
import { Readable } from 'node:stream';
5+
import test from 'node:test';
6+
import { isStagingArtifact, stageArtifact } from '../src/store/large-artifacts.js';
7+
import { prune } from '../src/store/retention.js';
8+
import { setup, waitFor } from './helpers.js';
9+
10+
test('orphan sweep continues past the first directory buffer without deleting younger files', async () => {
11+
const s = await setup();
12+
try {
13+
const dir = path.join(s.store.root, 'files');
14+
await mkdir(dir, { recursive: true });
15+
const past = new Date(Date.now() - 120_000);
16+
for (let i = 0; i < 300; i++) {
17+
const old = path.join(dir, 'orphan-' + i);
18+
await writeFile(old, 'expired');
19+
await utimes(old, past, past);
20+
}
21+
await writeFile(path.join(dir, 'fresh'), 'keep');
22+
await mkdir(path.join(dir, 'subdir'));
23+
await prune(s.store, { olderThanMs: 60_000 });
24+
assert.deepEqual((await readdir(dir)).sort(), ['fresh', 'subdir']);
25+
} finally {
26+
await s.cleanup();
27+
}
28+
});
29+
30+
test('orphan sweep rechecks file registrations and input claims made during the stat', async (t) => {
31+
const s = await setup();
32+
try {
33+
const db = s.store.db;
34+
const prepare = db.prepare.bind(db);
35+
const dir = path.join(s.store.root, 'files');
36+
const known = 'file_' + 'a'.repeat(32);
37+
const pending = 'file_' + 'b'.repeat(32);
38+
const orphan = 'file_' + 'c'.repeat(32);
39+
const past = new Date(Date.now() - 120_000);
40+
await mkdir(dir, { recursive: true });
41+
for (const name of [known, pending, orphan]) {
42+
const file = path.join(dir, name);
43+
await writeFile(file, name);
44+
await utimes(file, past, past);
45+
}
46+
const observed = new Set<string>();
47+
let failure: unknown;
48+
t.mock.method(db, 'prepare', (sql: string) => {
49+
const stmt = prepare(sql);
50+
if (sql !== 'SELECT 1 FROM files WHERE id=?') return stmt;
51+
const get = stmt.get.bind(stmt);
52+
t.mock.method(stmt, 'get', (...args: Parameters<typeof get>) => {
53+
const row = get(...args);
54+
const name = String(args[0]);
55+
if ((name === known || name === pending) && !observed.has(name) && !row) {
56+
observed.add(name);
57+
// The initial lookup saw no owner. The awaited stat lets this writer commit.
58+
queueMicrotask(() => {
59+
try {
60+
if (name === known) {
61+
prepare('INSERT INTO files(id,owner,subject,payload) VALUES(?,?,?,?)').run(
62+
known,
63+
'owner',
64+
'fixture',
65+
JSON.stringify({
66+
id: known,
67+
owner: 'owner',
68+
name: 'known.txt',
69+
bytes: known.length,
70+
createdAt: Date.now(),
71+
}),
72+
);
73+
} else {
74+
prepare(`INSERT INTO oaa_inline_inputs(file_id,owner,subject,digest,bytes,identity,phase)
75+
VALUES(?,?,?,?,?,?,'writing')`).run(
76+
pending,
77+
'owner',
78+
'fixture',
79+
'fixture',
80+
pending.length,
81+
'fixture',
82+
);
83+
}
84+
} catch (error) {
85+
failure = error;
86+
}
87+
});
88+
}
89+
return row;
90+
});
91+
return stmt;
92+
});
93+
await prune(s.store, { olderThanMs: 60_000, live: true });
94+
assert.ifError(failure);
95+
assert.deepEqual([...observed].sort(), [known, pending]);
96+
assert.equal(await readFile(path.join(dir, known), 'utf8'), known);
97+
assert.equal(await readFile(path.join(dir, pending), 'utf8'), pending);
98+
await assert.rejects(readFile(path.join(dir, orphan)), { code: 'ENOENT' });
99+
} finally {
100+
await s.cleanup();
101+
}
102+
});
103+
104+
test('an old-enough blob stays pinned during a real streaming artifact write', async () => {
105+
const s = await setup();
106+
const finish = Promise.withResolvers<void>();
107+
const dir = path.join(s.store.root, 'files');
108+
const source = Readable.from(
109+
(async function* () {
110+
yield Buffer.from('first');
111+
await finish.promise;
112+
yield Buffer.from('-last');
113+
})(),
114+
);
115+
const writing = stageArtifact(s.store, { owner: 'owner', name: 'fixture.txt', stream: source });
116+
void writing.catch(() => {});
117+
try {
118+
let id: string | undefined;
119+
await waitFor(async () => {
120+
id = (await readdir(dir).catch(() => []))[0];
121+
if (!id) return false;
122+
return (await readFile(path.join(dir, id), 'utf8')) === 'first';
123+
});
124+
assert.ok(id && isStagingArtifact(s.store.db, id));
125+
assert.equal(s.store.db.prepare('SELECT 1 FROM files WHERE id=?').get(id), undefined);
126+
await prune(s.store, { olderThanMs: 60_000, now: Date.now() + 120_000, live: true });
127+
assert.equal(await readFile(path.join(dir, id), 'utf8'), 'first');
128+
finish.resolve();
129+
const staged = await writing;
130+
assert.equal((await staged.commit()).id, id);
131+
assert.equal(await readFile(path.join(dir, id), 'utf8'), 'first-last');
132+
} finally {
133+
finish.resolve();
134+
await (await writing.catch(() => undefined))?.discard();
135+
await s.cleanup();
136+
}
137+
});

0 commit comments

Comments
 (0)