@staix/agent-mem 0.29.0 → 0.30.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/.claude-plugin/plugin.json +1 -1
- package/README.md +9 -7
- package/package.json +3 -2
- package/src/cli.ts +69 -10
- package/src/commands-table.ts +4 -0
- package/src/mcp-memory.ts +36 -8
- package/src/memory/bridge.ts +26 -1
- package/src/memory/capacity.ts +5 -2
- package/src/memory/catalog.ts +10 -1
- package/src/memory/doctor.ts +17 -14
- package/src/memory/formats.ts +4 -3
- package/src/memory/intent-brief.ts +34 -6
- package/src/memory/metrics.ts +173 -14
- package/src/memory/shard-bridge.ts +18 -6
- package/src/memory/shard-sync-format.ts +18 -0
- package/src/memory/shard-sync.ts +52 -4
- package/src/memory/sync-placement-bound.ts +21 -4
- package/src/memory/sync-placement-cache.ts +16 -1
- package/src/memory/sync-placement-capture.ts +14 -2
- package/src/memory/sync-placement-checkpoint-format.ts +199 -0
- package/src/memory/sync-placement-checkpoint-person.ts +209 -0
- package/src/memory/sync-placement-checkpoint-prospective.ts +141 -0
- package/src/memory/sync-placement-checkpoint-storage.ts +218 -0
- package/src/memory/sync-placement-checkpoint.ts +234 -0
- package/src/memory/sync-placement-dependencies.ts +42 -9
- package/src/memory/sync-placement-effective-writers.ts +12 -6
- package/src/memory/sync-placement-git.ts +17 -7
- package/src/memory/sync-placement-inspection-evidence.ts +1 -1
- package/src/memory/sync-placement-inventory.ts +5 -0
- package/src/memory/sync-placement-journal-format.ts +4 -1
- package/src/memory/sync-placement-journal-storage.ts +129 -26
- package/src/memory/sync-placement-materialize.ts +33 -19
- package/src/memory/sync-placement-projection.ts +7 -1
- package/src/memory/sync-placement-publication-events.ts +42 -0
- package/src/memory/sync-placement-publication-plan.ts +18 -1
- package/src/memory/sync-placement-realm-admission.ts +20 -3
- package/src/memory/sync-placement-realm-discovery.ts +42 -0
- package/src/memory/sync-placement-remote-admission.ts +190 -0
- package/src/memory/sync-placement-remote-adoption-format.ts +54 -0
- package/src/memory/sync-placement-remote-materialization.ts +49 -0
- package/src/memory/sync-placement-remote-refusal.ts +21 -0
- package/src/memory/sync-placement-remote-stage.ts +275 -0
- package/src/memory/sync-placement-transport.ts +202 -51
- package/src/memory/sync-placement-writer-history.ts +75 -17
- package/src/memory/sync-placement-writer-renewal.ts +18 -10
- package/src/memory/sync-placement-writer-revision-format.ts +16 -13
- package/src/memory/sync-placement-yield.ts +14 -0
- package/src/memory/sync.ts +4 -1
- package/src/sync-placement-writer-context.ts +5 -5
- package/src/ui/plugin.ts +1 -1
|
@@ -3,6 +3,7 @@ import { createHash } from "node:crypto";
|
|
|
3
3
|
import { types } from "node:util";
|
|
4
4
|
import { PUBLIC_PRUNE_REPLAY_MAX_BYTES } from "./public-prune-input-chain.ts";
|
|
5
5
|
import { decodePlacementTransportDescriptor, decodeShardManifest, isShardManifestPath, SHARD_PACK_MAX_BYTES, type ShardSyncRealm } from "./shard-sync-format.ts";
|
|
6
|
+
import { drainSteps, drainStepsAsync, type CooperativeYield } from "./sync-placement-yield.ts";
|
|
6
7
|
|
|
7
8
|
export interface PlannedGitObject { type: "blob" | "tree" | "commit"; oid: string; bytes: Buffer; path: string | null }
|
|
8
9
|
export interface PlacementGitObjects { objects: PlannedGitObject[]; tree: string; commit: string }
|
|
@@ -27,10 +28,17 @@ function object(type: PlannedGitObject["type"], bytes: Buffer, path: string | nu
|
|
|
27
28
|
* Retained public bytes share the existing replay bound; new source's separate 8MiB allowance is the caller's proof. */
|
|
28
29
|
export function compilePlacementGitObjects(files: ReadonlyMap<string, Uint8Array>, parent: string | null, createdUnixSeconds: number,
|
|
29
30
|
previous?: { tree: string; commit: string }): PlacementGitObjects {
|
|
30
|
-
try { return
|
|
31
|
+
try { return drainSteps(compileSteps(files, parent, createdUnixSeconds, previous)); } catch { return fail(); }
|
|
31
32
|
}
|
|
32
|
-
|
|
33
|
-
|
|
33
|
+
/** #470: the same objects, awaiting the caller's event loop between entries and tree nodes; bytes and ids are identical. */
|
|
34
|
+
export async function compilePlacementGitObjectsAsync(files: ReadonlyMap<string, Uint8Array>, parent: string | null, createdUnixSeconds: number,
|
|
35
|
+
previous?: { tree: string; commit: string }, yieldPoint?: CooperativeYield): Promise<PlacementGitObjects> {
|
|
36
|
+
try { return await drainStepsAsync(compileSteps(files, parent, createdUnixSeconds, previous), yieldPoint); } catch { return fail(); }
|
|
37
|
+
}
|
|
38
|
+
/** Objects between step boundaries: at most 128 blob hashes per uninterrupted stretch. */
|
|
39
|
+
const STEP_OBJECTS = 128;
|
|
40
|
+
function* compileSteps(files: ReadonlyMap<string, Uint8Array>, parent: string | null, createdUnixSeconds: number,
|
|
41
|
+
previous?: { tree: string; commit: string }): Generator<void, PlacementGitObjects, void> {
|
|
34
42
|
if (!files || typeof files !== "object" || types.isProxy(files) || Object.getPrototypeOf(files) !== Map.prototype
|
|
35
43
|
|| !Number.isSafeInteger(createdUnixSeconds) || createdUnixSeconds < 0 || parent !== null && !oid(parent)) return fail();
|
|
36
44
|
const count = mapSize.call(files);
|
|
@@ -42,9 +50,10 @@ function compile(files: ReadonlyMap<string, Uint8Array>, parent: string | null,
|
|
|
42
50
|
|| !oid(fields.tree.value) || !oid(fields.commit.value)) return fail();
|
|
43
51
|
previous = { tree: fields.tree.value, commit: fields.commit.value };
|
|
44
52
|
}
|
|
45
|
-
const entries: { path: string; bytes: Buffer }[] = []; let total = 0;
|
|
53
|
+
const entries: { path: string; bytes: Buffer }[] = []; let total = 0, stepped = 0;
|
|
46
54
|
for (const [path, value] of Map.prototype.entries.call(files) as Iterable<[unknown, unknown]>) {
|
|
47
55
|
if (typeof path !== "string" || types.isProxy(value) || !(value instanceof Uint8Array)) return fail();
|
|
56
|
+
if (++stepped >= STEP_OBJECTS) { stepped = 0; yield; }
|
|
48
57
|
const pack = PACK.exec(path), validPack = pack?.[0] === path;
|
|
49
58
|
if (path !== "shard.json" && !validPack && !isShardManifestPath(path)) return fail();
|
|
50
59
|
const length = getLength.call(value) as number, maximum = validPack ? SHARD_PACK_MAX_BYTES : 64 * 1024;
|
|
@@ -70,10 +79,11 @@ function compile(files: ReadonlyMap<string, Uint8Array>, parent: string | null,
|
|
|
70
79
|
for (const name of parts.slice(0, -1)) { if (target.blobs.has(name)) return fail(); let next = target.directories.get(name); if (!next) target.directories.set(name, next = node()); target = next; }
|
|
71
80
|
const name = parts.at(-1)!; if (target.directories.has(name) || target.blobs.has(name)) return fail(); target.blobs.set(name, blob.oid);
|
|
72
81
|
}
|
|
73
|
-
const buildTree = (tree: TreeNode, path: string): string
|
|
82
|
+
const buildTree = function* (tree: TreeNode, path: string): Generator<void, string, void> {
|
|
74
83
|
const children: { name: string; oid: string; directory: boolean }[] = [...tree.blobs].map(([name, id]) => ({ name, oid: id, directory: false }));
|
|
84
|
+
if (++stepped >= STEP_OBJECTS) { stepped = 0; yield; }
|
|
75
85
|
for (const [name, directory] of [...tree.directories].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0))
|
|
76
|
-
children.push({ name, oid: buildTree(directory, path ? `${path}/${name}` : name), directory: true });
|
|
86
|
+
children.push({ name, oid: yield* buildTree(directory, path ? `${path}/${name}` : name), directory: true });
|
|
77
87
|
children.sort((a,b) => Buffer.compare(Buffer.from(a.name + (a.directory ? "/" : "")), Buffer.from(b.name + (b.directory ? "/" : ""))));
|
|
78
88
|
let length = 0; const chunks: Buffer[] = [];
|
|
79
89
|
for (const child of children) {
|
|
@@ -82,7 +92,7 @@ function compile(files: ReadonlyMap<string, Uint8Array>, parent: string | null,
|
|
|
82
92
|
}
|
|
83
93
|
const result = object("tree", Buffer.concat(chunks, length), path); trees.push(result); return result.oid;
|
|
84
94
|
};
|
|
85
|
-
const tree = buildTree(root, "");
|
|
95
|
+
const tree = yield* buildTree(root, "");
|
|
86
96
|
trees.sort((a,b) => (b.path ? b.path.split("/").length : 0) - (a.path ? a.path.split("/").length : 0)
|
|
87
97
|
|| (a.path! < b.path! ? -1 : a.path! > b.path! ? 1 : 0));
|
|
88
98
|
objects.push(...trees);
|
|
@@ -29,7 +29,7 @@ export function captureInspectionJournal(home: string, epochHash: string): Inspe
|
|
|
29
29
|
const captured = capturePlacementPublicationMetadata(home, epochHash, io => {
|
|
30
30
|
const journal = io.journal();
|
|
31
31
|
if (journal.pending) throw new SyncPlacementJournalError("pending");
|
|
32
|
-
const attempts = new Set<string>();
|
|
32
|
+
const attempts = new Set<string>(io.archivedPublications());
|
|
33
33
|
for (const name of io.names()) {
|
|
34
34
|
const match = /^publication-([a-f0-9]{64})-/.exec(name);
|
|
35
35
|
if (match) attempts.add(match[1]!);
|
|
@@ -15,6 +15,7 @@ import { join } from "node:path";
|
|
|
15
15
|
import { readActivePlacementBinding } from "./sync-placement-active.ts";
|
|
16
16
|
import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
|
|
17
17
|
import { readPlacementJournal } from "./sync-placement-journal-storage.ts";
|
|
18
|
+
import { PLACEMENT_CHECKPOINT_PENDING_MESSAGE, placementCheckpointPending } from "./sync-placement-checkpoint-storage.ts";
|
|
18
19
|
import { readPlacementPublication } from "./sync-placement-publication-storage.ts";
|
|
19
20
|
import { readEffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
|
|
20
21
|
import { readShardDescriptor, shardDir, userShardDir } from "./shard.ts";
|
|
@@ -86,6 +87,10 @@ function retainedRealms(home: string): string[] | undefined {
|
|
|
86
87
|
}
|
|
87
88
|
|
|
88
89
|
export async function syncPlacementInventory(home: string, opts: SyncOptions, ports: PlacementInventoryPorts): Promise<SyncResult & { placementRealms: PlacementRealmResult[] }> {
|
|
90
|
+
// #288 step 3: a started checkpoint pauses every placement effect before any journal read, with its own cause and next step.
|
|
91
|
+
const markers = readPlacementRuntimeMarkers(home), binding = readActivePlacementBinding(home, markers.profile, markers.shards);
|
|
92
|
+
if (binding && placementCheckpointPending(home, binding.profile.placementHead))
|
|
93
|
+
return { ok: false, pushed: false, entries: 0, error: PLACEMENT_CHECKPOINT_PENDING_MESSAGE, failure: { cause: "checkpoint-pending" }, placementRealms: [] };
|
|
89
94
|
const { local, missing, inactive } = placementInventory(home);
|
|
90
95
|
const retained = retainedRealms(home);
|
|
91
96
|
let order = local;
|
|
@@ -8,13 +8,16 @@ export const PLACEMENT_RECORD_SCHEMA = "agent-mem.sync-placement-record/v1";
|
|
|
8
8
|
export const PLACEMENT_ACTIVE_FENCE_SCHEMA = "agent-mem.sync-placement-fence/v1";
|
|
9
9
|
export const PLACEMENT_JOURNAL_MAX_RECORDS = 20_000, PLACEMENT_JOURNAL_MAX_OBJECTS = 256;
|
|
10
10
|
export const PLACEMENT_JOURNAL_CHUNK_MAX_BYTES = 64 * 1024, PLACEMENT_JOURNAL_ROOT_MAX_BYTES = 256 * 1024;
|
|
11
|
-
export type SyncPlacementJournalErrorCode = "invalid" | "corrupt" | "bound" | "conflict" | "pending" | "changed" | "authorization" | "policy" | "local" | "busy";
|
|
11
|
+
export type SyncPlacementJournalErrorCode = "invalid" | "corrupt" | "bound" | "conflict" | "pending" | "checkpoint-pending" | "changed" | "authorization" | "policy" | "local" | "busy";
|
|
12
|
+
export const PLACEMENT_CHECKPOINT_COMMAND = "amem migrate --sync-placement --checkpoint";
|
|
13
|
+
export const PLACEMENT_CHECKPOINT_PENDING_MESSAGE = `A placement checkpoint is pending; placement effects are paused until it finishes. Run ${PLACEMENT_CHECKPOINT_COMMAND} --resume to complete its recorded bytes, or ${PLACEMENT_CHECKPOINT_COMMAND} --abandon if its commit line has not started.`;
|
|
12
14
|
const messages: Record<SyncPlacementJournalErrorCode, string> = {
|
|
13
15
|
invalid: "Sync placement journal data is invalid or unsupported; inspect the retained state and use a compatible runtime.",
|
|
14
16
|
corrupt: "Sync placement journal evidence is incomplete or inconsistent; restore the exact retained evidence before continuing.",
|
|
15
17
|
bound: "Sync placement journal exceeds its supported bounds; a person-reviewed bounded epoch transition is required.",
|
|
16
18
|
conflict: "Sync placement journal identity or request conflicts with retained evidence; inspect the exact request before retrying.",
|
|
17
19
|
pending: "Sync placement journal has an unfinished transaction; resume its exact recorded request before continuing.",
|
|
20
|
+
"checkpoint-pending": PLACEMENT_CHECKPOINT_PENDING_MESSAGE,
|
|
18
21
|
changed: "Sync placement journal or source bindings changed; capture and review a fresh request before continuing.",
|
|
19
22
|
authorization: "Sync placement change requires explicit person authorization of the exact reviewed request.",
|
|
20
23
|
policy: "Current mandatory policy refuses this sync placement change; inspect its safe policy classification.",
|
|
@@ -18,6 +18,8 @@ import { WRITER_RENEWAL_INTENT_FILE, WRITER_RENEWAL_INTENT_MAX_BYTES, WRITER_COM
|
|
|
18
18
|
import { isWriterRenewalIntentTempName } from "./sync-placement-writer-history.ts";
|
|
19
19
|
import { PLACEMENT_BATCH_INTENT_MAX_BYTES, planPlacementBatchIntent, validatePlacementBatchIntent, type PlacementBatchIntent } from "./sync-placement-batch-intent.ts";
|
|
20
20
|
import { formatFloorAtLeast } from "./formats.ts";
|
|
21
|
+
import { resolvePlacementWindow, placementWindowToken, releasePlacementCheckpointCaches, type ResolvedPlacementWindow } from "./sync-placement-checkpoint-storage.ts";
|
|
22
|
+
import { isCheckpointSealedName, PLACEMENT_CHECKPOINT_MANIFEST_MAX_BYTES, type CheckpointMember } from "./sync-placement-checkpoint-format.ts";
|
|
21
23
|
|
|
22
24
|
export type PlacementStoragePhase = "epoch-written" | "epoch-fsync" | "activation-written" | "activation-fsync" | "fence-written" | "fence-fsync"
|
|
23
25
|
| "intent-written" | "intent-fsync" | "chunk-written" | "chunk-fsync" | "intent-cleared"
|
|
@@ -27,7 +29,7 @@ export interface PlacementStorageOptions { mutation: MutationHandle; assertCurre
|
|
|
27
29
|
export interface PlacementJournalRead {
|
|
28
30
|
epoch: PlacementEpoch; activation: SyncPlacementActivationPlan; records: PlacementRecord[]; headHash: string; sequence: number; objects: number; pending: boolean; pendingRecordSequence?: number; pendingRecord?: PlacementRecord; pendingBatch?: { attemptHash: string; count: number }; publicationReservation?: { attemptHash: string; reservedRecords: number; consumedRecords: number };
|
|
29
31
|
}
|
|
30
|
-
interface Paths { home: string; root: string; epochs: string; dir: string; hash: string }
|
|
32
|
+
interface Paths { home: string; root: string; epochs: string; dir: string; hash: string; epochDir: string; window: ResolvedPlacementWindow }
|
|
31
33
|
interface Chunk { name: string; size: number; hash: string }
|
|
32
34
|
interface Intent { schema: "agent-mem.sync-placement-append-intent/v1"; epochHash: string; record: PlacementRecord; chunk: string; prefixBytes: number; prefixHash: string; lineHash: string }
|
|
33
35
|
interface Snapshot extends PlacementJournalRead { chunks: Chunk[]; projection: PlacementProjection; intent?: Intent; batchIntent?: PlacementBatchIntent; intentPending: boolean; fencePending: boolean }
|
|
@@ -49,8 +51,15 @@ function state(file: string, directory = false): BigIntStats | undefined {
|
|
|
49
51
|
function paths(home: string, epochHash: string): Paths {
|
|
50
52
|
if (!hex(epochHash)) return fail("invalid");
|
|
51
53
|
const canonical = realPath(home); owned(lstatSync(home, { bigint: true }), true);
|
|
52
|
-
|
|
54
|
+
// #288: the one window resolver selects the live window; epoch.json and activation.json stay in frozen window 0.
|
|
55
|
+
const window = resolvePlacementWindow(canonical, epochHash), epochDir = join(canonical, "sync-placement", "epochs", epochHash);
|
|
56
|
+
return { home: canonical, root: join(canonical, "sync-placement"), epochs: join(canonical, "sync-placement", "epochs"), dir: window.dir, hash: epochHash, epochDir, window };
|
|
53
57
|
}
|
|
58
|
+
/** Archived journal chunks in replay order: every frozen window's `records-*` members, by their global chunk index. */
|
|
59
|
+
function archivedChunks(p: Paths): { dir: string; name: string; member: CheckpointMember }[] {
|
|
60
|
+
return p.window.archived.flatMap(window => window.members.filter(member => /^records-\d{5}\.jsonl$/.test(member.name)).map(member => ({ dir: window.dir, name: member.name, member })));
|
|
61
|
+
}
|
|
62
|
+
const checkpointMember = (name: string) => isCheckpointSealedName(name);
|
|
54
63
|
function names(dir: string, maximum: number): string[] {
|
|
55
64
|
const reader = opendirSync(dir), result: string[] = [];
|
|
56
65
|
try { for (;;) { const entry = reader.readSync(); if (!entry) break; if (result.length >= maximum) fail("bound"); result.push(entry.name); } }
|
|
@@ -70,25 +79,28 @@ function renewalIntentObjects(home:string):{count:number;token:unknown[]} {
|
|
|
70
79
|
}
|
|
71
80
|
function inventory(p: Paths): { files: Map<string, BigIntStats>; token: string; renewalObjects:number } {
|
|
72
81
|
const parents: unknown[] = [];
|
|
73
|
-
for (const dir of [p.home, p.root, p.epochs, p.dir]) { const stat = state(dir, true); parents.push([dir, stat ? [String(stat.dev), String(stat.ino)] : null]); }
|
|
82
|
+
for (const dir of [p.home, p.root, p.epochs, p.epochDir, ...(p.window.window ? [p.dir] : [])]) { const stat = state(dir, true); parents.push([dir, stat ? [String(stat.dev), String(stat.ino)] : null]); }
|
|
74
83
|
if (state(p.root, true)) for (const name of names(p.root, 2)) {
|
|
75
84
|
if (name === "epochs") state(p.epochs, true); else if (name === "active.json") { const stat = state(join(p.root, name))!; if (stat.size > BigInt(PLACEMENT_JOURNAL_ROOT_MAX_BYTES)) fail("bound"); }
|
|
76
85
|
else fail();
|
|
77
86
|
}
|
|
78
|
-
const files = new Map<string, BigIntStats>();
|
|
87
|
+
const files = new Map<string, BigIntStats>(), live = p.window.window > 0;
|
|
79
88
|
if (state(p.dir, true)) for (const name of names(p.dir, PLACEMENT_JOURNAL_MAX_OBJECTS - 1)) {
|
|
80
89
|
const chunk = /^records-\d{5}\.jsonl$/.test(name);
|
|
81
|
-
const writerLimit=writerHistoryFileLimit(name);
|
|
82
|
-
|
|
90
|
+
const writerLimit=writerHistoryFileLimit(name), sealed = live && checkpointMember(name);
|
|
91
|
+
// Window 0 holds the epoch's own metadata; a later live window holds the checkpoint's sealed files instead.
|
|
92
|
+
if (!chunk && !publicationName(name) && writerLimit===undefined && !sealed && ![...(live ? [] : ["epoch.json", "activation.json"]), "append-intent.json"].includes(name)) fail();
|
|
83
93
|
const stat = state(join(p.dir, name))!;
|
|
84
|
-
if (stat.size > BigInt(writerLimit??(name === "append-intent.json" ? PLACEMENT_BATCH_INTENT_MAX_BYTES : chunk || /-chunk-\d{5}\.json$/.test(name) ? PLACEMENT_JOURNAL_CHUNK_MAX_BYTES : PLACEMENT_JOURNAL_ROOT_MAX_BYTES))) fail("bound");
|
|
94
|
+
if (stat.size > BigInt(writerLimit??(sealed ? PLACEMENT_CHECKPOINT_MANIFEST_MAX_BYTES : name === "append-intent.json" ? PLACEMENT_BATCH_INTENT_MAX_BYTES : chunk || /-chunk-\d{5}\.json$/.test(name) ? PLACEMENT_JOURNAL_CHUNK_MAX_BYTES : PLACEMENT_JOURNAL_ROOT_MAX_BYTES))) fail("bound");
|
|
85
95
|
files.set(name, stat);
|
|
86
96
|
}
|
|
87
|
-
//
|
|
97
|
+
// The frozen epoch metadata still binds every read once the live window moved on.
|
|
98
|
+
const metadata = live ? ["epoch.json", "activation.json"].map(name => { const stat = state(join(p.epochDir, name)); return [name, stat ? stamp(stat) : null]; }) : [];
|
|
99
|
+
// One global active.json slot is always reserved, whether that fence exists yet or not. Only the live window is charged (#288).
|
|
88
100
|
const renewal=renewalIntentObjects(p.home);
|
|
89
101
|
if (files.size + 1 + renewal.count > PLACEMENT_JOURNAL_MAX_OBJECTS) fail("bound");
|
|
90
102
|
const fence = state(join(p.root, "active.json"));
|
|
91
|
-
return { files, renewalObjects:renewal.count, token: canonicalJSON({ parents, renewal:renewal.token, files: [...files].map(([name, stat]) => [name, String(stat.dev), String(stat.ino), String(stat.size), String(stat.mtimeNs), String(stat.ctimeNs)]),
|
|
103
|
+
return { files, renewalObjects:renewal.count, token: canonicalJSON({ parents, renewal:renewal.token, window: placementWindowToken(p.home, p.hash), metadata, files: [...files].map(([name, stat]) => [name, String(stat.dev), String(stat.ino), String(stat.size), String(stat.mtimeNs), String(stat.ctimeNs)]),
|
|
92
104
|
fence: fence ? [String(fence.dev), String(fence.ino), String(fence.size), String(fence.mtimeNs), String(fence.ctimeNs)] : null }) };
|
|
93
105
|
}
|
|
94
106
|
function readOwned(file: string, maximum: number): Buffer | undefined {
|
|
@@ -138,17 +150,52 @@ let journalSnapshot: { token: string; value: Snapshot } | undefined;
|
|
|
138
150
|
/** #462: the validated batch intent by its exact bytes; a pure function of content, so a hit cannot change a result. */
|
|
139
151
|
let batchIntentMemo: { key: string; value: PlacementBatchIntent } | undefined;
|
|
140
152
|
/** Drop every decoded journal/publication memo; a sync calls this when it ends so a resident host never keeps a journal's records. */
|
|
141
|
-
export function releasePlacementStorageCaches(): void { journalPrefix = undefined; journalTail = undefined; journalSnapshot = undefined; publicationBundle = undefined; reservationRoot = undefined; batchIntentMemo = undefined; reservedNamesMemo = undefined; }
|
|
153
|
+
export function releasePlacementStorageCaches(): void { journalPrefix = undefined; journalTail = undefined; journalSnapshot = undefined; publicationBundle = undefined; reservationRoot = undefined; batchIntentMemo = undefined; reservedNamesMemo = undefined; archiveReplay = undefined; releasePlacementCheckpointCaches(); }
|
|
142
154
|
// Records are frozen and shared (the bulk); every small mutable field is a fresh copy, so a caller's mutation never reaches the memo.
|
|
143
155
|
const detachSnapshot = (value: Snapshot): Snapshot => ({ ...value, records: value.records.map(freeze), chunks: value.chunks.map(chunk => ({ ...chunk })), projection: value.projection.clone(),
|
|
144
156
|
epoch: structuredClone(value.epoch), activation: structuredClone(value.activation),
|
|
145
157
|
...(value.intent ? { intent: structuredClone(value.intent) } : {}), ...(value.batchIntent ? { batchIntent: freeze(value.batchIntent) } : {}), ...(value.pendingBatch ? { pendingBatch: { ...value.pendingBatch } } : {}), ...(value.pendingRecord ? { pendingRecord: structuredClone(value.pendingRecord) } : {}) });
|
|
158
|
+
/**
|
|
159
|
+
* #288: the replayed frozen windows for one committed checkpoint chain, keyed by the resolver's token and the last manifest.
|
|
160
|
+
* The replay is verified once against the sealed projection snapshot; later snapshots replay only the live tail.
|
|
161
|
+
*/
|
|
162
|
+
let archiveReplay: { key: string; records: PlacementRecord[]; chunks: Chunk[]; projection: PlacementProjection } | undefined;
|
|
163
|
+
/** Archived chunks are closed: their reported size is the chunk ceiling, so no append or reservation ever reuses one. */
|
|
164
|
+
function replayArchive(p: Paths, epoch: PlacementEpoch): { records: PlacementRecord[]; chunks: Chunk[]; projection: PlacementProjection } | undefined {
|
|
165
|
+
const manifest = p.window.manifests.at(-1); if (!manifest) return undefined;
|
|
166
|
+
const key = canonicalJSON([p.hash, manifest.seal, p.window.token]);
|
|
167
|
+
if (archiveReplay?.key === key) return { records: [...archiveReplay.records], chunks: archiveReplay.chunks.map(chunk => ({ ...chunk })), projection: archiveReplay.projection.clone() };
|
|
168
|
+
const projection = new PlacementProjection(epoch), records: PlacementRecord[] = [], chunks: Chunk[] = [];
|
|
169
|
+
for (const [index, chunk] of archivedChunks(p).entries()) {
|
|
170
|
+
if (chunk.name !== `records-${String(index).padStart(5, "0")}.jsonl`) fail();
|
|
171
|
+
const bytes = readOwned(join(chunk.dir, chunk.name), PLACEMENT_JOURNAL_CHUNK_MAX_BYTES);
|
|
172
|
+
if (!bytes?.length || bytes.length !== chunk.member.size || digest(bytes) !== chunk.member.sha256) fail();
|
|
173
|
+
let start = 0;
|
|
174
|
+
while (start < bytes.length) {
|
|
175
|
+
const end = bytes.indexOf(10, start); if (end < 0 || end === start) fail();
|
|
176
|
+
if (records.length >= PLACEMENT_JOURNAL_MAX_RECORDS) fail("bound");
|
|
177
|
+
const row = decode(bytes.subarray(start, end + 1), validatePlacementRecord); projection.apply(row); records.push(freeze(row)); start = end + 1;
|
|
178
|
+
}
|
|
179
|
+
chunks.push({ name: chunk.name, size: PLACEMENT_JOURNAL_CHUNK_MAX_BYTES, hash: chunk.member.sha256 });
|
|
180
|
+
}
|
|
181
|
+
const sealed = p.window.projection;
|
|
182
|
+
if (chunks.length !== manifest.journal.chunks || projection.sequence !== manifest.journal.sequence || projection.headHash !== manifest.journal.headHash
|
|
183
|
+
|| !sealed || sealed.projectionHash !== projection.digest()) fail();
|
|
184
|
+
archiveReplay = { key, records: [...records], chunks: chunks.map(chunk => ({ ...chunk })), projection: projection.clone() };
|
|
185
|
+
return { records, chunks, projection };
|
|
186
|
+
}
|
|
187
|
+
function epochMetadataStamp(p: Paths): string {
|
|
188
|
+
const stat = state(join(p.epochDir, "epoch.json")); if (!stat) fail("changed"); return stamp(stat);
|
|
189
|
+
}
|
|
146
190
|
function snapshot(p: Paths): Snapshot {
|
|
191
|
+
// #288: a started checkpoint owns the window until resume or abandon; no journal reader treats it as settled.
|
|
192
|
+
if (p.window.pending) fail("checkpoint-pending");
|
|
147
193
|
const before = inventory(p);
|
|
148
194
|
if (journalSnapshot?.token === canonicalJSON([p.dir, before.token])) return detachSnapshot(journalSnapshot.value);
|
|
149
|
-
const epoch = decode(readOwned(join(p.
|
|
195
|
+
const epoch = decode(readOwned(join(p.epochDir, "epoch.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementEpoch);
|
|
150
196
|
if (placementEpochHash(epoch) !== p.hash) return fail("conflict");
|
|
151
|
-
const plan = decode(readOwned(join(p.
|
|
197
|
+
const plan = decode(readOwned(join(p.epochDir, "activation.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), value => activation(epoch, p.hash, value));
|
|
198
|
+
if (p.window.manifests.some(manifest => manifest.activationHash !== plan.seal)) fail("conflict");
|
|
152
199
|
const pendingBytes = readOwned(join(p.dir, "append-intent.json"), PLACEMENT_BATCH_INTENT_MAX_BYTES);
|
|
153
200
|
const intentPending = pendingBytes !== undefined && (!pendingBytes.length || pendingBytes.at(-1) !== 10);
|
|
154
201
|
let pending: Intent | undefined, batch: PlacementBatchIntent | undefined;
|
|
@@ -162,6 +209,8 @@ function snapshot(p: Paths): Snapshot {
|
|
|
162
209
|
else { if (pendingBytes.length > PLACEMENT_JOURNAL_ROOT_MAX_BYTES) fail("bound"); pending = decode(pendingBytes, value => intent(value, p.hash)); }
|
|
163
210
|
}
|
|
164
211
|
let projection = new PlacementProjection(epoch); const records: PlacementRecord[] = [], chunks: Chunk[] = [];
|
|
212
|
+
const archive = replayArchive(p, epoch), base = archive?.chunks.length ?? 0;
|
|
213
|
+
if (archive) { projection = archive.projection; records.push(...archive.records); chunks.push(...archive.chunks); }
|
|
165
214
|
const apply = (bytes: Buffer) => {
|
|
166
215
|
let start = 0;
|
|
167
216
|
while (start < bytes.length) {
|
|
@@ -171,17 +220,18 @@ function snapshot(p: Paths): Snapshot {
|
|
|
171
220
|
}
|
|
172
221
|
};
|
|
173
222
|
const chunkNames = [...before.files.keys()].filter(name => /^records-\d{5}\.jsonl$/.test(name));
|
|
174
|
-
const prefixKey = (count: number) => canonicalJSON([p.dir,
|
|
223
|
+
const prefixKey = (count: number) => canonicalJSON([p.dir, epochMetadataStamp(p), archive ? p.window.token : null, chunkNames.slice(0, count).map(name => [name, stamp(before.files.get(name)!)])]);
|
|
175
224
|
// #462: a batch only touches its own chunks, so a prefix that ends before the batch's first chunk is still exact.
|
|
176
|
-
const batchStart = batch ? Number(batch.chunks[0]!.name.slice(8, 13)) : Infinity;
|
|
225
|
+
const batchStart = batch ? Number(batch.chunks[0]!.name.slice(8, 13)) - base : Infinity;
|
|
177
226
|
const cached = journalPrefix && journalPrefix.count < chunkNames.length && journalPrefix.count <= batchStart && journalPrefix.key === prefixKey(journalPrefix.count) ? journalPrefix : undefined;
|
|
178
227
|
let batchPartial = false;
|
|
179
228
|
let prefix: typeof journalPrefix, tail: typeof journalTail;
|
|
180
|
-
if (cached) { projection = cached.projection.clone(); records.push(...cached.records); chunks.push(...cached.chunks); }
|
|
229
|
+
if (cached) { projection = cached.projection.clone(); records.length = 0; records.push(...cached.records); chunks.length = 0; chunks.push(...cached.chunks); }
|
|
181
230
|
for (const [index, name] of chunkNames.entries()) {
|
|
182
231
|
if (index < (cached?.count ?? 0)) continue;
|
|
183
232
|
if (!batch && index > 0 && index === chunkNames.length - 1) prefix = { key: prefixKey(index), count: index, records: records.map(freeze), chunks: [...chunks], projection: projection.clone() };
|
|
184
|
-
|
|
233
|
+
// Chunk names stay global across windows: the live window continues after the archived chunks (#288).
|
|
234
|
+
if (name !== `records-${String(base + index).padStart(5, "0")}.jsonl`) fail();
|
|
185
235
|
const bytes = readOwned(join(p.dir, name), PLACEMENT_JOURNAL_CHUNK_MAX_BYTES)!;
|
|
186
236
|
const batchChunk = batch?.chunks.find(chunk => chunk.name === name);
|
|
187
237
|
if (batchChunk) {
|
|
@@ -216,7 +266,7 @@ function snapshot(p: Paths): Snapshot {
|
|
|
216
266
|
}
|
|
217
267
|
if (pending) {
|
|
218
268
|
const found = chunkNames.includes(pending.chunk);
|
|
219
|
-
if (!found && (pending.chunk !== `records-${String(chunkNames.length).padStart(5, "0")}.jsonl` || pending.prefixBytes !== 0 || pending.prefixHash !== digest(Buffer.alloc(0)))) fail();
|
|
269
|
+
if (!found && (pending.chunk !== `records-${String(base + chunkNames.length).padStart(5, "0")}.jsonl` || pending.prefixBytes !== 0 || pending.prefixHash !== digest(Buffer.alloc(0)))) fail();
|
|
220
270
|
if (!found && (projection.headHash !== pending.record.previousHash || projection.sequence + 1 !== pending.record.sequence)) fail();
|
|
221
271
|
if (pending.record.sequence > PLACEMENT_JOURNAL_MAX_RECORDS) fail("bound");
|
|
222
272
|
}
|
|
@@ -268,7 +318,8 @@ export function readPlacementJournal(home: string, epochHash: string): Placement
|
|
|
268
318
|
export function placementWriterJournalToken(home:string,epochHash:string):string {
|
|
269
319
|
return protectedIO(()=>{
|
|
270
320
|
const p=paths(home,epochHash),dir=state(p.dir,true);if(!dir)fail("changed");
|
|
271
|
-
|
|
321
|
+
// #288: a checkpoint commit moves the live window, so the window's own identity is part of the anchor token.
|
|
322
|
+
const rows:unknown[]=[["window",p.window.window,placementWindowToken(p.home,p.hash)],["directory",String(dir.dev),String(dir.ino),String(dir.mode),String(dir.uid)]];
|
|
272
323
|
for(const name of names(p.dir,PLACEMENT_JOURNAL_MAX_OBJECTS-1))if(name.startsWith("records-")||name==="append-intent.json"){
|
|
273
324
|
const s=state(join(p.dir,name));if(!s)fail("changed");
|
|
274
325
|
rows.push([name,String(s.dev),String(s.ino),String(s.mode),String(s.uid),String(s.nlink),String(s.size),String(s.mtimeNs),String(s.ctimeNs)]);
|
|
@@ -286,6 +337,9 @@ function current(p: Paths, opts: PlacementStorageOptions, required: readonly str
|
|
|
286
337
|
try { assertMutationHandle(opts.mutation, p.home); } catch { return fail("busy"); }
|
|
287
338
|
try { opts.assertCurrent(); } catch (error) { if (knownError(error)) throw error; return fail("changed"); }
|
|
288
339
|
try { assertMutationHandle(opts.mutation, p.home); } catch { return fail("busy"); }
|
|
340
|
+
// #288: a started checkpoint refuses every placement effect until it is resumed or abandoned; a committed one moved the window.
|
|
341
|
+
if (p.window.pending) fail("checkpoint-pending");
|
|
342
|
+
if (placementWindowToken(p.home, p.hash) !== p.window.token) fail("changed");
|
|
289
343
|
const found = inventory(p), names = new Set([...found.files.keys(), ...required, ...reservedPublicationJournalNames(p)]);
|
|
290
344
|
if(found.renewalObjects)fail("pending");
|
|
291
345
|
if (names.size + 1 + found.renewalObjects > PLACEMENT_JOURNAL_MAX_OBJECTS) fail("bound");
|
|
@@ -350,6 +404,7 @@ export function preparePlacementEpoch(home: string, value: PlacementEpoch, activ
|
|
|
350
404
|
const epoch = validatePlacementEpoch(value), epochHash = placementEpochHash(epoch);
|
|
351
405
|
writer(home, epochHash, opts, p => {
|
|
352
406
|
const plan = activation(epoch, epochHash, activationPlan), required = ["epoch.json", "activation.json"];
|
|
407
|
+
if (p.window.window) fail("conflict"); // A checkpointed epoch was prepared long ago; its metadata is frozen.
|
|
353
408
|
current(p, opts, required); directories(p, opts, required);
|
|
354
409
|
complete(p, opts, join(p.dir, "epoch.json"), line(epoch), PLACEMENT_JOURNAL_ROOT_MAX_BYTES, required, "epoch-written", "epoch-fsync");
|
|
355
410
|
complete(p, opts, join(p.dir, "activation.json"), line(plan), PLACEMENT_JOURNAL_ROOT_MAX_BYTES, required, "activation-written", "activation-fsync");
|
|
@@ -469,23 +524,30 @@ export interface PlacementPublicationStored {
|
|
|
469
524
|
/** Validated plan bundle keyed by the stat stamps of epoch.json, the root and every plan chunk (#420); same ceiling as journalPrefix. */
|
|
470
525
|
let publicationBundle: { key: string; bundle: PlacementPublicationBundle } | undefined;
|
|
471
526
|
function publicationRead(p: Paths, attemptHash: string): PlacementPublicationStored {
|
|
472
|
-
|
|
473
|
-
|
|
527
|
+
// #288: a completed publication frozen by a checkpoint resolves through the sealed catalog, never the live window.
|
|
528
|
+
// Its members were content-verified by the resolver, so their sealed hashes stand in for the live stat stamps.
|
|
529
|
+
const archived = p.window.catalog.get(attemptHash);
|
|
530
|
+
const dir = archived?.dir ?? p.dir, stem = `publication-${attemptHash}-`;
|
|
531
|
+
const files: Map<string, string> = archived ? new Map(archived.members.map(member => [member.name, member.sha256]))
|
|
532
|
+
: new Map([...inventory(p).files].map(([name, stat]) => [name, stamp(stat)]));
|
|
533
|
+
const keyOf = (found: Map<string, string>) => canonicalJSON([dir, attemptHash, epochMetadataStamp(p), [...found].filter(([name]) => name === stem + "root.json" || name.startsWith(stem + "chunk-"))]);
|
|
474
534
|
const key = keyOf(files);
|
|
475
535
|
let bundle = publicationBundle?.key === key ? publicationBundle.bundle : undefined;
|
|
476
536
|
if (!bundle) {
|
|
477
|
-
const root = decode(readOwned(join(
|
|
478
|
-
const epoch = decode(readOwned(join(p.
|
|
537
|
+
const root = decode(readOwned(join(dir, stem + "root.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementPublicationRoot);
|
|
538
|
+
const epoch = decode(readOwned(join(p.epochDir, "epoch.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementEpoch);
|
|
479
539
|
if (root.seal !== attemptHash || root.epochHash !== p.hash || root.generation !== epoch.generation || root.homeHash !== epoch.homeHash) fail("corrupt");
|
|
480
|
-
const chunks = root.chunks.map(c => decode(readOwned(join(
|
|
540
|
+
const chunks = root.chunks.map(c => decode(readOwned(join(dir, `${stem}chunk-${String(c.index).padStart(5, "0")}.json`), PLACEMENT_JOURNAL_CHUNK_MAX_BYTES), value => value));
|
|
481
541
|
bundle = freeze(validatePlacementPublicationBundle({ root, chunks }));
|
|
482
|
-
|
|
542
|
+
const after = archived ? files : new Map([...inventory(p).files].map(([name, stat]) => [name, stamp(stat)]));
|
|
543
|
+
if (keyOf(after) === key) publicationBundle = { key, bundle }; // Never cache bytes read across a concurrent change.
|
|
483
544
|
}
|
|
484
545
|
const root = bundle.root, allowed = new Set(publicationFileNames(root));
|
|
485
546
|
for (const name of files.keys()) if (name.startsWith(stem) && !allowed.has(name)) fail("corrupt");
|
|
547
|
+
if (archived && [...allowed].some(name => !files.has(name))) fail("corrupt");
|
|
486
548
|
const facts: PlacementPublicationFact[] = []; let phase: PlacementPublicationStored["phase"] = "prepared", pending = false, absent = false; let pendingPhase: PlacementPublicationFact["phase"] | undefined;
|
|
487
549
|
for (const [index, suffix] of ["artifact", "intent", "receipt"].entries()) {
|
|
488
|
-
const bytes = readOwned(join(
|
|
550
|
+
const bytes = readOwned(join(dir, stem + suffix + ".json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES);
|
|
489
551
|
if (bytes === undefined) fail("corrupt"); // Every future phase slot was reserved before root acknowledgement.
|
|
490
552
|
if (!bytes.length) { absent = true; continue; }
|
|
491
553
|
if (absent && (suffix !== "receipt" || pendingPhase)) fail("corrupt");
|
|
@@ -544,6 +606,44 @@ function reservedPublicationJournalNamesUncached(p: Paths): string[] {
|
|
|
544
606
|
for (const root of complete) names.push(...placementPublicationReservedJournalNames(root, read, sizes));
|
|
545
607
|
return names;
|
|
546
608
|
}
|
|
609
|
+
/** #288 step 1: which holders fill the journal-objects bound. Counts only, never a name, path or row. */
|
|
610
|
+
export interface PlacementJournalObjectComposition {
|
|
611
|
+
epochFixed:number; writerHistory:number; journalChunks:number;
|
|
612
|
+
completedPublications:{ count:number; objects:number };
|
|
613
|
+
newPlan:{ chunks:number; slots:number; reservedJournalChunks:number } | null;
|
|
614
|
+
}
|
|
615
|
+
/**
|
|
616
|
+
* Splits the objects `assertPlanCapacity` counts, over exactly the inputs it counts: the epoch directory's names, one
|
|
617
|
+
* planned publication and the journal names that plan reserves. Every counted name lands in one class, so the parts
|
|
618
|
+
* always sum to the counted total, and a name outside the known families counts as fixed - `inventory()` has already
|
|
619
|
+
* refused an unknown epoch member, so the remainder is the epoch's own fixed set rather than a silent fifth holder.
|
|
620
|
+
* `plan` is absent where nothing is planned yet (the renewal preview), which reports `newPlan: null`.
|
|
621
|
+
*/
|
|
622
|
+
export function placementJournalObjectComposition(input:{ names:readonly string[]; plan?:{ root:PlacementPublicationRoot; reserved:readonly string[] } }):PlacementJournalObjectComposition {
|
|
623
|
+
const planned = new Set(input.plan ? publicationFileNames(input.plan.root) : []), reserved = new Set(input.plan?.reserved ?? []);
|
|
624
|
+
// One global active.json slot is always reserved, whether that fence exists yet or not: the counted total's `+ 1`.
|
|
625
|
+
const composition:PlacementJournalObjectComposition = { epochFixed:1, writerHistory:0, journalChunks:0, completedPublications:{ count:0, objects:0 },
|
|
626
|
+
newPlan:input.plan ? { chunks:input.plan.root.chunks.length, slots:planned.size, reservedJournalChunks:reserved.size } : null };
|
|
627
|
+
const sealed = new Set<string>();
|
|
628
|
+
for (const name of new Set([...input.names, ...planned, ...reserved])) {
|
|
629
|
+
if (reserved.has(name) || planned.has(name)) continue; // counted in newPlan, whether or not the file already exists
|
|
630
|
+
if (writerHistoryFileLimit(name) !== undefined) { composition.writerHistory++; continue; }
|
|
631
|
+
if (/^records-\d{5}\.jsonl$/.test(name)) { composition.journalChunks++; continue; }
|
|
632
|
+
const attempt = publicationName(name) ? publicationPattern.exec(name)![1]! : undefined;
|
|
633
|
+
if (attempt) { sealed.add(attempt); composition.completedPublications.objects++; continue; }
|
|
634
|
+
composition.epochFixed++; // epoch.json, activation.json and a pending append-intent.json
|
|
635
|
+
}
|
|
636
|
+
composition.completedPublications.count = sealed.size;
|
|
637
|
+
return composition;
|
|
638
|
+
}
|
|
639
|
+
/** The composition as one numbers-only clause for a refusal or a preview, in the counted total's own order. */
|
|
640
|
+
export function placementJournalObjectCompositionText(composition:PlacementJournalObjectComposition):string {
|
|
641
|
+
const plan = composition.newPlan ? `, new plan ${composition.newPlan.chunks} chunks/${composition.newPlan.slots} slots/${composition.newPlan.reservedJournalChunks} reserved journal chunks` : "";
|
|
642
|
+
const sum = composition.epochFixed + composition.writerHistory + composition.journalChunks + composition.completedPublications.objects
|
|
643
|
+
+ (composition.newPlan ? composition.newPlan.slots + composition.newPlan.reservedJournalChunks : 0);
|
|
644
|
+
return `Objects by holder (${sum}): epoch fixed ${composition.epochFixed}, writer history ${composition.writerHistory}, journal chunks ${composition.journalChunks}, `
|
|
645
|
+
+ `completed publications ${composition.completedPublications.count} (${composition.completedPublications.objects} objects)${plan}.`;
|
|
646
|
+
}
|
|
547
647
|
/** A complete (newline-terminated) root is immutable: keep the last decoded one by its stat stamp (#420), same ceiling as journalPrefix. */
|
|
548
648
|
let reservationRoot: { key: string; root: PlacementPublicationRoot } | undefined;
|
|
549
649
|
function publicationRootsForReservation(p: Paths): PlacementPublicationRoot[] {
|
|
@@ -584,6 +684,8 @@ export interface PlacementPublicationMetadataIO {
|
|
|
584
684
|
names(): string[]; read(name: string): Buffer | undefined; journal(): PlacementJournalRead;
|
|
585
685
|
reservedJournalNames(root: PlacementPublicationRoot): string[];
|
|
586
686
|
publication(attemptHash: string): PlacementPublicationStored;
|
|
687
|
+
/** #288: completed publications frozen by a checkpoint, by attempt; `publication()` resolves them through the same catalog. */
|
|
688
|
+
archivedPublications(): string[];
|
|
587
689
|
complete(name: string, bytes: Buffer, written: PlacementStoragePhase, synced: PlacementStoragePhase): boolean;
|
|
588
690
|
check(): void;
|
|
589
691
|
}
|
|
@@ -593,6 +695,7 @@ function metadataIO(p: Paths, opts?: PlacementStorageOptions, required: readonly
|
|
|
593
695
|
names: () => [...inventory(p).files.keys()], read: name => readOwned(join(p.dir, name), valid(name)), journal: () => snapshot(p),
|
|
594
696
|
reservedJournalNames: root => { const read = snapshot(p); return placementPublicationReservedJournalNames(root, read, read.chunks.map(c => c.size)); },
|
|
595
697
|
publication: hash => { if (!hex(hash)) fail("invalid"); return publicationRead(p, hash); },
|
|
698
|
+
archivedPublications: () => [...p.window.catalog.keys()].sort(),
|
|
596
699
|
complete: (name, bytes, written, synced) => { const maximum = valid(name); if (!opts || !required.includes(name)) fail("invalid"); return complete(p, opts, join(p.dir, name), bytes, maximum, required, written, synced); },
|
|
597
700
|
check: () => { if (opts) current(p, opts, required); else inventory(p); },
|
|
598
701
|
};
|
|
@@ -609,7 +712,7 @@ export function readPlacementPublicationMetadata<T>(home: string, epochHash: str
|
|
|
609
712
|
return capturePlacementPublicationMetadata(home, epochHash, work).value;
|
|
610
713
|
}
|
|
611
714
|
function assertPublicationActive(p: Paths): void {
|
|
612
|
-
const epoch = decode(readOwned(join(p.
|
|
715
|
+
const epoch = decode(readOwned(join(p.epochDir, "epoch.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementEpoch);
|
|
613
716
|
const profile = decode(readOwned(join(p.home, "profile.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementProfile);
|
|
614
717
|
decode(readOwned(join(p.home, "shards.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), value => validatePlacementShards(value, profile));
|
|
615
718
|
const fence = decode(readOwned(join(p.root, "active.json"), PLACEMENT_JOURNAL_ROOT_MAX_BYTES), validatePlacementActiveFence);
|
|
@@ -4,14 +4,14 @@ import { canonicalJSON, hashJSON } from "./generation.ts";
|
|
|
4
4
|
import type { OutboundVerdict } from "./sync-screen.ts";
|
|
5
5
|
import { PLACEMENT_SOURCE_MAX_BYTES, PLACEMENT_SOURCE_MAX_ROWS, PlacementSyncBoundError } from "./sync-placement-bound.ts";
|
|
6
6
|
import type { PlacementCapture } from "./sync-placement-capture.ts";
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
7
|
+
import { compilePlacementDependenciesAsync, type DependencySource, type VerifiedDependencyEndpoint } from "./sync-placement-dependencies.ts";
|
|
8
|
+
import { compilePlacementGitObjectsAsync, type PlannedGitObject } from "./sync-placement-git.ts";
|
|
9
9
|
import { PLACEMENT_DESCRIPTOR_SCHEMA, PLACEMENT_FORMAT } from "./sync-placement-format.ts";
|
|
10
10
|
import { placementKeyId, type PlacementKey, type PlacementRealm } from "./sync-placement-journal-format.ts";
|
|
11
11
|
import type { PlacementProjection } from "./sync-placement-projection.ts";
|
|
12
12
|
import type { PlacementPublicationBundle, PlacementPublicationDecision, PlacementPublicationObject, PlacementPublicationTarget } from "./sync-placement-publication-plan.ts";
|
|
13
13
|
import type { ShardHistory } from "./shard-sync-history.ts";
|
|
14
|
-
import { decodeShardPack,
|
|
14
|
+
import { decodeShardPack, encodeShardPacksAsync, encodeShardManifest, shardSyncRef, type ShardSyncRow, type ShardSyncRealm } from "./shard-sync-format.ts";
|
|
15
15
|
import { cooperativeYield, type CooperativeYield } from "./sync-placement-yield.ts";
|
|
16
16
|
import { verifyPublicPruneWitness, type PublicPruneWitnessV1, type PublicPruneLineage } from "./public-prune-witness.ts";
|
|
17
17
|
import type { Entry } from "./store.ts";
|
|
@@ -65,7 +65,9 @@ export async function materializePlacementRows(input: PlacementMaterializeInput)
|
|
|
65
65
|
// (and its writer proofs), so an unsupported source set refuses before any expensive per-row work (#419).
|
|
66
66
|
const admitted: Omit<DependencySource, "policy">[] = [], seenSources = new Set<string>();
|
|
67
67
|
const prunedByTarget = new Map(workTargets.map(target => [target, target.pruned]));
|
|
68
|
+
let collected = 0;
|
|
68
69
|
for (const source of capture.rows.values()) {
|
|
70
|
+
if (++collected % 64 === 0) await pause();
|
|
69
71
|
const target = workTargets.find(target => sameRealm(physical(target), source.key.realm)); if (!target) refuse();
|
|
70
72
|
const pruned = prunedByTarget.get(target)!.has(source.key.id) && !target.fetched.has(source.key.id);
|
|
71
73
|
if (pruned) blocked.add(placementKeyId(source.key));
|
|
@@ -78,12 +80,14 @@ export async function materializePlacementRows(input: PlacementMaterializeInput)
|
|
|
78
80
|
// Incoming verified occurrences are selected immutable originals too. Classify them before import so a private
|
|
79
81
|
// remote goal cannot temporarily authorize a new dependent, and exposure/holds are durable in this same attempt.
|
|
80
82
|
for(const [index,target]of workTargets.entries())for(const row of old[index]?.rows.values()??[])if(row.op!=="prune"||row.generation===target.generation){
|
|
83
|
+
if (++collected % 64 === 0) await pause();
|
|
81
84
|
const key=keyFor(target,row),id=placementKeyId(key);if(seenSources.has(id))continue;seenSources.add(id);
|
|
82
85
|
admitted.push({key,row,sourcePlacement:"synced",held:!!projection.get(key)?.held});
|
|
83
86
|
}
|
|
84
87
|
// Source size, not outbound size: local and declined rows count too, because their decisions are bound in the plan.
|
|
85
88
|
if (admitted.length > PLACEMENT_SOURCE_MAX_ROWS) throw new PlacementSyncBoundError({ phase: "materialization", kind: "source-rows", limit: PLACEMENT_SOURCE_MAX_ROWS, observed: admitted.length });
|
|
86
|
-
let sourceBytes = 0;
|
|
89
|
+
let sourceBytes = 0;
|
|
90
|
+
for (const [at, source] of admitted.entries()) { if (at % 64 === 0) await pause(); sourceBytes += Buffer.byteLength(canonicalJSON(source.row)); }
|
|
87
91
|
if (sourceBytes > PLACEMENT_SOURCE_MAX_BYTES) throw new PlacementSyncBoundError({ phase: "materialization", kind: "source-bytes", limit: PLACEMENT_SOURCE_MAX_BYTES, observed: sourceBytes });
|
|
88
92
|
input.progress?.phase("policy-evaluation", "rows", admitted.length);
|
|
89
93
|
for (const source of admitted) { await pause(); sources.push({ ...source, policy: input.evaluate(source.row) }); input.progress?.advance(); }
|
|
@@ -107,15 +111,18 @@ export async function materializePlacementRows(input: PlacementMaterializeInput)
|
|
|
107
111
|
let decisions: PlacementPublicationDecision[] = [];
|
|
108
112
|
for (let pass = 0; pass < 2; pass++) {
|
|
109
113
|
await pause();
|
|
110
|
-
|
|
111
|
-
verifiedPrunes:sources.filter(source => verified.has(placementKeyId(source.key))).map(source => source.key) })
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
114
|
+
const compiled = await compilePlacementDependenciesAsync({ generation: input.generation, selectedRealms: workTargets.map(physical), rows:sources, publicEndpoints:endpoints,
|
|
115
|
+
verifiedPrunes:sources.filter(source => verified.has(placementKeyId(source.key))).map(source => source.key) }, pause);
|
|
116
|
+
decisions = [];
|
|
117
|
+
for (const [at, decision] of compiled.entries()) {
|
|
118
|
+
if (at % 64 === 0) await pause();
|
|
119
|
+
const source = sourceMap.get(placementKeyId(decision.key))!;
|
|
120
|
+
const index=workTargets.findIndex(target=>sameRealm(physical(target),decision.key.realm));
|
|
121
|
+
const original=old[index]?.rows.get(decision.key.id), published=!!original&&hashJSON(original)===decision.key.rowHash;
|
|
122
|
+
const reason=blocked.has(placementKeyId(decision.key)) && !projection.get(decision.key)?.held ? "related-local" : decision.reason ?? null;
|
|
123
|
+
decisions.push({ ...decision, sourcePlacement:source.sourcePlacement, reason,
|
|
124
|
+
hold:!decision.eligible&&(reason!=="source-local"||published)&&!projection.get(decision.key)?.held });
|
|
125
|
+
}
|
|
119
126
|
let rejected = false;
|
|
120
127
|
for (const [index,target] of workTargets.entries()) {
|
|
121
128
|
await pause();
|
|
@@ -123,7 +130,7 @@ export async function materializePlacementRows(input: PlacementMaterializeInput)
|
|
|
123
130
|
const publish = descriptorVerdicts[index]!.ok && (!!old[index] || eligible.size > 0); publishes[index] = publish;
|
|
124
131
|
if (publish) files.set("shard.json", Buffer.from(canonicalJSON({schema:PLACEMENT_DESCRIPTOR_SCHEMA,...target.realm,publicationFormat:PLACEMENT_FORMAT})+"\n"));
|
|
125
132
|
const additions = sources.filter(source => sameRealm(source.key.realm,physical(target)) && eligible.has(source.key.id) && !old[index]?.rows.has(source.key.id)).map(source => source.row as ShardSyncRow);
|
|
126
|
-
for (const [path,bytes] of
|
|
133
|
+
for (const [path,bytes] of await encodeShardPacksAsync(additions,pause)) { const prior = files.get(path); if (prior && !prior.equals(bytes)) refuse(); files.set(path,bytes); }
|
|
127
134
|
const manifests = new Map(old[index]?.manifests), occurrences = new Map<string,{pack:string;blob:string}>();
|
|
128
135
|
for (const [path,bytes] of files) if (path.startsWith("rows/")) {
|
|
129
136
|
// #462: one Git blob id per pack, not one per row in it (was quadratic in pack size); same value.
|
|
@@ -150,7 +157,7 @@ export async function materializePlacementRows(input: PlacementMaterializeInput)
|
|
|
150
157
|
if(pass===0&&index===0)input.progress?.phase("artifact-construction");
|
|
151
158
|
if(publish){
|
|
152
159
|
const previous=old[index]&&target.remote?{tree:await input.readTree(index,frozen?.root.targets[index]?.expectedRemoteHead??target.remote!),commit:frozen?.root.targets[index]?.expectedRemoteHead??target.remote!}:undefined;
|
|
153
|
-
const objects=
|
|
160
|
+
const objects=await compilePlacementGitObjectsAsync(files,frozen?.root.targets[index]?.expectedRemoteHead??target.remote??null,createdUnixSeconds,previous,pause);target.objects=objects.objects;target.commit=objects.commit;
|
|
154
161
|
for(const [path,manifest]of manifests)if(manifest.commit==="0".repeat(40))manifests.set(path,{...manifest,commit:objects.commit});
|
|
155
162
|
}else target.commit=target.remote;
|
|
156
163
|
const rows=new Map(old[index]?.rows);for(const row of additions)rows.set(row.id,row);
|
|
@@ -158,13 +165,20 @@ export async function materializePlacementRows(input: PlacementMaterializeInput)
|
|
|
158
165
|
}
|
|
159
166
|
if(!rejected)break;if(pass===1)refuse();
|
|
160
167
|
}
|
|
161
|
-
const plannedTargets:PlacementPublicationTarget[]=
|
|
168
|
+
const plannedTargets: PlacementPublicationTarget[] = [];
|
|
169
|
+
for (const [index, target] of workTargets.entries()) {
|
|
162
170
|
const publish=publishes[index]!,descriptor=target.candidate?.files.get("shard.json");
|
|
163
|
-
|
|
171
|
+
// #470: the export set hashes every row of the target; it is built in chunks so one 8,000-row target cannot hold the loop.
|
|
172
|
+
const exportRows: { id: string; rowHash: string }[] = [];
|
|
173
|
+
for (const [at, row] of [...target.candidate!.rows.values()].entries()) {
|
|
174
|
+
if (at % 64 === 0) await pause();
|
|
175
|
+
exportRows.push({ id: row.id, rowHash: hashJSON(row) });
|
|
176
|
+
}
|
|
177
|
+
plannedTargets[index]={realm:physical(target),publish,refHash:digest(shardSyncRef(target.realm)),expectedRemoteHead:frozen?.root.targets[index]?.expectedRemoteHead??target.remote??null,
|
|
164
178
|
expectedCacheHead:frozen?.root.targets[index]?.expectedCacheHead??target.local??null,descriptorHash:digest(descriptor??Buffer.alloc(0)),
|
|
165
|
-
exportSetHash:hashJSON(
|
|
179
|
+
exportSetHash:hashJSON(exportRows.sort((a,b)=>a.id.localeCompare(b.id))),
|
|
166
180
|
tree:publish?target.objects.find(object=>object.type==="tree"&&object.path==="")!.oid:target.remote?frozen?.root.targets[index]?.tree??null:null,commit:target.commit??null};
|
|
167
|
-
}
|
|
181
|
+
}
|
|
168
182
|
for(const [index,target]of workTargets.entries())if(!plannedTargets[index]!.publish&&target.remote)plannedTargets[index]!.tree=await input.readTree(index,target.remote);
|
|
169
183
|
const objects:PlacementPublicationObject[]=workTargets.flatMap((target,targetIndex)=>target.objects.map(object=>({targetIndex,type:object.type,path:object.path === "" ? null : object.path,oid:object.oid,sha256:digest(object.bytes),size:object.bytes.length})));
|
|
170
184
|
return {decisions,targets:workTargets.map(target=>({candidate:target.candidate!,objects:target.objects,commit:target.commit})),plannedTargets,objects};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { types } from "node:util";
|
|
2
|
-
import { canonicalJSON } from "./generation.ts";
|
|
2
|
+
import { canonicalJSON, hashJSON } from "./generation.ts";
|
|
3
3
|
import {
|
|
4
4
|
SyncPlacementJournalError, PLACEMENT_JOURNAL_MAX_RECORDS, placementEpochHash, placementKeyId,
|
|
5
5
|
validatePlacementEpoch, validatePlacementKey, validatePlacementRecord,
|
|
@@ -32,6 +32,12 @@ export class PlacementProjection {
|
|
|
32
32
|
for (const [key, value] of this.#requests) out.#requests.set(key, value);
|
|
33
33
|
return out;
|
|
34
34
|
}
|
|
35
|
+
/** #288: one hash of the whole projected state (states, row identities, requests, frontier); a checkpoint seals it. */
|
|
36
|
+
digest(): string {
|
|
37
|
+
const sorted = <T>(map: Map<string, T>) => [...map].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
38
|
+
return hashJSON(["agent-mem.sync-placement-projection-digest/v1", this.#epochHash, this.#sequence, this.#headHash,
|
|
39
|
+
sorted(this.#states), sorted(this.#rowHashes), sorted(this.#requests).map(([id, record]) => [id, record.seal])]);
|
|
40
|
+
}
|
|
35
41
|
get epochHash(): string { return this.#epochHash; }
|
|
36
42
|
get sequence(): number { return this.#sequence; }
|
|
37
43
|
get headHash(): string { return this.#headHash; }
|