@foldrun/core 22.2.0 → 22.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/records.d.ts +5 -0
- package/dist/src/runner.js +14 -0
- package/dist/src/step-state.d.ts +1 -1
- package/dist/src/test-writes-store.d.ts +17 -0
- package/dist/src/test-writes-store.js +170 -0
- package/dist/src/workspace-revisions.js +13 -3
- package/package.json +1 -1
- package/src/records.ts +2 -0
- package/src/runner.ts +12 -0
- package/src/step-state.ts +1 -1
- package/src/test-writes-store.ts +174 -0
- package/src/workspace-revisions.ts +13 -3
package/dist/src/records.d.ts
CHANGED
|
@@ -21,6 +21,11 @@ export interface RecordsPortAsync {
|
|
|
21
21
|
* step-state.ts is the only caller. */
|
|
22
22
|
stepGet?(tenant: string, workspace: string, runId: string, kind: string, ref: string): Promise<unknown | undefined>;
|
|
23
23
|
stepPut?(tenant: string, workspace: string, runId: string, kind: string, ref: string, data: unknown): Promise<void>;
|
|
24
|
+
/** Every row of one kind for a run (test writes: one row per file). Optional. */
|
|
25
|
+
stepList?(tenant: string, workspace: string, runId: string, kind: string): Promise<{
|
|
26
|
+
ref: string;
|
|
27
|
+
data: unknown;
|
|
28
|
+
}[]>;
|
|
24
29
|
/** `ref` null: every ref of the kind. */
|
|
25
30
|
stepDrop?(tenant: string, workspace: string, runId: string, kind: string, ref: string | null): Promise<void>;
|
|
26
31
|
/** The ids of the runs that have rows of this kind in the workspace. */
|
package/dist/src/runner.js
CHANGED
|
@@ -80,6 +80,7 @@ import { earlierTurns, conversationBlock } from "./conversation.js";
|
|
|
80
80
|
import { inputsNote } from "./run-inputs.js";
|
|
81
81
|
import { textCandidates } from "./input-text.js";
|
|
82
82
|
import { resolveClock, localDate } from "./clock.js";
|
|
83
|
+
import { restoreTestWrites, saveTestWrites } from "./test-writes-store.js";
|
|
83
84
|
export { localDate } from "./clock.js";
|
|
84
85
|
// An MCP tool definition becomes an SDK server config. ${SECRET} placeholders
|
|
85
86
|
// in env and headers resolve server-side, so a credential reaches the server
|
|
@@ -2610,6 +2611,7 @@ conversation) {
|
|
|
2610
2611
|
// The confinement boundary: agents in a workspace are one team, but the
|
|
2611
2612
|
// workspace is where isolation is enforced.
|
|
2612
2613
|
const workspaceRoot = path.resolve(agentDir, "..", "..");
|
|
2614
|
+
const workspaceName = path.basename(workspaceRoot);
|
|
2613
2615
|
// Where a test run's state/ and storage/ writes go, and the line each
|
|
2614
2616
|
// one leaves: under the run, beside its archived outputs.
|
|
2615
2617
|
const divertFor = (id) => ({
|
|
@@ -3405,6 +3407,11 @@ conversation) {
|
|
|
3405
3407
|
save();
|
|
3406
3408
|
}
|
|
3407
3409
|
let out;
|
|
3410
|
+
// A test run's earlier diverted writes, brought back if this worker
|
|
3411
|
+
// does not have them (another worker, a restart: FOL-126).
|
|
3412
|
+
// Not caught: a step must not run without what earlier steps wrote, nor
|
|
3413
|
+
// save an index short of it (Codex review).
|
|
3414
|
+
const twStart = testRun && runId && tenant ? (await restoreTestWrites(tenant, workspaceName, runId, divertFor(runId).to)).start : undefined;
|
|
3408
3415
|
try {
|
|
3409
3416
|
out = await runIsolated(a);
|
|
3410
3417
|
return out;
|
|
@@ -3418,6 +3425,10 @@ conversation) {
|
|
|
3418
3425
|
if (!out?.deferred)
|
|
3419
3426
|
step.roomWait = null;
|
|
3420
3427
|
save();
|
|
3428
|
+
// Last, after the bookkeeping: not caught — a step whose writes were
|
|
3429
|
+
// not kept fails (Codex review).
|
|
3430
|
+
if (testRun && runId && tenant)
|
|
3431
|
+
await saveTestWrites(tenant, workspaceName, runId, divertFor(runId).to, twStart);
|
|
3421
3432
|
}
|
|
3422
3433
|
};
|
|
3423
3434
|
let attemptFrom = step.events.length;
|
|
@@ -3824,6 +3835,7 @@ conversation) {
|
|
|
3824
3835
|
// sandbox to write instead, and afterwards what changed is moved
|
|
3825
3836
|
// under the run and the originals come back.
|
|
3826
3837
|
const attemptThrough = async (modelEnv, spec) => {
|
|
3838
|
+
const twStart = testRun && runId && tenant ? (await restoreTestWrites(tenant, workspaceName, runId, divertFor(runId).to)).start : undefined;
|
|
3827
3839
|
const before = testRun ? snapshotDivertedDirs(workspaceRoot) : null;
|
|
3828
3840
|
// What earlier steps of this test run wrote, laid over the real files
|
|
3829
3841
|
// for this attempt; restoreDivertedDirs puts the originals back.
|
|
@@ -3841,6 +3853,8 @@ conversation) {
|
|
|
3841
3853
|
if (before && runId) {
|
|
3842
3854
|
const d = divertFor(runId);
|
|
3843
3855
|
restoreDivertedDirs(workspaceRoot, before, d.to, d.note, handed ?? before);
|
|
3856
|
+
if (tenant)
|
|
3857
|
+
await saveTestWrites(tenant, workspaceName, runId, d.to, twStart);
|
|
3844
3858
|
}
|
|
3845
3859
|
}
|
|
3846
3860
|
};
|
package/dist/src/step-state.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type StepStateKind = "handed-in" | "base" | "storage";
|
|
1
|
+
export type StepStateKind = "handed-in" | "base" | "storage" | "test-writes";
|
|
2
2
|
/** Stored as a row? False: the caller writes the file. */
|
|
3
3
|
export declare function putStepState(tenant: string | undefined, workspace: string, runId: string, kind: StepStateKind, ref: string, data: unknown): Promise<boolean>;
|
|
4
4
|
/** The row, or undefined (look at the file). */
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** After a step: the run's diverted files into the store, one row each.
|
|
2
|
+
* Throws: a step whose writes were not kept must not count as done. */
|
|
3
|
+
/** What the folder held when an attempt started (restoreTestWrites' answer):
|
|
4
|
+
* a save writes only what the attempt changed from it, so a file another
|
|
5
|
+
* step changed meanwhile on another worker is never written back stale
|
|
6
|
+
* (Codex review). */
|
|
7
|
+
export type TestWritesStart = Map<string, {
|
|
8
|
+
sha: string;
|
|
9
|
+
mtimeMs: number;
|
|
10
|
+
}>;
|
|
11
|
+
export declare function saveTestWrites(tenant: string, workspace: string, runId: string, dir: string, start?: TestWritesStart): Promise<number>;
|
|
12
|
+
/** Before a step: what the rows name and this worker's folder lacks (or has
|
|
13
|
+
* at another time). Throws: a step must not run without what earlier steps wrote. */
|
|
14
|
+
export declare function restoreTestWrites(tenant: string, workspace: string, runId: string, dir: string): Promise<{
|
|
15
|
+
restored: number;
|
|
16
|
+
start: TestWritesStart;
|
|
17
|
+
}>;
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
// A test run's diverted writes, kept off the pod's disk (FOL-126, the shared
|
|
2
|
+
// volume retired): what a test run's steps wrote to state/ and storage/ goes
|
|
3
|
+
// under runs/<id>/test-writes/ on the worker that ran the step, and the next
|
|
4
|
+
// step — on any worker, after any restart — must see it. So after each step
|
|
5
|
+
// the folder's files are put in the blob store (pinned by the run) and listed
|
|
6
|
+
// in one step-state row; before each step the files that row names and the
|
|
7
|
+
// folder lacks are brought back. Without a database or a blob store (a laptop,
|
|
8
|
+
// the CLI) nothing changes: the folder is all there is.
|
|
9
|
+
import fs from "node:fs";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import { dropStepState } from "./step-state.js";
|
|
12
|
+
import { records } from "./records.js";
|
|
13
|
+
import { revisionBackend } from "./workspace-revisions.js";
|
|
14
|
+
import { blobObjectKey, sha256Hex } from "./manifest.js";
|
|
15
|
+
import { readAll } from "./blob-types.js";
|
|
16
|
+
import { registerRunRemovedHook } from "./store.js";
|
|
17
|
+
import { opsError } from "./ops-log.js";
|
|
18
|
+
import { processState } from "./process-state.js";
|
|
19
|
+
const KIND = "test-writes";
|
|
20
|
+
/** Per run folder on this worker: the version of each file it last brought
|
|
21
|
+
* back or saved. A local file that differs from it is a change not saved yet
|
|
22
|
+
* (another step of the run on this worker); one equal to it is a copy the
|
|
23
|
+
* rows may update. File times never decide this (Codex review). */
|
|
24
|
+
const KNOWN = processState("test-writes-known", () => new Map());
|
|
25
|
+
const knownOf = (dir) => {
|
|
26
|
+
let m = KNOWN.get(dir);
|
|
27
|
+
if (!m)
|
|
28
|
+
KNOWN.set(dir, (m = new Map()));
|
|
29
|
+
return m;
|
|
30
|
+
};
|
|
31
|
+
const holderOf = (runId) => ({ kind: "run", id: `test-writes:${runId}` });
|
|
32
|
+
/** A diverted file kept whole up to this; a bigger one stays on the worker
|
|
33
|
+
* that wrote it (and is named in the ops line), as before. */
|
|
34
|
+
const MAX_FILE = 64 * 1024 * 1024;
|
|
35
|
+
function walk(root) {
|
|
36
|
+
const out = [];
|
|
37
|
+
if (!fs.existsSync(root))
|
|
38
|
+
return out;
|
|
39
|
+
for (const e of fs.readdirSync(root, { recursive: true, withFileTypes: true })) {
|
|
40
|
+
if (!e.isFile())
|
|
41
|
+
continue; // links and the rest never leave the worker
|
|
42
|
+
const abs = path.join(e.parentPath, e.name);
|
|
43
|
+
out.push({ rel: path.relative(root, abs).replaceAll("\\", "/"), abs });
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
/** The rows' port (null: a laptop, no records port), and whether new rows
|
|
48
|
+
* are written (`runs.step_state_store`). Rows already there are READ either
|
|
49
|
+
* way, as step state's are (Codex review). */
|
|
50
|
+
function rowsPort(tenant, workspace) {
|
|
51
|
+
const p = records(tenant, workspace);
|
|
52
|
+
if (!p?.async?.stepPut || !p.async.stepList || !p.async.stepDrop)
|
|
53
|
+
return null;
|
|
54
|
+
let on = false;
|
|
55
|
+
try {
|
|
56
|
+
on = p.stepStateOn?.() === true;
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
on = false;
|
|
60
|
+
}
|
|
61
|
+
return { port: p.async, on };
|
|
62
|
+
}
|
|
63
|
+
/** One row per file, keyed by its path's hash: two steps of the run saving at
|
|
64
|
+
* once (a parallel group on two workers) each write their own rows, never
|
|
65
|
+
* one index over the other (Codex review). */
|
|
66
|
+
const refOf = (rel) => sha256Hex(Buffer.from(rel)).slice(0, 40);
|
|
67
|
+
function snapshot(dir) {
|
|
68
|
+
const m = new Map();
|
|
69
|
+
for (const f of walk(dir))
|
|
70
|
+
m.set(f.rel, { sha: sha256Hex(fs.readFileSync(f.abs)), mtimeMs: fs.statSync(f.abs).mtimeMs });
|
|
71
|
+
return m;
|
|
72
|
+
}
|
|
73
|
+
export async function saveTestWrites(tenant, workspace, runId, dir, start) {
|
|
74
|
+
const deps = revisionBackend();
|
|
75
|
+
const rp = rowsPort(tenant, workspace);
|
|
76
|
+
if (!deps || !rp)
|
|
77
|
+
return 0;
|
|
78
|
+
const { port, on } = rp;
|
|
79
|
+
const prior = new Map((await port.stepList(tenant, workspace, runId, KIND)).map((r) => [r.data.path, r.data]));
|
|
80
|
+
let saved = 0;
|
|
81
|
+
for (const f of walk(dir)) {
|
|
82
|
+
const st = fs.statSync(f.abs);
|
|
83
|
+
const was = prior.get(f.rel);
|
|
84
|
+
if (!on) {
|
|
85
|
+
// Rows switched off: the folder is the record; an old row for this file
|
|
86
|
+
// goes, so it is never restored over the newer one.
|
|
87
|
+
if (was && (was.size !== st.size || was.sha !== sha256Hex(fs.readFileSync(f.abs))))
|
|
88
|
+
await port.stepDrop(tenant, workspace, runId, KIND, refOf(f.rel));
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
if (st.size > MAX_FILE) {
|
|
92
|
+
// Not kept elsewhere, so the step fails rather than let an older copy
|
|
93
|
+
// come back over it on the next step (Codex review).
|
|
94
|
+
throw new Error(`a test run's diverted file is over ${MAX_FILE / 1024 / 1024} MiB and cannot be kept for the next step`);
|
|
95
|
+
}
|
|
96
|
+
const bytes = fs.readFileSync(f.abs);
|
|
97
|
+
const sha = sha256Hex(bytes);
|
|
98
|
+
if (was && was.sha === sha && was.mtimeMs === st.mtimeMs)
|
|
99
|
+
continue; // a newer time with the same bytes counts
|
|
100
|
+
const atStart = start?.get(f.rel);
|
|
101
|
+
// Unchanged by this attempt AND already kept: another step's newer copy
|
|
102
|
+
// stays; a file never kept (the store switched on mid-run) is kept now.
|
|
103
|
+
if (was && atStart && atStart.sha === sha && atStart.mtimeMs === st.mtimeMs)
|
|
104
|
+
continue;
|
|
105
|
+
if (was?.sha !== sha) {
|
|
106
|
+
await deps.pins?.pinBlobs(tenant, [sha], holderOf(runId));
|
|
107
|
+
await deps.blobs.putIfAbsent(blobObjectKey(tenant, sha), bytes);
|
|
108
|
+
}
|
|
109
|
+
await port.stepPut(tenant, workspace, runId, KIND, refOf(f.rel), { path: f.rel, sha, size: bytes.length, mtimeMs: st.mtimeMs });
|
|
110
|
+
knownOf(dir).set(f.rel, sha);
|
|
111
|
+
saved++;
|
|
112
|
+
}
|
|
113
|
+
return saved;
|
|
114
|
+
}
|
|
115
|
+
/** Before a step: what the rows name and this worker's folder lacks (or has
|
|
116
|
+
* at another time). Throws: a step must not run without what earlier steps wrote. */
|
|
117
|
+
export async function restoreTestWrites(tenant, workspace, runId, dir) {
|
|
118
|
+
const deps = revisionBackend();
|
|
119
|
+
const rp = rowsPort(tenant, workspace);
|
|
120
|
+
if (!deps || !rp)
|
|
121
|
+
return { restored: 0, start: new Map() }; // nothing kept elsewhere: nothing to compare (a laptop hashes nothing)
|
|
122
|
+
const { port } = rp;
|
|
123
|
+
let n = 0;
|
|
124
|
+
for (const row of await port.stepList(tenant, workspace, runId, KIND)) {
|
|
125
|
+
const f = row.data;
|
|
126
|
+
if (typeof f?.path !== "string" || refOf(f.path) !== row.ref)
|
|
127
|
+
continue;
|
|
128
|
+
const abs = path.resolve(dir, f.path);
|
|
129
|
+
if (!abs.startsWith(path.resolve(dir) + path.sep))
|
|
130
|
+
continue; // names stay inside the folder
|
|
131
|
+
const t = new Date(f.mtimeMs);
|
|
132
|
+
const known = knownOf(dir);
|
|
133
|
+
if (fs.existsSync(abs)) {
|
|
134
|
+
const local = sha256Hex(fs.readFileSync(abs));
|
|
135
|
+
if (local === f.sha) {
|
|
136
|
+
known.set(f.path, f.sha);
|
|
137
|
+
if (Math.round(fs.statSync(abs).mtimeMs) !== Math.round(f.mtimeMs))
|
|
138
|
+
fs.utimesSync(abs, t, t);
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
// Changed here since this process last brought or saved it: another
|
|
142
|
+
// step of the run wrote it and has not saved yet — kept (Codex review).
|
|
143
|
+
// No record at all (a restart: no step of this process is mid-write)
|
|
144
|
+
// means a stale copy, refreshed from the rows.
|
|
145
|
+
const was = known.get(f.path);
|
|
146
|
+
if (was !== undefined && local !== was)
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
const bytes = await readAll(deps.blobs, blobObjectKey(tenant, f.sha));
|
|
150
|
+
if (sha256Hex(bytes) !== f.sha)
|
|
151
|
+
throw new Error("a diverted file's object does not hash to its name — refused");
|
|
152
|
+
fs.mkdirSync(path.dirname(abs), { recursive: true });
|
|
153
|
+
fs.writeFileSync(abs, bytes);
|
|
154
|
+
fs.utimesSync(abs, t, t); // a verify that asks whether a file is fresh answers for the step that wrote it
|
|
155
|
+
known.set(f.path, f.sha);
|
|
156
|
+
n++;
|
|
157
|
+
}
|
|
158
|
+
return { restored: n, start: snapshot(dir) };
|
|
159
|
+
}
|
|
160
|
+
/** A run deleted: its diverted files' pins and row go. */
|
|
161
|
+
registerRunRemovedHook((tenant, workspace, runId) => {
|
|
162
|
+
for (const dir of [...KNOWN.keys()])
|
|
163
|
+
if (dir.includes(`${path.sep}runs${path.sep}${runId}${path.sep}`))
|
|
164
|
+
KNOWN.delete(dir);
|
|
165
|
+
const deps = revisionBackend();
|
|
166
|
+
void (async () => {
|
|
167
|
+
await deps?.pins?.release(tenant, holderOf(runId));
|
|
168
|
+
await dropStepState(tenant, workspace, runId, KIND, null);
|
|
169
|
+
})().catch((err) => opsError("test_writes.release_failed", err, { tenant, workspace, runId }, "warn"));
|
|
170
|
+
}, "test-writes");
|
|
@@ -1616,7 +1616,7 @@ async function syncNow(tenant, workspace) {
|
|
|
1616
1616
|
return "skipped"; // a write landed meanwhile: next round
|
|
1617
1617
|
const bytes = await blobBytes(deps, tenant, e.sha);
|
|
1618
1618
|
if (!bytes)
|
|
1619
|
-
throw new Error(`revisions: blob ${e.sha.slice(0, 12)}
|
|
1619
|
+
throw new Error(`revisions: blob ${e.sha.slice(0, 12)} is missing`); // no file path: ops lines carry no customer content
|
|
1620
1620
|
const abs = path.join(dir, p);
|
|
1621
1621
|
// Never through a link: a folder on the way that is a symlink could lead
|
|
1622
1622
|
// outside the workspace (Codex review). Such a path is left as it is.
|
|
@@ -1725,11 +1725,21 @@ export async function syncAllFromHeads() {
|
|
|
1725
1725
|
}
|
|
1726
1726
|
// ------------------------------------------------------------- reading
|
|
1727
1727
|
async function blobBytes(deps, tenant, sha) {
|
|
1728
|
+
// An object is named by its content: bytes that do not hash to the name
|
|
1729
|
+
// (corruption, or a store someone wrote to) are refused — never written into
|
|
1730
|
+
// a pod's copy, staged into a run or served (FOL-126 security review).
|
|
1731
|
+
const checked = (b, from) => {
|
|
1732
|
+
if (sha256Hex(b) !== sha) {
|
|
1733
|
+
opsError("revisions.blob_mismatch", new Error(`blob ${sha.slice(0, 12)} does not hash to its name`), { tenant, surface: from });
|
|
1734
|
+
throw new Error(`revisions: blob ${sha.slice(0, 12)}… does not hash to its name — refused`);
|
|
1735
|
+
}
|
|
1736
|
+
return b;
|
|
1737
|
+
};
|
|
1728
1738
|
const hit = await S.cache?.get(tenant, sha);
|
|
1729
1739
|
if (hit)
|
|
1730
|
-
return hit;
|
|
1740
|
+
return checked(hit, "cache");
|
|
1731
1741
|
try {
|
|
1732
|
-
const b = await readAll(deps.blobs, blobObjectKey(tenant, sha));
|
|
1742
|
+
const b = checked(await readAll(deps.blobs, blobObjectKey(tenant, sha)), "store");
|
|
1733
1743
|
void S.cache?.put(tenant, sha, b).catch(() => { });
|
|
1734
1744
|
return b;
|
|
1735
1745
|
}
|
package/package.json
CHANGED
package/src/records.ts
CHANGED
|
@@ -39,6 +39,8 @@ export interface RecordsPortAsync {
|
|
|
39
39
|
* step-state.ts is the only caller. */
|
|
40
40
|
stepGet?(tenant: string, workspace: string, runId: string, kind: string, ref: string): Promise<unknown | undefined>;
|
|
41
41
|
stepPut?(tenant: string, workspace: string, runId: string, kind: string, ref: string, data: unknown): Promise<void>;
|
|
42
|
+
/** Every row of one kind for a run (test writes: one row per file). Optional. */
|
|
43
|
+
stepList?(tenant: string, workspace: string, runId: string, kind: string): Promise<{ ref: string; data: unknown }[]>;
|
|
42
44
|
/** `ref` null: every ref of the kind. */
|
|
43
45
|
stepDrop?(tenant: string, workspace: string, runId: string, kind: string, ref: string | null): Promise<void>;
|
|
44
46
|
/** The ids of the runs that have rows of this kind in the workspace. */
|
package/src/runner.ts
CHANGED
|
@@ -134,6 +134,7 @@ import { earlierTurns, conversationBlock, type RunContext, type RunInput } from
|
|
|
134
134
|
import { inputsNote, type RunInputFile } from "./run-inputs.ts";
|
|
135
135
|
import { textCandidates } from "./input-text.ts";
|
|
136
136
|
import { resolveClock, localDate, type ClockChoice } from "./clock.ts";
|
|
137
|
+
import { restoreTestWrites, saveTestWrites } from "./test-writes-store.ts";
|
|
137
138
|
|
|
138
139
|
export { localDate } from "./clock.ts";
|
|
139
140
|
|
|
@@ -2823,6 +2824,7 @@ async function runStepBody(
|
|
|
2823
2824
|
// The confinement boundary: agents in a workspace are one team, but the
|
|
2824
2825
|
// workspace is where isolation is enforced.
|
|
2825
2826
|
const workspaceRoot = path.resolve(agentDir, "..", "..");
|
|
2827
|
+
const workspaceName = path.basename(workspaceRoot);
|
|
2826
2828
|
// Where a test run's state/ and storage/ writes go, and the line each
|
|
2827
2829
|
// one leaves: under the run, beside its archived outputs.
|
|
2828
2830
|
const divertFor = (id: string) => ({
|
|
@@ -3619,6 +3621,11 @@ async function runStepBody(
|
|
|
3619
3621
|
save();
|
|
3620
3622
|
}
|
|
3621
3623
|
let out: Awaited<ReturnType<typeof runIsolated>> | undefined;
|
|
3624
|
+
// A test run's earlier diverted writes, brought back if this worker
|
|
3625
|
+
// does not have them (another worker, a restart: FOL-126).
|
|
3626
|
+
// Not caught: a step must not run without what earlier steps wrote, nor
|
|
3627
|
+
// save an index short of it (Codex review).
|
|
3628
|
+
const twStart = testRun && runId && tenant ? (await restoreTestWrites(tenant, workspaceName, runId, divertFor(runId).to)).start : undefined;
|
|
3622
3629
|
try {
|
|
3623
3630
|
out = await runIsolated(a);
|
|
3624
3631
|
return out;
|
|
@@ -3630,6 +3637,9 @@ async function runStepBody(
|
|
|
3630
3637
|
// back to the queue keeps its place in line.
|
|
3631
3638
|
if (!out?.deferred) step.roomWait = null;
|
|
3632
3639
|
save();
|
|
3640
|
+
// Last, after the bookkeeping: not caught — a step whose writes were
|
|
3641
|
+
// not kept fails (Codex review).
|
|
3642
|
+
if (testRun && runId && tenant) await saveTestWrites(tenant, workspaceName, runId, divertFor(runId).to, twStart);
|
|
3633
3643
|
}
|
|
3634
3644
|
};
|
|
3635
3645
|
let attemptFrom = step.events.length;
|
|
@@ -4037,6 +4047,7 @@ async function runStepBody(
|
|
|
4037
4047
|
// sandbox to write instead, and afterwards what changed is moved
|
|
4038
4048
|
// under the run and the originals come back.
|
|
4039
4049
|
const attemptThrough = async (modelEnv: Record<string, string | undefined>, spec: TranslatorSpec | null) => {
|
|
4050
|
+
const twStart = testRun && runId && tenant ? (await restoreTestWrites(tenant, workspaceName, runId, divertFor(runId).to)).start : undefined;
|
|
4040
4051
|
const before = testRun ? snapshotDivertedDirs(workspaceRoot) : null;
|
|
4041
4052
|
// What earlier steps of this test run wrote, laid over the real files
|
|
4042
4053
|
// for this attempt; restoreDivertedDirs puts the originals back.
|
|
@@ -4053,6 +4064,7 @@ async function runStepBody(
|
|
|
4053
4064
|
if (before && runId) {
|
|
4054
4065
|
const d = divertFor(runId);
|
|
4055
4066
|
restoreDivertedDirs(workspaceRoot, before, d.to, d.note, handed ?? before);
|
|
4067
|
+
if (tenant) await saveTestWrites(tenant, workspaceName, runId, d.to, twStart);
|
|
4056
4068
|
}
|
|
4057
4069
|
}
|
|
4058
4070
|
};
|
package/src/step-state.ts
CHANGED
|
@@ -20,7 +20,7 @@ import fs from "node:fs";
|
|
|
20
20
|
import path from "node:path";
|
|
21
21
|
import { records } from "./records.ts";
|
|
22
22
|
|
|
23
|
-
export type StepStateKind = "handed-in" | "base" | "storage";
|
|
23
|
+
export type StepStateKind = "handed-in" | "base" | "storage" | "test-writes";
|
|
24
24
|
|
|
25
25
|
const SAFE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$/;
|
|
26
26
|
const okIds = (runId: string, ref: string) => SAFE.test(runId) && (ref === "" || SAFE.test(ref));
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// A test run's diverted writes, kept off the pod's disk (FOL-126, the shared
|
|
2
|
+
// volume retired): what a test run's steps wrote to state/ and storage/ goes
|
|
3
|
+
// under runs/<id>/test-writes/ on the worker that ran the step, and the next
|
|
4
|
+
// step — on any worker, after any restart — must see it. So after each step
|
|
5
|
+
// the folder's files are put in the blob store (pinned by the run) and listed
|
|
6
|
+
// in one step-state row; before each step the files that row names and the
|
|
7
|
+
// folder lacks are brought back. Without a database or a blob store (a laptop,
|
|
8
|
+
// the CLI) nothing changes: the folder is all there is.
|
|
9
|
+
|
|
10
|
+
import fs from "node:fs";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { dropStepState } from "./step-state.ts";
|
|
13
|
+
import { records } from "./records.ts";
|
|
14
|
+
import { revisionBackend } from "./workspace-revisions.ts";
|
|
15
|
+
import { blobObjectKey, sha256Hex } from "./manifest.ts";
|
|
16
|
+
import { readAll } from "./blob-types.ts";
|
|
17
|
+
import { registerRunRemovedHook } from "./store.ts";
|
|
18
|
+
import { opsError } from "./ops-log.ts";
|
|
19
|
+
import { processState } from "./process-state.ts";
|
|
20
|
+
|
|
21
|
+
interface Listed {
|
|
22
|
+
sha: string;
|
|
23
|
+
size: number;
|
|
24
|
+
mtimeMs: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const KIND = "test-writes" as const;
|
|
28
|
+
/** Per run folder on this worker: the version of each file it last brought
|
|
29
|
+
* back or saved. A local file that differs from it is a change not saved yet
|
|
30
|
+
* (another step of the run on this worker); one equal to it is a copy the
|
|
31
|
+
* rows may update. File times never decide this (Codex review). */
|
|
32
|
+
const KNOWN = processState("test-writes-known", () => new Map<string, Map<string, string>>());
|
|
33
|
+
const knownOf = (dir: string) => {
|
|
34
|
+
let m = KNOWN.get(dir);
|
|
35
|
+
if (!m) KNOWN.set(dir, (m = new Map()));
|
|
36
|
+
return m;
|
|
37
|
+
};
|
|
38
|
+
const holderOf = (runId: string) => ({ kind: "run" as const, id: `test-writes:${runId}` });
|
|
39
|
+
/** A diverted file kept whole up to this; a bigger one stays on the worker
|
|
40
|
+
* that wrote it (and is named in the ops line), as before. */
|
|
41
|
+
const MAX_FILE = 64 * 1024 * 1024;
|
|
42
|
+
|
|
43
|
+
function walk(root: string): { rel: string; abs: string }[] {
|
|
44
|
+
const out: { rel: string; abs: string }[] = [];
|
|
45
|
+
if (!fs.existsSync(root)) return out;
|
|
46
|
+
for (const e of fs.readdirSync(root, { recursive: true, withFileTypes: true })) {
|
|
47
|
+
if (!e.isFile()) continue; // links and the rest never leave the worker
|
|
48
|
+
const abs = path.join(e.parentPath, e.name);
|
|
49
|
+
out.push({ rel: path.relative(root, abs).replaceAll("\\", "/"), abs });
|
|
50
|
+
}
|
|
51
|
+
return out;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The rows' port (null: a laptop, no records port), and whether new rows
|
|
55
|
+
* are written (`runs.step_state_store`). Rows already there are READ either
|
|
56
|
+
* way, as step state's are (Codex review). */
|
|
57
|
+
function rowsPort(tenant: string, workspace: string) {
|
|
58
|
+
const p = records(tenant, workspace);
|
|
59
|
+
if (!p?.async?.stepPut || !p.async.stepList || !p.async.stepDrop) return null;
|
|
60
|
+
let on = false;
|
|
61
|
+
try {
|
|
62
|
+
on = p.stepStateOn?.() === true;
|
|
63
|
+
} catch {
|
|
64
|
+
on = false;
|
|
65
|
+
}
|
|
66
|
+
return { port: p.async, on };
|
|
67
|
+
}
|
|
68
|
+
/** One row per file, keyed by its path's hash: two steps of the run saving at
|
|
69
|
+
* once (a parallel group on two workers) each write their own rows, never
|
|
70
|
+
* one index over the other (Codex review). */
|
|
71
|
+
const refOf = (rel: string) => sha256Hex(Buffer.from(rel)).slice(0, 40);
|
|
72
|
+
|
|
73
|
+
/** After a step: the run's diverted files into the store, one row each.
|
|
74
|
+
* Throws: a step whose writes were not kept must not count as done. */
|
|
75
|
+
/** What the folder held when an attempt started (restoreTestWrites' answer):
|
|
76
|
+
* a save writes only what the attempt changed from it, so a file another
|
|
77
|
+
* step changed meanwhile on another worker is never written back stale
|
|
78
|
+
* (Codex review). */
|
|
79
|
+
export type TestWritesStart = Map<string, { sha: string; mtimeMs: number }>;
|
|
80
|
+
|
|
81
|
+
function snapshot(dir: string): TestWritesStart {
|
|
82
|
+
const m: TestWritesStart = new Map();
|
|
83
|
+
for (const f of walk(dir)) m.set(f.rel, { sha: sha256Hex(fs.readFileSync(f.abs)), mtimeMs: fs.statSync(f.abs).mtimeMs });
|
|
84
|
+
return m;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export async function saveTestWrites(tenant: string, workspace: string, runId: string, dir: string, start?: TestWritesStart): Promise<number> {
|
|
88
|
+
const deps = revisionBackend();
|
|
89
|
+
const rp = rowsPort(tenant, workspace);
|
|
90
|
+
if (!deps || !rp) return 0;
|
|
91
|
+
const { port, on } = rp;
|
|
92
|
+
const prior = new Map((await port.stepList!(tenant, workspace, runId, KIND)).map((r) => [(r.data as Listed & { path: string }).path, r.data as Listed]));
|
|
93
|
+
let saved = 0;
|
|
94
|
+
for (const f of walk(dir)) {
|
|
95
|
+
const st = fs.statSync(f.abs);
|
|
96
|
+
const was = prior.get(f.rel);
|
|
97
|
+
if (!on) {
|
|
98
|
+
// Rows switched off: the folder is the record; an old row for this file
|
|
99
|
+
// goes, so it is never restored over the newer one.
|
|
100
|
+
if (was && (was.size !== st.size || was.sha !== sha256Hex(fs.readFileSync(f.abs)))) await port.stepDrop!(tenant, workspace, runId, KIND, refOf(f.rel));
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
if (st.size > MAX_FILE) {
|
|
104
|
+
// Not kept elsewhere, so the step fails rather than let an older copy
|
|
105
|
+
// come back over it on the next step (Codex review).
|
|
106
|
+
throw new Error(`a test run's diverted file is over ${MAX_FILE / 1024 / 1024} MiB and cannot be kept for the next step`);
|
|
107
|
+
}
|
|
108
|
+
const bytes = fs.readFileSync(f.abs);
|
|
109
|
+
const sha = sha256Hex(bytes);
|
|
110
|
+
if (was && was.sha === sha && was.mtimeMs === st.mtimeMs) continue; // a newer time with the same bytes counts
|
|
111
|
+
const atStart = start?.get(f.rel);
|
|
112
|
+
// Unchanged by this attempt AND already kept: another step's newer copy
|
|
113
|
+
// stays; a file never kept (the store switched on mid-run) is kept now.
|
|
114
|
+
if (was && atStart && atStart.sha === sha && atStart.mtimeMs === st.mtimeMs) continue;
|
|
115
|
+
if (was?.sha !== sha) {
|
|
116
|
+
await deps.pins?.pinBlobs(tenant, [sha], holderOf(runId));
|
|
117
|
+
await deps.blobs.putIfAbsent(blobObjectKey(tenant, sha), bytes);
|
|
118
|
+
}
|
|
119
|
+
await port.stepPut!(tenant, workspace, runId, KIND, refOf(f.rel), { path: f.rel, sha, size: bytes.length, mtimeMs: st.mtimeMs });
|
|
120
|
+
knownOf(dir).set(f.rel, sha);
|
|
121
|
+
saved++;
|
|
122
|
+
}
|
|
123
|
+
return saved;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Before a step: what the rows name and this worker's folder lacks (or has
|
|
127
|
+
* at another time). Throws: a step must not run without what earlier steps wrote. */
|
|
128
|
+
export async function restoreTestWrites(tenant: string, workspace: string, runId: string, dir: string): Promise<{ restored: number; start: TestWritesStart }> {
|
|
129
|
+
const deps = revisionBackend();
|
|
130
|
+
const rp = rowsPort(tenant, workspace);
|
|
131
|
+
if (!deps || !rp) return { restored: 0, start: new Map() }; // nothing kept elsewhere: nothing to compare (a laptop hashes nothing)
|
|
132
|
+
const { port } = rp;
|
|
133
|
+
let n = 0;
|
|
134
|
+
for (const row of await port.stepList!(tenant, workspace, runId, KIND)) {
|
|
135
|
+
const f = row.data as Listed & { path: string };
|
|
136
|
+
if (typeof f?.path !== "string" || refOf(f.path) !== row.ref) continue;
|
|
137
|
+
const abs = path.resolve(dir, f.path);
|
|
138
|
+
if (!abs.startsWith(path.resolve(dir) + path.sep)) continue; // names stay inside the folder
|
|
139
|
+
const t = new Date(f.mtimeMs);
|
|
140
|
+
const known = knownOf(dir);
|
|
141
|
+
if (fs.existsSync(abs)) {
|
|
142
|
+
const local = sha256Hex(fs.readFileSync(abs));
|
|
143
|
+
if (local === f.sha) {
|
|
144
|
+
known.set(f.path, f.sha);
|
|
145
|
+
if (Math.round(fs.statSync(abs).mtimeMs) !== Math.round(f.mtimeMs)) fs.utimesSync(abs, t, t);
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
// Changed here since this process last brought or saved it: another
|
|
149
|
+
// step of the run wrote it and has not saved yet — kept (Codex review).
|
|
150
|
+
// No record at all (a restart: no step of this process is mid-write)
|
|
151
|
+
// means a stale copy, refreshed from the rows.
|
|
152
|
+
const was = known.get(f.path);
|
|
153
|
+
if (was !== undefined && local !== was) continue;
|
|
154
|
+
}
|
|
155
|
+
const bytes = await readAll(deps.blobs, blobObjectKey(tenant, f.sha));
|
|
156
|
+
if (sha256Hex(bytes) !== f.sha) throw new Error("a diverted file's object does not hash to its name — refused");
|
|
157
|
+
fs.mkdirSync(path.dirname(abs), { recursive: true });
|
|
158
|
+
fs.writeFileSync(abs, bytes);
|
|
159
|
+
fs.utimesSync(abs, t, t); // a verify that asks whether a file is fresh answers for the step that wrote it
|
|
160
|
+
known.set(f.path, f.sha);
|
|
161
|
+
n++;
|
|
162
|
+
}
|
|
163
|
+
return { restored: n, start: snapshot(dir) };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** A run deleted: its diverted files' pins and row go. */
|
|
167
|
+
registerRunRemovedHook((tenant, workspace, runId) => {
|
|
168
|
+
for (const dir of [...KNOWN.keys()]) if (dir.includes(`${path.sep}runs${path.sep}${runId}${path.sep}`)) KNOWN.delete(dir);
|
|
169
|
+
const deps = revisionBackend();
|
|
170
|
+
void (async () => {
|
|
171
|
+
await deps?.pins?.release(tenant, holderOf(runId));
|
|
172
|
+
await dropStepState(tenant, workspace, runId, KIND, null);
|
|
173
|
+
})().catch((err) => opsError("test_writes.release_failed", err, { tenant, workspace, runId }, "warn"));
|
|
174
|
+
}, "test-writes");
|
|
@@ -1642,7 +1642,7 @@ async function syncNow(tenant: string, workspace: string): Promise<"unchanged" |
|
|
|
1642
1642
|
}
|
|
1643
1643
|
if (busy()) return "skipped"; // a write landed meanwhile: next round
|
|
1644
1644
|
const bytes = await blobBytes(deps, tenant, e.sha);
|
|
1645
|
-
if (!bytes) throw new Error(`revisions: blob ${e.sha.slice(0, 12)}
|
|
1645
|
+
if (!bytes) throw new Error(`revisions: blob ${e.sha.slice(0, 12)} is missing`); // no file path: ops lines carry no customer content
|
|
1646
1646
|
const abs = path.join(dir, p);
|
|
1647
1647
|
// Never through a link: a folder on the way that is a symlink could lead
|
|
1648
1648
|
// outside the workspace (Codex review). Such a path is left as it is.
|
|
@@ -1742,10 +1742,20 @@ export async function syncAllFromHeads(): Promise<{ synced: number; removed: num
|
|
|
1742
1742
|
// ------------------------------------------------------------- reading
|
|
1743
1743
|
|
|
1744
1744
|
async function blobBytes(deps: Deps, tenant: string, sha: string): Promise<Buffer | null> {
|
|
1745
|
+
// An object is named by its content: bytes that do not hash to the name
|
|
1746
|
+
// (corruption, or a store someone wrote to) are refused — never written into
|
|
1747
|
+
// a pod's copy, staged into a run or served (FOL-126 security review).
|
|
1748
|
+
const checked = (b: Buffer, from: string): Buffer => {
|
|
1749
|
+
if (sha256Hex(b) !== sha) {
|
|
1750
|
+
opsError("revisions.blob_mismatch", new Error(`blob ${sha.slice(0, 12)} does not hash to its name`), { tenant, surface: from });
|
|
1751
|
+
throw new Error(`revisions: blob ${sha.slice(0, 12)}… does not hash to its name — refused`);
|
|
1752
|
+
}
|
|
1753
|
+
return b;
|
|
1754
|
+
};
|
|
1745
1755
|
const hit = await S.cache?.get(tenant, sha);
|
|
1746
|
-
if (hit) return hit;
|
|
1756
|
+
if (hit) return checked(hit, "cache");
|
|
1747
1757
|
try {
|
|
1748
|
-
const b = await readAll(deps.blobs, blobObjectKey(tenant, sha));
|
|
1758
|
+
const b = checked(await readAll(deps.blobs, blobObjectKey(tenant, sha)), "store");
|
|
1749
1759
|
void S.cache?.put(tenant, sha, b).catch(() => {});
|
|
1750
1760
|
return b;
|
|
1751
1761
|
} catch (err) {
|