Skip to content

Commit b171dca

Browse files
author
hzq
committed
Preserve artifact blobs across uncertain publication commits
1 parent 682f12b commit b171dca

9 files changed

Lines changed: 382 additions & 21 deletions

File tree

‎docs/protocol.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -853,6 +853,7 @@ Error codes and response shapes do not depend on language; only the text of `mes
853853
| `data_placement_denied` | 403 | Input files are not allowed to be sent to this node |
854854
| `memory_too_large` | 413 | The memory entry exceeds 256 KB |
855855
| `artifact_integrity` | 502 | The native artifact digest does not match |
856+
| `artifact_commit_unconfirmed` | 409 | The artifact batch cannot be confirmed as committed or absent. No success receipt is issued and staging cleanup preserves its files. Inspect the run before retrying the producing operation. |
856857
| `artifacts_too_large` | 413 | The native artifact export exceeds the limit |
857858
| `unsafe_artifact` | 403 | The artifacts contain a symbolic link; automatic export was refused |
858859

‎docs/zh-CN/protocol.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -877,6 +877,7 @@ HTTP 错误响应默认使用形状 `{"error":{"code":"…","message":"…","typ
877877
| `data_placement_denied` | 403 | 输入文件不允许发送到该节点 |
878878
| `memory_too_large` | 413 | 记忆条目超过 256 KB |
879879
| `artifact_integrity` | 502 | 原生产物摘要不匹配 |
880+
| `artifact_commit_unconfirmed` | 409 | 无法确认整批产物已提交或不存在。不出具成功凭据,暂存清理保留文件;先核对运行记录,不要直接重放产生文件的操作。 |
880881
| `artifacts_too_large` | 413 | 原生产物导出超过上限 |
881882
| `unsafe_artifact` | 403 | 产物中含符号链接,拒绝自动导出 |
882883

‎src/core/errors-en.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@ export const ERROR_EN: Readonly<Record<string, readonly [string, string?]>> = {
154154
data_placement_denied: ['Input files are not allowed to be sent to this node.'],
155155
memory_too_large: ['The memory entry exceeds 256 KB.'],
156156
artifact_integrity: ['The native artifact digest does not match.'],
157+
artifact_commit_unconfirmed: ['The artifact metadata commit could not be confirmed. The files were retained.', 'Inspect the run and artifact records before repeating the producing operation.'],
157158
artifacts_too_large: ['The native artifact export exceeds the limit.'],
158159
unsafe_artifact: ['The artifacts contain a symbolic link; automatic export was refused.'],
159160
// tool

‎src/core/errors.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,7 @@ const ROWS: Row[] = [
212212
['data_placement_denied', 403, 'file', _, '输入文件不允许发送到该节点'],
213213
['memory_too_large', 413, 'file', _, '记忆条目超过 256 KB'],
214214
['artifact_integrity', 502, 'file', _, '原生产物摘要不匹配'],
215+
['artifact_commit_unconfirmed', 409, 'file', _, '产物元数据的提交结果不明,原文件已保留', '先核对运行和产物记录,不要重放产生文件的操作'],
215216
['artifacts_too_large', 413, 'file', _, '原生产物导出超过上限'],
216217
['unsafe_artifact', 403, 'file', _, '产物中含符号链接,拒绝自动导出'],
217218
// tool

‎src/fabric/artifact-transfer.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import {
1010
stageArtifact,
1111
type ArtifactStoreLike,
1212
} from '../store/large-artifacts.js';
13-
import { withSavepoint } from '../store/savepoint.js';
13+
import { publishArtifacts } from '../store/artifact-publication.js';
1414
import { ARTIFACT_CHUNK_BYTES, type ArtifactChunk } from './node-messages.js';
1515

1616
type WireArtifact = ArtifactPayload & { transferIndex?: number };
@@ -229,9 +229,10 @@ export class IncomingArtifacts {
229229
true,
230230
);
231231
if (items.length) {
232-
withSavepoint(this.store.db, () => {
233-
for (const { staged } of items) staged.commit();
234-
});
232+
publishArtifacts(
233+
this.store,
234+
items.map(({ staged }) => staged.publication),
235+
);
235236
for (const { payload, staged } of items)
236237
attachReceivedArtifact(this.store, payload, staged.record);
237238
}

‎src/store/artifact-publication.ts‎

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
import type { DatabaseSync, StatementSync } from 'node:sqlite';
2+
import { Fault } from '../core/util.js';
3+
import { isWriteUnavailable } from './checkpoint.js';
4+
import { withSavepoint } from './savepoint.js';
5+
6+
type Storage = { db: DatabaseSync; prepare(sql: string): StatementSync };
7+
const failed = () =>
8+
new Fault('persistence_failed', 'Could not publish the complete artifact batch.', 500, true);
9+
const unconfirmed = () =>
10+
new Fault(
11+
'artifact_commit_unconfirmed',
12+
'The artifact commit could not be confirmed. Its files were retained; do not repeat the producing operation.',
13+
409,
14+
true,
15+
);
16+
17+
/** Deletion rights belong to the staging operation, never to a failed acknowledgement. */
18+
export class ArtifactPublication {
19+
readonly payload: string;
20+
readonly id: string;
21+
readonly owner: string;
22+
private privateBlob = true;
23+
constructor(
24+
readonly store: Storage,
25+
record: { id: string; owner: string },
26+
readonly subject: string,
27+
private unpin: () => void,
28+
) {
29+
this.id = record.id;
30+
this.owner = record.owner;
31+
this.payload = JSON.stringify(record);
32+
}
33+
insert() {
34+
if (
35+
!this.privateBlob ||
36+
!this.store
37+
.prepare('INSERT INTO files(id,owner,payload,subject) VALUES(?,?,?,?)')
38+
.run(this.id, this.owner, this.payload, this.subject).changes
39+
)
40+
throw failed();
41+
}
42+
keep() {
43+
if (this.privateBlob) {
44+
this.privateBlob = false;
45+
this.unpin();
46+
}
47+
}
48+
async discard(remove: (stillAbsent: () => boolean) => Promise<void>) {
49+
if (!this.privateBlob) return;
50+
this.privateBlob = false;
51+
const absent = () => {
52+
try {
53+
return (
54+
!this.store.db.isTransaction &&
55+
!this.store.prepare('SELECT 1 FROM files WHERE id=?').get(this.id)
56+
);
57+
} catch {
58+
return false;
59+
}
60+
};
61+
try {
62+
if (absent()) await remove(absent);
63+
} finally {
64+
this.unpin();
65+
}
66+
}
67+
}
68+
69+
/** Publish all records together. A readback is one snapshot and checks the complete immutable
70+
* payload and both ownership columns. It never repeats an INSERT or grants a partial receipt. */
71+
export function publishArtifacts(store: Storage, items: readonly ArtifactPublication[]) {
72+
if (!items.length) return;
73+
if (store.db.isTransaction || items.some((p) => p.store.db !== store.db)) throw failed();
74+
const expected = new Map(items.map((p) => [p.id, p]));
75+
if (expected.size !== items.length) throw failed();
76+
const ids = JSON.stringify([...expected.keys()]);
77+
const inspect = () => {
78+
const rows = store
79+
.prepare(
80+
'SELECT id,owner,subject,payload FROM files WHERE id IN (SELECT value FROM json_each(?))',
81+
)
82+
.all(ids);
83+
if (!rows.length) return 'absent';
84+
return rows.length === items.length &&
85+
rows.every((r) => {
86+
const p = expected.get(String(r.id));
87+
return p && r.owner === p.owner && r.subject === p.subject && r.payload === p.payload;
88+
})
89+
? 'committed'
90+
: 'unknown';
91+
};
92+
let ready = false;
93+
try {
94+
withSavepoint(store.db, () => {
95+
for (const p of items) p.insert();
96+
if (inspect() !== 'committed') throw failed();
97+
ready = true;
98+
});
99+
if (store.db.isTransaction) throw failed();
100+
} catch (error) {
101+
let proof: 'committed' | 'absent' | 'unknown' = 'unknown';
102+
// Entry forbids an outer transaction. An unsuccessful savepoint cleanup must
103+
// not turn provisional rows on our connection into evidence of a commit.
104+
if (store.db.isTransaction)
105+
try {
106+
store.db.exec('ROLLBACK');
107+
} catch {
108+
/* Do not unlink on uncertainty. */
109+
}
110+
try {
111+
if (!store.db.isTransaction) proof = inspect();
112+
} catch {
113+
/* An unreadable catalog is not an empty one. */
114+
}
115+
if (proof === 'absent') throw error instanceof Fault ? error : failed();
116+
for (const p of items) p.keep();
117+
if (ready && isWriteUnavailable(error) && proof === 'committed') return;
118+
throw unconfirmed();
119+
}
120+
for (const p of items) p.keep();
121+
}

‎src/store/file-write.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
} from './large-artifacts.js';
88
import type { ProvisionalInputs } from './provisional-inputs.js';
99
import type { UploadPolicy } from './upload-budget.js';
10+
import { ArtifactPublication, publishArtifacts } from './artifact-publication.js';
1011

1112
export async function writeFileRecord(
1213
store: ArtifactStoreLike & { provisionalInputs: ProvisionalInputs },
@@ -31,7 +32,7 @@ export async function writeFileRecord(
3132
);
3233
else {
3334
await writePrivate(path.join(store.root, 'files'), file.id, bytes, true);
34-
insert();
35+
publishArtifacts(store, [new ArtifactPublication(store, file, subject, unpin)]);
3536
}
3637
} finally {
3738
unpin();

‎src/store/large-artifacts.ts‎

Lines changed: 45 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { createHash } from 'node:crypto';
2-
import { constants, type ReadStream } from 'node:fs';
3-
import { open, unlink, type FileHandle } from 'node:fs/promises';
2+
import { constants, type BigIntStats, type ReadStream } from 'node:fs';
3+
import { lstat, open, unlink, type FileHandle } from 'node:fs/promises';
44
import path from 'node:path';
55
import type { DatabaseSync, StatementSync } from 'node:sqlite';
66
import type { Readable } from 'node:stream';
@@ -9,6 +9,7 @@ import { LIMITS } from '../core/limits.js';
99
import { artifactMedia, type MediaKind } from '../core/media.js';
1010
import { Fault, id, relativeName, safePath } from '../core/util.js';
1111
import { restrictToOwner } from '../core/win-acl.js';
12+
import { ArtifactPublication, publishArtifacts } from './artifact-publication.js';
1213

1314
export type ArtifactStoreLike = {
1415
readonly root: string;
@@ -139,6 +140,29 @@ export async function stageArtifact(store: ArtifactStoreLike, params: ArtifactSo
139140
let total = 0;
140141
let succeeded = false;
141142
const unpin = trackStagingBlob(store.db, fileId);
143+
let mark: BigIntStats | undefined;
144+
const sameFile = (s: BigIntStats) =>
145+
!!mark?.ino &&
146+
s.isFile() &&
147+
s.dev === mark.dev &&
148+
s.ino === mark.ino &&
149+
s.birthtimeNs === mark.birthtimeNs &&
150+
s.size === mark.size;
151+
// Windows can finalize the modification time only after the last writer closes.
152+
const settleWindowsStamp = async () => {
153+
const closed = await lstat(target, { bigint: true }).catch(() => undefined);
154+
mark = closed && sameFile(closed) ? closed : undefined;
155+
};
156+
const removeOwned = async (stillAbsent: () => boolean) => {
157+
if (!mark?.ino) return;
158+
const actual = await lstat(target, { bigint: true }).catch((e: NodeJS.ErrnoException) => {
159+
if (e.code !== 'ENOENT') throw e;
160+
});
161+
if (actual && sameFile(actual) && actual.mtimeNs === mark.mtimeNs && stillAbsent())
162+
await unlink(target).catch((e: NodeJS.ErrnoException) => {
163+
if (e.code !== 'ENOENT') throw e;
164+
});
165+
};
142166
try {
143167
if (params.sourcePath) {
144168
const src = await open(params.sourcePath, constants.O_RDONLY | constants.O_NOFOLLOW);
@@ -184,8 +208,12 @@ export async function stageArtifact(store: ArtifactStoreLike, params: ArtifactSo
184208
if (params.expectedSha256 && digest !== params.expectedSha256)
185209
throw new Fault('artifact_integrity', 'Artifact digest does not match.', 502);
186210

211+
mark = await out.stat({ bigint: true });
187212
await out.close();
188-
if (process.platform === 'win32') await restrictToOwner(target);
213+
if (process.platform === 'win32') {
214+
await settleWindowsStamp();
215+
await restrictToOwner(target);
216+
}
189217

190218
const record: StoredArtifactRecord = {
191219
id: fileId,
@@ -197,29 +225,30 @@ export async function stageArtifact(store: ArtifactStoreLike, params: ArtifactSo
197225
allowedNodes: params.allowedNodes,
198226
runId: params.runId,
199227
};
228+
const publication = new ArtifactPublication(store, record, fileSubject, unpin);
200229
succeeded = true;
201230
return {
202231
record,
232+
publication,
203233
commit() {
204-
store
205-
.prepare('INSERT INTO files(id,owner,payload,subject) VALUES(?,?,?,?)')
206-
.run(record.id, params.owner, JSON.stringify(record), fileSubject);
207-
unpin();
234+
publishArtifacts(store, [publication]);
208235
return record;
209236
},
210-
async discard() {
211-
try {
212-
await unlink(target);
213-
} finally {
214-
unpin();
215-
}
216-
},
237+
discard: () => publication.discard(removeOwned),
217238
};
218239
} finally {
219240
if (!succeeded) {
220-
unpin();
241+
mark ??= await out.stat({ bigint: true }).catch(() => undefined);
221242
await out.close().catch(() => {});
222-
await unlink(target).catch(() => {});
243+
if (process.platform === 'win32') await settleWindowsStamp();
244+
try {
245+
await removeOwned(
246+
() =>
247+
!store.db.isTransaction && !store.prepare('SELECT 1 FROM files WHERE id=?').get(fileId),
248+
).catch(() => {});
249+
} finally {
250+
unpin();
251+
}
223252
}
224253
}
225254
}

0 commit comments

Comments
 (0)