@staix/agent-mem 0.40.0 → 0.42.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 +2 -2
- package/package.json +4 -3
- package/src/cli.ts +172 -30
- package/src/commands-table.ts +16 -4
- package/src/index.ts +2 -1
- package/src/mcp-bounds.ts +3 -0
- package/src/mcp-memory.ts +64 -10
- package/src/mcp.ts +36 -121
- package/src/memory/candidates.ts +21 -5
- package/src/memory/commands.ts +6 -3
- package/src/memory/config.ts +26 -0
- package/src/memory/consolidation-clusters.ts +13 -2
- package/src/memory/doctor-text.ts +7 -1
- package/src/memory/formats-raise.ts +36 -15
- package/src/memory/formats.ts +26 -10
- package/src/memory/profile-marker-cache.ts +45 -0
- package/src/memory/reader-lease.ts +37 -1
- package/src/memory/search-fts.ts +55 -27
- package/src/memory/shard.ts +17 -14
- package/src/memory/store.ts +5 -3
- package/src/memory/sync-cadence.ts +8 -4
- package/src/memory/sync-placement-activation-locks.ts +27 -19
- package/src/memory/sync-placement-active.ts +67 -19
- package/src/memory/sync-placement-advertisement.ts +25 -3
- package/src/memory/sync-placement-checkpoint-person.ts +35 -13
- package/src/memory/sync-placement-effective-writers.ts +4 -3
- package/src/memory/sync-placement-guard.ts +29 -11
- package/src/memory/sync-placement-inventory.ts +20 -4
- package/src/memory/sync-placement-realm-admission.ts +16 -11
- package/src/memory/sync-placement-refusal.ts +7 -0
- package/src/memory/sync-placement-remote-admission.ts +31 -13
- package/src/memory/sync-placement-remote-refusal.ts +1 -1
- package/src/memory/sync-placement-remote-stage.ts +1 -1
- package/src/memory/sync-placement-transport.ts +28 -12
- package/src/memory/sync-placement-writer-listing.ts +90 -0
- package/src/memory/sync-placement-writer-renewal.ts +5 -7
- package/src/memory/topic.ts +14 -0
- package/src/setup-console.ts +49 -23
- package/src/setup-drift.ts +92 -21
- package/src/setup-writer-roots.ts +17 -3
- package/src/setup.ts +71 -11
- package/src/sync-placement-writer-context.ts +1 -1
|
@@ -8,21 +8,29 @@ import { assertNoLiveReaders } from "./reader-lease.ts";
|
|
|
8
8
|
import { createPlacementActivationOwner } from "./sync-placement-activation-proof.ts";
|
|
9
9
|
/** #578 Q1: a checkpoint fence never refuses for readers; its `busy` means a placement sync, admission or renewal holds a lock. */
|
|
10
10
|
export const PLACEMENT_CHECKPOINT_BUSY_MESSAGE = "Sync placement checkpoint is busy: a placement sync, admission or renewal holds its lock; wait for it to finish (amem sync --status shows recorded operations), then rerun the same checkpoint command.";
|
|
11
|
-
|
|
12
|
-
export
|
|
13
|
-
|
|
14
|
-
|
|
11
|
+
type PlacementMutationSurface = "checkpoint" | "admit" | "renewal";
|
|
12
|
+
export class PlacementInventoryFenceError extends Error {
|
|
13
|
+
constructor(readonly causeClass: "readers" | "busy", surface?: PlacementMutationSurface) {
|
|
14
|
+
const message = causeClass === "readers"
|
|
15
|
+
? "Sync placement migration is blocked by live readers; close cooperating readers/writers, then run amem migrate --sync-placement --dry-run before retrying."
|
|
16
|
+
: surface === "checkpoint" ? PLACEMENT_CHECKPOINT_BUSY_MESSAGE
|
|
17
|
+
: surface === "admit" ? "Sync placement realm admission is busy; wait for the operation holding its lock (amem sync --status), then run amem migrate --sync-placement --admit <project> --dry-run."
|
|
18
|
+
: surface === "renewal" ? "Sync placement writer renewal is busy; wait for the operation holding its lock (amem sync --status), then run amem migrate --sync-placement --dry-run before retrying."
|
|
19
|
+
: "Sync placement migration is busy; close cooperating readers/writers, then run amem migrate --sync-placement --dry-run before retrying.";
|
|
20
|
+
super(message);
|
|
21
|
+
this.name = "PlacementInventoryFenceError";
|
|
22
|
+
}
|
|
15
23
|
}
|
|
16
|
-
type FenceWork<T
|
|
17
|
-
async function withFences<T>(home:string,directories:readonly string[],
|
|
18
|
-
const fail=(cause:"readers"|"busy"):never=>{throw new PlacementInventoryFenceError(cause
|
|
24
|
+
type FenceWork<T> = (mutation: MutationHandle, owner: ReturnType<typeof createPlacementActivationOwner>) => Promise<T>;
|
|
25
|
+
async function withFences<T>(home: string, directories: readonly string[], work: FenceWork<T>, surface?: PlacementMutationSurface): Promise<T> {
|
|
26
|
+
const fail = (cause: "readers" | "busy"): never => { throw new PlacementInventoryFenceError(cause, surface); };
|
|
19
27
|
return withProfileLock(home,async()=>{
|
|
20
28
|
const releases:(()=>void)[]=[];
|
|
21
29
|
try {
|
|
22
30
|
const transports=["shard-sync","shard-sync-placement"].map(name=>join(home,name)).filter(dir=>lstatSync(dir,{throwIfNoEntry:false})!==undefined);
|
|
23
31
|
const dirs=[...new Set([home,...directories,...transports])].sort();let mutation:MutationHandle|undefined;
|
|
24
32
|
for(const dir of dirs){
|
|
25
|
-
if(
|
|
33
|
+
if(surface === undefined){try{assertNoLiveReaders(dir,{includeShards:true});}catch{fail("readers");}}
|
|
26
34
|
const handle=acquireMutation(dir);if(!handle)fail("busy");releases.push(handle!);if(dir===home)mutation=handle!;
|
|
27
35
|
}
|
|
28
36
|
if(!mutation)fail("busy");
|
|
@@ -31,16 +39,16 @@ async function withFences<T>(home:string,directories:readonly string[],options:{
|
|
|
31
39
|
}finally{for(const release of releases.reverse())release();}
|
|
32
40
|
});
|
|
33
41
|
}
|
|
34
|
-
/**
|
|
35
|
-
export function withPlacementActivationFences<T>(home:string,directories:readonly string[],work:FenceWork<T
|
|
36
|
-
return withFences(home,directories,
|
|
42
|
+
/** Initial activation changes the markers that readers bind to when opening a store. */
|
|
43
|
+
export function withPlacementActivationFences<T>(home: string, directories: readonly string[], work: FenceWork<T>): Promise<T> {
|
|
44
|
+
return withFences(home, directories, work);
|
|
37
45
|
}
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
export function withPlacementCheckpointFences<T>(home:string,directories:readonly string[],work:FenceWork<T>):Promise<T> {
|
|
45
|
-
return
|
|
46
|
+
|
|
47
|
+
/** Active placement mutations leave store bindings intact. The profile lock still blocks new readers. */
|
|
48
|
+
export function withPlacementMutationFences<T>(home: string, directories: readonly string[], work: FenceWork<T>, options: { surface: PlacementMutationSurface }): Promise<T> {
|
|
49
|
+
return withFences(home, directories, work, options.surface);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function withPlacementCheckpointFences<T>(home: string, directories: readonly string[], work: FenceWork<T>): Promise<T> {
|
|
53
|
+
return withPlacementMutationFences(home, directories, work, { surface: "checkpoint" });
|
|
46
54
|
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { freezeMetadata, isMetadataSnapshot, sameMetadataStamp } from "./profile-marker-cache.ts";
|
|
1
2
|
/** Metadata-only v3 admission. Publication still requires the complete journal/source/policy proof. */
|
|
2
3
|
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type BigIntStats } from "node:fs";
|
|
3
4
|
import { join } from "node:path";
|
|
4
|
-
import { reportBindingRead } from "./binding-read-set.ts";
|
|
5
|
+
import { collectBindingReads, reportBindingRead } from "./binding-read-set.ts";
|
|
5
6
|
import { canonicalJSON, hashJSON } from "./generation.ts";
|
|
6
7
|
import { realPath } from "./platform.ts";
|
|
7
8
|
import { homeIdentityHash } from "./home-identity.ts";
|
|
@@ -14,7 +15,6 @@ import { shardDir, userShardDir } from "./shard.ts";
|
|
|
14
15
|
|
|
15
16
|
export interface ActivePlacementBinding { profile: PlacementProfile; shards: PlacementShards; epoch: PlacementEpoch; activation: SyncPlacementActivationPlan }
|
|
16
17
|
function fail(): never { throw new Error("sync placement activation metadata unavailable or changed; inspect the retained activation before continuing"); }
|
|
17
|
-
const same = (a: BigIntStats, b: BigIntStats) => a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs;
|
|
18
18
|
function owned(s: BigIntStats, directory = false): void {
|
|
19
19
|
if (s.uid !== BigInt(process.getuid?.() ?? -1) || (s.mode & 0o077n) !== 0n || s.isSymbolicLink()
|
|
20
20
|
|| (directory ? !s.isDirectory() : !s.isFile() || s.nlink !== 1n)) fail();
|
|
@@ -26,7 +26,35 @@ export function assertPlacementViewAdvance(home: string, activation: SyncPlaceme
|
|
|
26
26
|
if (canonicalJSON(before) !== canonicalJSON(after)) fail();
|
|
27
27
|
const initialShards = { ...shards, selectorRevision: hashJSON(initial) };
|
|
28
28
|
if (hashJSON(initialShards) !== activation.targetShardsHash) fail();
|
|
29
|
+
assertLivePruneAdvance(home, initial, profile);
|
|
30
|
+
}
|
|
31
|
+
function assertLivePruneAdvance(home: string, initial: PlacementProfile, profile: PlacementProfile): void {
|
|
29
32
|
if (initial.pruneInputSetHash === profile.pruneInputSetHash) return;
|
|
33
|
+
// #656: a fence check runs this per row. Reuse a positive answer only while every file and directory the full check read
|
|
34
|
+
// keeps its dev:ino:size:mtimeNs:ctimeNs stamp; a stat error or any change takes the full check again. Only a reused-proof
|
|
35
|
+
// fence check (inside withPlacementFenceMemo) uses the memo: every other reader, the brief fence included, reads in full.
|
|
36
|
+
if (fenceMemoDepth === 0) { assertLivePruneAdvanceUncached(home, initial, profile); return; }
|
|
37
|
+
const key = JSON.stringify([home, initial.pruneInputSetHash, profile.pruneInputSetHash, profile.generation]), cached = pruneAdvanceMemo.get(key);
|
|
38
|
+
if (cached && pathStamps(cached.paths) === cached.stamps) return;
|
|
39
|
+
pruneAdvanceMemo.delete(key);
|
|
40
|
+
const { paths } = collectBindingReads(() => assertLivePruneAdvanceUncached(home, initial, profile));
|
|
41
|
+
const stamps = pathStamps(paths);
|
|
42
|
+
// The stamps are taken after the read, so the check runs once more under them: a change between the read and the stamp is never memoized.
|
|
43
|
+
if (stamps !== undefined) assertLivePruneAdvanceUncached(home, initial, profile);
|
|
44
|
+
if (stamps !== undefined && pathStamps(paths) === stamps) { if (pruneAdvanceMemo.size >= 32) pruneAdvanceMemo.delete(pruneAdvanceMemo.keys().next().value!); pruneAdvanceMemo.set(key, { paths, stamps }); }
|
|
45
|
+
}
|
|
46
|
+
// ponytail: 32 entries across homes, keyed by resolved home; same-size in-place rewrites within one stat tick are not seen (profile-marker-cache ceiling).
|
|
47
|
+
const pruneAdvanceMemo = new Map<string, { paths: string[]; stamps: string }>();
|
|
48
|
+
let fenceMemoDepth = 0;
|
|
49
|
+
/** #656: run a cheap fence check whose prune-advance answer may be reused while its files keep their stamps. */
|
|
50
|
+
export function withPlacementFenceMemo<T>(work: () => T): T { fenceMemoDepth++; try { return work(); } finally { fenceMemoDepth--; } }
|
|
51
|
+
function pathStamps(paths: readonly string[]): string | undefined {
|
|
52
|
+
const out: string[] = [];
|
|
53
|
+
try { for (const path of paths) { const s = lstatSync(path, { bigint: true, throwIfNoEntry: false }); if (!s) return undefined; out.push([s.dev, s.ino, s.mode, s.size, s.mtimeNs, s.ctimeNs].map(String).join(":")); } }
|
|
54
|
+
catch { return undefined; }
|
|
55
|
+
return JSON.stringify(out);
|
|
56
|
+
}
|
|
57
|
+
function assertLivePruneAdvanceUncached(home: string, initial: PlacementProfile, profile: PlacementProfile): void {
|
|
30
58
|
const oldView = readPublicPruneViewForActivation(home, initial.pruneInputSetHash, profile.generation);
|
|
31
59
|
const nextView = readPublicPruneViewForActivation(home, profile.pruneInputSetHash, profile.generation);
|
|
32
60
|
if (!Object.keys(oldView.realms).every(key => Object.hasOwn(nextView.realms, key))) fail();
|
|
@@ -37,16 +65,26 @@ export function assertPlacementViewAdvance(home: string, activation: SyncPlaceme
|
|
|
37
65
|
if (old !== undefined && !chain.commitments.includes(old)) fail();
|
|
38
66
|
}
|
|
39
67
|
}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
const
|
|
46
|
-
|
|
68
|
+
// Only file-reader snapshots have stable identity. Arbitrary caller objects always take the full validator.
|
|
69
|
+
const shardProofs = new WeakMap<object, { input: object; proof: { profile: PlacementProfile; shards: PlacementShards } }>();
|
|
70
|
+
export function provePlacementShards(value: unknown, profileInput: unknown): { profile: PlacementProfile; shards: PlacementShards } {
|
|
71
|
+
const cached = isMetadataSnapshot(value) ? shardProofs.get(value) : undefined;
|
|
72
|
+
if (cached && cached.input === profileInput) return cached.proof;
|
|
73
|
+
const profile = validatePlacementProfile(profileInput);
|
|
74
|
+
const proof = { profile, shards: validatePlacementShards(value, profile) };
|
|
75
|
+
if (isMetadataSnapshot(value) && isMetadataSnapshot(profileInput)) {
|
|
76
|
+
shardProofs.set(value, { input: profileInput, proof: freezeMetadata(proof) });
|
|
77
|
+
}
|
|
78
|
+
return proof;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
type BindingProof = Pick<ActivePlacementBinding, "epoch" | "activation">;
|
|
82
|
+
// ponytail: only one proof per parsed shard snapshot (bounded by the marker caches), plus one for arbitrary inputs.
|
|
83
|
+
const snapshotBindings = new WeakMap<object, { key: string; profileInput: object; value: BindingProof }>();
|
|
84
|
+
let valueBinding: { key: string; value: BindingProof } | undefined;
|
|
47
85
|
/** No mutation/reader registration/index open. Missing preparation is distinct from malformed retained evidence. */
|
|
48
86
|
export function readActivePlacementBinding(homeInput: string, profileInput: unknown, shardsInput: unknown): ActivePlacementBinding | undefined {
|
|
49
|
-
const profile
|
|
87
|
+
const { profile, shards } = provePlacementShards(shardsInput, profileInput);
|
|
50
88
|
const home = realPath(homeInput), root = lstatSync(home, { bigint: true }); owned(root, true);
|
|
51
89
|
const stampKey = () => {
|
|
52
90
|
const dir = join(home, "sync-placement", "epochs", profile.placementHead), stamps: string[] = [];
|
|
@@ -56,11 +94,17 @@ export function readActivePlacementBinding(homeInput: string, profileInput: unkn
|
|
|
56
94
|
reportBindingRead(file);
|
|
57
95
|
stamps.push([st.dev, st.ino, st.size, st.mtimeNs, st.ctimeNs].map(String).join(":"));
|
|
58
96
|
}
|
|
59
|
-
return
|
|
97
|
+
return JSON.stringify([home, stamps]);
|
|
60
98
|
}, memoKey = stampKey();
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
99
|
+
const snapshot = isMetadataSnapshot(profileInput) && isMetadataSnapshot(shardsInput) ? { profileInput, shardsInput } : undefined;
|
|
100
|
+
const previous = snapshot && snapshotBindings.get(snapshot.shardsInput);
|
|
101
|
+
const valueKey = !snapshot && memoKey !== undefined ? canonicalJSON([memoKey, profile, shards]) : undefined;
|
|
102
|
+
const cached = previous && previous.key === memoKey && previous.profileInput === profileInput ? previous.value
|
|
103
|
+
: valueKey !== undefined && valueBinding?.key === valueKey ? valueBinding.value : undefined;
|
|
104
|
+
if (cached) {
|
|
105
|
+
// The binding stamps cover the static commitments. Prune artifacts can change independently.
|
|
106
|
+
assertLivePruneAdvance(home, cached.activation.targetProfile, profile);
|
|
107
|
+
return { profile: { ...profile }, shards: snapshot ? structuredClone(shards) : shards, ...cached };
|
|
64
108
|
}
|
|
65
109
|
const checks: (() => void)[] = [() => { const now = lstatSync(home, { bigint: true }); owned(now, true); if (now.dev !== root.dev || now.ino !== root.ino) fail(); }];
|
|
66
110
|
const directory = (dir: string): boolean => {
|
|
@@ -73,13 +117,13 @@ export function readActivePlacementBinding(homeInput: string, profileInput: unkn
|
|
|
73
117
|
owned(before); if (before.size <= 0n || before.size > 262144n) fail();
|
|
74
118
|
const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
75
119
|
try {
|
|
76
|
-
const s = fstatSync(fd, { bigint: true }); owned(s); if (!
|
|
120
|
+
const s = fstatSync(fd, { bigint: true }); owned(s); if (!sameMetadataStamp(before, s)) fail();
|
|
77
121
|
const bytes = Buffer.alloc(Number(s.size) + 1); let at = 0;
|
|
78
122
|
while (at < bytes.length) { const n = readSync(fd, bytes, at, bytes.length - at, at); if (!n) break; at += n; }
|
|
79
|
-
if (at !== Number(s.size) || !
|
|
123
|
+
if (at !== Number(s.size) || !sameMetadataStamp(s, fstatSync(fd, { bigint: true })) || !sameMetadataStamp(s, lstatSync(file, { bigint: true }))) fail();
|
|
80
124
|
const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, at)), value: unknown = JSON.parse(text);
|
|
81
125
|
if (canonicalJSON(value) + "\n" !== text) fail();
|
|
82
|
-
checks.push(() => { const now = lstatSync(file, { bigint: true }); owned(now); if (!
|
|
126
|
+
checks.push(() => { const now = lstatSync(file, { bigint: true }); owned(now); if (!sameMetadataStamp(s, now)) fail(); }); return { value, text };
|
|
83
127
|
} finally { closeSync(fd); }
|
|
84
128
|
};
|
|
85
129
|
if (!directory(join(home, "sync-placement")) || !directory(join(home, "sync-placement", "epochs"))) return undefined;
|
|
@@ -95,6 +139,10 @@ export function readActivePlacementBinding(homeInput: string, profileInput: unkn
|
|
|
95
139
|
if (read(join(home, "profile.json"))?.text !== canonicalJSON(profile) + "\n" || read(join(home, "shards.json"))?.text !== canonicalJSON(shards) + "\n") fail();
|
|
96
140
|
assertPlacementViewAdvance(home, activation, profile, shards);
|
|
97
141
|
for (const check of checks) check();
|
|
98
|
-
if (memoKey !== undefined && stampKey() === memoKey)
|
|
99
|
-
|
|
142
|
+
if (memoKey !== undefined && stampKey() === memoKey) {
|
|
143
|
+
const value = { epoch: freezeMetadata(epoch), activation: freezeMetadata(activation) };
|
|
144
|
+
if (snapshot) snapshotBindings.set(snapshot.shardsInput, { key: memoKey, profileInput: snapshot.profileInput, value });
|
|
145
|
+
else if (valueKey !== undefined) valueBinding = { key: valueKey, value };
|
|
146
|
+
}
|
|
147
|
+
return { profile: { ...profile }, shards: snapshot ? structuredClone(shards) : shards, epoch, activation };
|
|
100
148
|
}
|
|
@@ -5,14 +5,36 @@ import type { SyncOptions } from "./sync.ts";
|
|
|
5
5
|
* shared by the run's publications. Kept off the public SyncOptions type (host API fixture): the inventory driver binds a
|
|
6
6
|
* fresh map to its own options object, and a publication reached with other options reads per run as before.
|
|
7
7
|
* Never authority: each publication still proves every target against it, and a publication that pushes deletes its entry.
|
|
8
|
+
*
|
|
9
|
+
* #656: the same run scope also holds the remote visibility answer by exact URL (one `gh repo view` per run, not per
|
|
10
|
+
* batch), and tells a publication to leave the placement storage memos for the driver to release in its finally.
|
|
8
11
|
*/
|
|
9
|
-
|
|
12
|
+
interface PlacementRun { advertisement: Map<string, ReadonlyMap<string, string>>; visibility: Map<string, Promise<string>> }
|
|
13
|
+
const runs = new WeakMap<SyncOptions, PlacementRun>();
|
|
10
14
|
|
|
11
15
|
export function bindPlacementAdvertisement(opts: SyncOptions): SyncOptions {
|
|
12
|
-
runs.set(opts, new Map());
|
|
16
|
+
runs.set(opts, { advertisement: new Map(), visibility: new Map() });
|
|
13
17
|
return opts;
|
|
14
18
|
}
|
|
15
19
|
|
|
20
|
+
/** Ends the run scope: later publications with these options read visibility and release storage memos on their own again. */
|
|
21
|
+
export function releasePlacementRun(opts: SyncOptions): void { runs.delete(opts); }
|
|
22
|
+
|
|
16
23
|
export function placementAdvertisement(opts: SyncOptions): Map<string, ReadonlyMap<string, string>> | undefined {
|
|
17
|
-
return runs.get(opts);
|
|
24
|
+
return runs.get(opts)?.advertisement;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Whether a publication with these options runs inside an inventory run that releases the storage memos itself. */
|
|
28
|
+
export function placementStorageCacheScope(opts: SyncOptions): boolean { return runs.has(opts); }
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Remote visibility, read once per exact URL inside one inventory run. Only a "private" answer is kept: any other answer or a
|
|
32
|
+
* failed read is dropped, so the next publication asks again and the refusal stays before any lock or fetch.
|
|
33
|
+
*/
|
|
34
|
+
export function placementVisibility(opts: SyncOptions, url: string, read: (url: string) => Promise<string>): Promise<string> {
|
|
35
|
+
const run = runs.get(opts); if (!run) return read(url);
|
|
36
|
+
const known = run.visibility.get(url); if (known) return known;
|
|
37
|
+
const pending = read(url).then(value => { if (value !== "private") run.visibility.delete(url); return value; },
|
|
38
|
+
error => { run.visibility.delete(url); throw error; });
|
|
39
|
+
run.visibility.set(url, pending); return pending;
|
|
18
40
|
}
|
|
@@ -10,7 +10,7 @@ import { memoryPolicySnapshot } from "./policy.ts";
|
|
|
10
10
|
import { realPath } from "./platform.ts";
|
|
11
11
|
import { canonicalJSON } from "./generation.ts";
|
|
12
12
|
import { assertFormatFloor, formatVersionBelow, readFormatFloors } from "./formats.ts";
|
|
13
|
-
import { installVersion } from "./formats-raise.ts";
|
|
13
|
+
import { installAbsent, installVersion } from "./formats-raise.ts";
|
|
14
14
|
import { SyncPlacementJournalError } from "./sync-placement-journal-format.ts";
|
|
15
15
|
import { PLACEMENT_JOURNAL_CHUNK_MAX_BYTES, PLACEMENT_JOURNAL_MAX_OBJECTS } from "./sync-placement-journal-format.ts";
|
|
16
16
|
import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
|
|
@@ -25,7 +25,7 @@ import { PLACEMENT_CHECKPOINT_LIMIT, PLACEMENT_CHECKPOINT_MIN_READER, validateCh
|
|
|
25
25
|
import { withPlacementCheckpointFences } from "./sync-placement-activation-locks.ts";
|
|
26
26
|
import { assertPlacementActivationOwner } from "./sync-placement-activation-proof.ts";
|
|
27
27
|
import { placementFenceDirectories } from "./sync-placement-writer-renewal.ts";
|
|
28
|
-
import { initialPlacementWriterContext } from "../sync-placement-writer-context.ts";
|
|
28
|
+
import { initialPlacementWriterContext, placementWriterRefusalDetail } from "../sync-placement-writer-context.ts";
|
|
29
29
|
import { readSetupWriterRoots, SetupWriterRootsError } from "../setup-writer-roots.ts";
|
|
30
30
|
import { checkpointProspective, type CheckpointProspective } from "./sync-placement-checkpoint-prospective.ts";
|
|
31
31
|
import { ShardHistoryError, type ShardHistoryCause } from "./shard-sync-history.ts";
|
|
@@ -35,7 +35,7 @@ const RESUME = `${CHECKPOINT_PREVIEW} --resume`, ABANDON = `${CHECKPOINT_PREVIEW
|
|
|
35
35
|
const homeFloorAtLeast = (home: string, minimum: string): boolean =>
|
|
36
36
|
(readFormatFloors(home) ?? []).some(floor => floor.surface === "home" && !formatVersionBelow(floor.minReader, minimum));
|
|
37
37
|
|
|
38
|
-
export type PlacementCheckpointCause = "pending" | "commit-started" | "floor" | "writer-below-floor" | "headroom" | "obligation" | "changed" | "inactive" | "candidate" | "history";
|
|
38
|
+
export type PlacementCheckpointCause = "pending" | "commit-started" | "floor" | "writer-below-floor" | "headroom" | "obligation" | "changed" | "inactive" | "candidate" | "history" | "writer-missing";
|
|
39
39
|
const MESSAGES: Record<PlacementCheckpointCause, string> = {
|
|
40
40
|
pending: PLACEMENT_CHECKPOINT_PENDING_MESSAGE,
|
|
41
41
|
"commit-started": `The placement checkpoint's commit line has started, so it can no longer be abandoned; run ${RESUME} to complete it.`,
|
|
@@ -45,8 +45,9 @@ const MESSAGES: Record<PlacementCheckpointCause, string> = {
|
|
|
45
45
|
obligation: "The placement journal has an unfinished append, publication, reservation, renewal or source recovery; finish it with amem sync (or the pending renewal with amem migrate --sync-placement --resume), then preview the checkpoint again.",
|
|
46
46
|
changed: `The placement state changed since the checkpoint plan was sealed; preview a fresh plan with ${CHECKPOINT_PREVIEW} and confirm that one.`,
|
|
47
47
|
inactive: "This home has no active sync placement; activate it with amem migrate --sync-placement --dry-run first.",
|
|
48
|
-
candidate: `A checkpoint carries one writer renewal: pass the complete inventory as repeatable --writer-root <install root> (every amem install sharing this home), then preview again with ${CHECKPOINT_PREVIEW}.`,
|
|
48
|
+
candidate: `A checkpoint carries one writer renewal: list the inventory and the roots to declare with amem migrate --sync-placement --writers, then pass the complete inventory as repeatable --writer-root <install root> (every amem install sharing this home) or use --discovered-writers, then preview again with ${CHECKPOINT_PREVIEW}.`,
|
|
49
49
|
history: "",
|
|
50
|
+
"writer-missing": "",
|
|
50
51
|
};
|
|
51
52
|
/** #567: the retained-history cause class and, for `bound`, which bound with its counts. Never a path, row or object id. */
|
|
52
53
|
export interface PlacementCheckpointHistoryRefusal { category: "shard history"; cause: ShardHistoryCause; kind?: string; limit?: number; observed?: number }
|
|
@@ -62,7 +63,7 @@ export class PlacementCheckpointError extends Error {
|
|
|
62
63
|
readonly history?: PlacementCheckpointHistoryRefusal;
|
|
63
64
|
constructor(readonly causeClass: PlacementCheckpointCause, detail = "", history?: PlacementCheckpointHistoryRefusal) {
|
|
64
65
|
super(causeClass === "headroom" ? `The checkpoint would not leave room for the next sync: ${detail} A single checkpoint cannot unblock this plan; the deferred multi-plan split in #288 design item 5 is the open path. Nothing was written.`
|
|
65
|
-
: causeClass === "history" && history ? historyMessage(history) : MESSAGES[causeClass]
|
|
66
|
+
: causeClass === "history" && history ? historyMessage(history) : [MESSAGES[causeClass], detail].filter(Boolean).join(" "));
|
|
66
67
|
this.name = "PlacementCheckpointError";
|
|
67
68
|
if (causeClass === "history" && history) this.history = history;
|
|
68
69
|
}
|
|
@@ -86,10 +87,17 @@ function input(home: string, a: ActivePlacementBinding, roots: PlacementCheckpoi
|
|
|
86
87
|
}
|
|
87
88
|
function measured(home: string, writerRoots: readonly string[], ownRoot: string): PlacementCheckpointInput["roots"] {
|
|
88
89
|
if (!writerRoots.length) throw new PlacementCheckpointError("candidate");
|
|
89
|
-
|
|
90
|
+
// #634: name a removed install before measurement turns it into a generic inventory refusal; preview and confirm both pass here.
|
|
91
|
+
const missing = writerRoots.find(installAbsent);
|
|
92
|
+
if (missing !== undefined) throw new PlacementCheckpointError("writer-missing", missingWriterMessage(missing));
|
|
93
|
+
try { return initialPlacementWriterContext(home, writerRoots, ownRoot).measurement.roots; }
|
|
94
|
+
catch (error) {
|
|
95
|
+
const refusal = placementWriterRefusalDetail(error);
|
|
96
|
+
if (refusal && !(refusal.rootCategory === "running CLI" && refusal.causeClass === "missing")) throw error;
|
|
97
|
+
throw new PlacementCheckpointError("candidate");
|
|
98
|
+
}
|
|
90
99
|
}
|
|
91
100
|
function plan(home: string, epochHash: string, value: PlacementCheckpointInput): CheckpointIntent {
|
|
92
|
-
if (placementCheckpointPending(home, epochHash)) throw new PlacementCheckpointError("pending");
|
|
93
101
|
try { return planPlacementCheckpoint(home, epochHash, value); }
|
|
94
102
|
catch (error) {
|
|
95
103
|
const code = error instanceof SyncPlacementJournalError ? Object.getOwnPropertyDescriptor(error, "code")?.value : undefined;
|
|
@@ -119,14 +127,17 @@ export interface PlacementCheckpointPreview {
|
|
|
119
127
|
*/
|
|
120
128
|
export async function previewPlacementCheckpoint(homeInput: string, opts: { writerRoots: readonly string[]; ownRoot: string }): Promise<PlacementCheckpointPreview> {
|
|
121
129
|
const home = realPath(homeInput), a = active(home), epochHash = a.profile.placementHead;
|
|
122
|
-
const roots = measured(home, opts.writerRoots, opts.ownRoot)
|
|
130
|
+
const roots = measured(home, opts.writerRoots, opts.ownRoot);
|
|
131
|
+
if (placementCheckpointPending(home, epochHash)) throw new PlacementCheckpointError("pending");
|
|
132
|
+
checkWriterVersions(home, roots);
|
|
133
|
+
const intent = plan(home, epochHash, input(home, a, roots, randomBytes(32).toString("hex")));
|
|
123
134
|
const journal = readPlacementJournal(home, epochHash), window = resolvePlacementWindow(home, epochHash);
|
|
124
135
|
const { headroom, journalObjects, assertCurrent } = await checkpointHeadroom(home, intent);
|
|
125
136
|
assertCurrent();
|
|
126
137
|
const minReader = PLACEMENT_CHECKPOINT_MIN_READER;
|
|
127
138
|
return { mode: "checkpoint-preview", window: window.window, nextWindow: intent.window, journalObjects, currentObjects: journal.objects, headroom,
|
|
128
139
|
floorReady: homeFloorAtLeast(home, minReader), requiredHomeFloor: minReader, writers: roots.length, planHash: intent.seal, plan: intent,
|
|
129
|
-
nextStep:
|
|
140
|
+
nextStep: `${CHECKPOINT_PREVIEW} --writer-root <install root> --out checkpoint-plan.json, repeating --writer-root for every install (or --discovered-writers), then ${CHECKPOINT_PREVIEW} --confirm --plan checkpoint-plan.json` };
|
|
130
141
|
}
|
|
131
142
|
async function checkpointHeadroom(home: string, intent: CheckpointIntent): Promise<{ headroom: PlacementCheckpointHeadroom; journalObjects: PlacementJournalObjectComposition; assertCurrent(): void }> {
|
|
132
143
|
const epochHash = intent.epochHash, prospective = await checkpointProspective(home).catch(historyRefusal);
|
|
@@ -167,13 +178,22 @@ function reviewedHeadroom(value: unknown): unknown {
|
|
|
167
178
|
if (!detached) throw new PlacementCheckpointError("changed");
|
|
168
179
|
return detached;
|
|
169
180
|
}
|
|
181
|
+
function missingWriterMessage(root: string): string {
|
|
182
|
+
return `The install at ${root} no longer exists; drop that --writer-root, then save the preview again with ${CHECKPOINT_PREVIEW} --writer-root <install root> --out checkpoint-plan.json, repeating --writer-root for every remaining install, and confirm it with ${CHECKPOINT_PREVIEW} --confirm --plan checkpoint-plan.json.`;
|
|
183
|
+
}
|
|
170
184
|
function checkFloor(home: string, roots: PlacementCheckpointInput["roots"] | undefined, minReader: string): void {
|
|
171
185
|
if (!homeFloorAtLeast(home, minReader)) throw new PlacementCheckpointError("floor");
|
|
172
186
|
// This reader itself below the recorded floor cannot measure anything: name the writer cause, not the inventory.
|
|
173
187
|
try { assertFormatFloor(home, "sync"); } catch { throw new PlacementCheckpointError("writer-below-floor"); }
|
|
174
|
-
if (
|
|
188
|
+
if (roots) checkWriterVersions(home, roots);
|
|
189
|
+
}
|
|
190
|
+
function checkWriterVersions(home: string, roots: PlacementCheckpointInput["roots"]): void {
|
|
175
191
|
const effective = readEffectiveSyncPlacementWriters(home).roots ?? [];
|
|
176
|
-
|
|
192
|
+
// #634: an inventoried install that is gone from disk and left out of the new plan can no longer write here; the
|
|
193
|
+
// renewal removes it. A root the new plan measures is checked through its measured version.
|
|
194
|
+
const renewed = new Set(roots.map(root => root.root));
|
|
195
|
+
const retained = effective.filter(root => !renewed.has(root) && !installAbsent(root));
|
|
196
|
+
const versions = [...roots.map(root => root.version), ...retained.map(root => installVersion(root))];
|
|
177
197
|
const floors = (readFormatFloors(home) ?? []).filter(floor => floor.surface === "home" || floor.surface === "sync");
|
|
178
198
|
if (versions.some(version => version === null || floors.some(floor => formatVersionBelow(version, floor.minReader)))) throw new PlacementCheckpointError("writer-below-floor");
|
|
179
199
|
}
|
|
@@ -183,12 +203,14 @@ function checkFloor(home: string, roots: PlacementCheckpointInput["roots"] | und
|
|
|
183
203
|
*/
|
|
184
204
|
export async function confirmPlacementCheckpoint(homeInput: string, value: unknown, opts: { writerRoots: readonly string[]; ownRoot: string; phase?: (phase: PlacementCheckpointPhase) => void }): Promise<{ window: number; renewed: true; planHash: string; nextStep: string }> {
|
|
185
205
|
const home = realPath(homeInput), intent = checkpointPlanFrom(value), a = active(home), minReader = PLACEMENT_CHECKPOINT_MIN_READER;
|
|
206
|
+
// #660: without --writer-root the sealed plan names the roots; every one is still measured fresh here and under the fences.
|
|
207
|
+
const writerRoots = opts.writerRoots.length ? opts.writerRoots : intent.writerRevision.roots.map(root => root.root);
|
|
186
208
|
if (intent.epochHash !== a.profile.placementHead) throw new PlacementCheckpointError("changed");
|
|
187
|
-
checkFloor(home, undefined, minReader); checkFloor(home, measured(home,
|
|
209
|
+
checkFloor(home, undefined, minReader); checkFloor(home, measured(home, writerRoots, opts.ownRoot), minReader);
|
|
188
210
|
const prospective = await checkpointHeadroom(home, intent);
|
|
189
211
|
if (canonicalJSON(reviewedHeadroom(value)) !== canonicalJSON(prospective.headroom)) throw new PlacementCheckpointError("changed");
|
|
190
212
|
return withPlacementCheckpointFences(home, placementFenceDirectories(home, a), async (mutation, owner) => {
|
|
191
|
-
const now = active(home), roots = measured(home,
|
|
213
|
+
const now = active(home), roots = measured(home, writerRoots, opts.ownRoot);
|
|
192
214
|
if (canonicalJSON(now) !== canonicalJSON(a)) throw new PlacementCheckpointError("changed");
|
|
193
215
|
prospective.assertCurrent();
|
|
194
216
|
checkFloor(home, roots, minReader);
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { lstatSync, opendirSync } from "node:fs";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { hashJSON } from "./generation.ts";
|
|
5
|
-
import {
|
|
5
|
+
import { readPlacementRuntimeMarkerSnapshots } from "./sync-placement-guard.ts";
|
|
6
6
|
import { readActivePlacementBinding, type ActivePlacementBinding } from "./sync-placement-active.ts";
|
|
7
7
|
import { readPlacementWriterJournalAnchors, placementWriterJournalToken } from "./sync-placement-journal-storage.ts";
|
|
8
8
|
import { readWriterHistory, isWriterRenewalIntentTempName } from "./sync-placement-writer-history.ts";
|
|
@@ -19,7 +19,7 @@ export interface EffectiveSyncPlacementWriters {
|
|
|
19
19
|
}
|
|
20
20
|
function fail():never{throw new SharedWriterRevisionError("changed");}
|
|
21
21
|
function active(home:string):ActivePlacementBinding {
|
|
22
|
-
const markers=
|
|
22
|
+
const markers=readPlacementRuntimeMarkerSnapshots(home),value=readActivePlacementBinding(home,markers.profile,markers.shards);if(!value)fail();return value;
|
|
23
23
|
}
|
|
24
24
|
const key=(value:ActivePlacementBinding)=>hashJSON({epoch:value.epoch,activation:value.activation,head:value.profile.placementHead,generation:value.profile.generation});
|
|
25
25
|
const fileStamp=(home:string)=>{
|
|
@@ -67,7 +67,8 @@ export function readEffectiveSyncPlacementWriters(home:string):EffectiveSyncPlac
|
|
|
67
67
|
if(placementWriterJournalToken(home,epochHash)!==token)fail();anchorToken=token;
|
|
68
68
|
};
|
|
69
69
|
const assertCurrent=()=>{
|
|
70
|
-
history.
|
|
70
|
+
// #656: one history pass per check, after the reads it brackets; the trailing pass covers the whole window.
|
|
71
|
+
if(key(active(home))!==bindingKey||fileStamp(home)!==initialStamp)fail();
|
|
71
72
|
if(initial&&readInitialSyncPlacementWriterLocator(home).seal!==initial.seal)fail();
|
|
72
73
|
if(history.sequence||history.window)requireWriterRenewalHomeFloor(home);
|
|
73
74
|
anchors();history.assertCurrent();
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { metadataReader, sameMetadataStamp } from "./profile-marker-cache.ts";
|
|
2
|
+
import { provePlacementShards, readActivePlacementBinding, type ActivePlacementBinding } from "./sync-placement-active.ts";
|
|
2
3
|
import { readEffectiveRealmInventory, type EffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
|
|
3
4
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
5
|
import { tmpdir } from "node:os";
|
|
@@ -11,7 +12,7 @@ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type Bi
|
|
|
11
12
|
import { join } from "node:path";
|
|
12
13
|
import { LOCAL_METADATA_MAX_BYTES, legacyProfileMarkerShape, type BoundProfile } from "./generation.ts";
|
|
13
14
|
import { legacyShardMarkerShape } from "./shard.ts";
|
|
14
|
-
import { PLACEMENT_FORMAT, PLACEMENT_PROFILE_SCHEMA, PLACEMENT_SHARDS_SCHEMA
|
|
15
|
+
import { PLACEMENT_FORMAT, PLACEMENT_PROFILE_SCHEMA, PLACEMENT_SHARDS_SCHEMA } from "./sync-placement-format.ts";
|
|
15
16
|
import { PLACEMENT_ACTIVATION_INTENT } from "./sync-placement-activation-path.ts";
|
|
16
17
|
import { profileLockRefusal, rememberProfileLockError } from "./profile-lock-diagnostic.ts";
|
|
17
18
|
|
|
@@ -66,8 +67,7 @@ export class SyncPlacementRuntimeError extends Error {
|
|
|
66
67
|
constructor(reason: string) { super(reason); this.name = "SyncPlacementRuntimeError"; this.code = reason === PLACEMENT_STAGE1_REFUSAL ? "sync_placement_not_enabled" : "sync_placement_unavailable";rememberProfileLockError(this,reason); }
|
|
67
68
|
}
|
|
68
69
|
class MarkerChanged extends Error {}
|
|
69
|
-
|
|
70
|
-
function readMarker(file: string): unknown | undefined {
|
|
70
|
+
function readMarkerUncached(file: string): { stamp: BigIntStats; value: unknown } | undefined {
|
|
71
71
|
for (let attempt = 0; attempt < 6; attempt++) {
|
|
72
72
|
let fd: number | undefined;
|
|
73
73
|
try {
|
|
@@ -76,20 +76,38 @@ function readMarker(file: string): unknown | undefined {
|
|
|
76
76
|
if (!before.isFile() || before.isSymbolicLink() || before.size > BigInt(LOCAL_METADATA_MAX_BYTES)) throw new SyncPlacementRuntimeError(PLACEMENT_MARKER_REFUSAL);
|
|
77
77
|
fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
78
78
|
const opened = fstatSync(fd, { bigint: true });
|
|
79
|
-
if (!
|
|
79
|
+
if (!sameMetadataStamp(before, opened)) throw new MarkerChanged();
|
|
80
80
|
const bytes = Buffer.alloc(Number(opened.size) + 1); let count = 0;
|
|
81
81
|
while (count < bytes.length) { const read = readSync(fd, bytes, count, bytes.length - count, count); if (!read) break; count += read; }
|
|
82
82
|
const after = fstatSync(fd, { bigint: true }), named = lstatSync(file, { bigint: true, throwIfNoEntry: false });
|
|
83
|
-
if (count !== Number(opened.size) || !
|
|
84
|
-
return JSON.parse(new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes.subarray(0, count)));
|
|
83
|
+
if (count !== Number(opened.size) || !sameMetadataStamp(opened, after) || !named || named.isSymbolicLink() || !sameMetadataStamp(opened, named)) throw new MarkerChanged();
|
|
84
|
+
return { stamp: named, value: JSON.parse(new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes.subarray(0, count))) as unknown };
|
|
85
85
|
} catch (error) { if (error instanceof MarkerChanged && attempt < 5) continue; throw new SyncPlacementRuntimeError(PLACEMENT_MARKER_REFUSAL); }
|
|
86
86
|
finally { if (fd !== undefined) closeSync(fd); }
|
|
87
87
|
}
|
|
88
88
|
throw new SyncPlacementRuntimeError(PLACEMENT_MARKER_REFUSAL);
|
|
89
89
|
}
|
|
90
|
-
|
|
90
|
+
const readMarker = metadataReader(readMarkerUncached);
|
|
91
|
+
/** The shard reader reuses only parsed v3 markers. Legacy and malformed values keep their existing reader. */
|
|
92
|
+
export function readPlacementV3Marker(file: string): Record<string, unknown> | undefined {
|
|
93
|
+
let value: unknown;
|
|
94
|
+
try { value = readMarker(file); } catch { return undefined; }
|
|
95
|
+
const format = schema(value);
|
|
96
|
+
return format === PLACEMENT_PROFILE_SCHEMA || format === PLACEMENT_SHARDS_SCHEMA ? value as Record<string, unknown> : undefined;
|
|
97
|
+
}
|
|
98
|
+
function runtimeMarkers(home: string): { profile: unknown | undefined; shards: unknown | undefined } {
|
|
91
99
|
return { profile: readMarker(join(home, "profile.json")), shards: readMarker(join(home, "shards.json")) };
|
|
92
100
|
}
|
|
101
|
+
export function readPlacementRuntimeMarkers(home: string): { profile: unknown | undefined; shards: unknown | undefined } {
|
|
102
|
+
return structuredClone(runtimeMarkers(home));
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* #656, internal fence reads only: the reader's own frozen snapshots, uncloned, so the shard-proof and binding WeakMaps hit while the
|
|
106
|
+
* markers are unchanged. Callers never mutate or return them; anything handed outward still takes readPlacementRuntimeMarkers.
|
|
107
|
+
*/
|
|
108
|
+
export function readPlacementRuntimeMarkerSnapshots(home: string): { profile: unknown | undefined; shards: unknown | undefined } {
|
|
109
|
+
return runtimeMarkers(home);
|
|
110
|
+
}
|
|
93
111
|
/** #551 AC2: whether a home is provably a placement home, provably not one, or unprovable from its own markers. */
|
|
94
112
|
export type PlacementMarkerState = "placement" | "unverified" | "not placement";
|
|
95
113
|
/**
|
|
@@ -99,7 +117,7 @@ export type PlacementMarkerState = "placement" | "unverified" | "not placement";
|
|
|
99
117
|
*/
|
|
100
118
|
export function placementMarkerState(home: string): PlacementMarkerState {
|
|
101
119
|
let markers: { profile: unknown | undefined; shards: unknown | undefined };
|
|
102
|
-
try { markers =
|
|
120
|
+
try { markers = runtimeMarkers(home); } catch { return "unverified"; }
|
|
103
121
|
if (schema(markers.profile) === PLACEMENT_PROFILE_SCHEMA || schema(markers.shards) === PLACEMENT_SHARDS_SCHEMA)
|
|
104
122
|
return (markers.profile as { publicationFormat?: unknown } | undefined)?.publicationFormat === PLACEMENT_FORMAT ? "placement" : "unverified";
|
|
105
123
|
// A missing marker or a recognizable legacy one is a home that never activated placement sync; any other shape is malformed.
|
|
@@ -120,7 +138,7 @@ function plainMarker(value: unknown): boolean {
|
|
|
120
138
|
export function placementMarkerRefusal(profile: unknown, shards: unknown): string | undefined {
|
|
121
139
|
if (!plainMarker(profile) || !plainMarker(shards)) return PLACEMENT_MARKER_REFUSAL;
|
|
122
140
|
if (schema(profile) === PLACEMENT_PROFILE_SCHEMA || schema(shards) === PLACEMENT_SHARDS_SCHEMA) {
|
|
123
|
-
try {
|
|
141
|
+
try { provePlacementShards(shards, profile); }
|
|
124
142
|
catch { return PLACEMENT_MARKER_REFUSAL; }
|
|
125
143
|
return PLACEMENT_STAGE1_REFUSAL;
|
|
126
144
|
}
|
|
@@ -158,7 +176,7 @@ function placementFencePresent(home: string): boolean {
|
|
|
158
176
|
* The v3 publication coordinator separately proves the complete journal, selected sources and policy. */
|
|
159
177
|
export function placementRuntimeRefusal(home: string, bound?: Pick<BoundProfile,"kind"|"sharded"|"generation"|"publicationFormat"|"placementHead">): string | undefined {
|
|
160
178
|
if (doctorScratchBinding(home)) return undefined;
|
|
161
|
-
try { const fenced = placementFencePresent(home), pending = placementActivationPending(home), markers =
|
|
179
|
+
try { const fenced = placementFencePresent(home), pending = placementActivationPending(home), markers = runtimeMarkers(home);
|
|
162
180
|
const refusal = placementMarkerRefusal(markers.profile, markers.shards);
|
|
163
181
|
if (refusal === PLACEMENT_STAGE1_REFUSAL) {
|
|
164
182
|
const active=readActivePlacementBinding(home,markers.profile,markers.shards);
|
|
@@ -14,7 +14,7 @@ import { existsSync, lstatSync } from "node:fs";
|
|
|
14
14
|
import { join } from "node:path";
|
|
15
15
|
import { readActivePlacementBinding } from "./sync-placement-active.ts";
|
|
16
16
|
import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
|
|
17
|
-
import { readPlacementJournal } from "./sync-placement-journal-storage.ts";
|
|
17
|
+
import { readPlacementJournal, releasePlacementStorageCaches } from "./sync-placement-journal-storage.ts";
|
|
18
18
|
import { PLACEMENT_CHECKPOINT_PENDING_MESSAGE, placementCheckpointPending } from "./sync-placement-checkpoint-storage.ts";
|
|
19
19
|
import { readPlacementPublication } from "./sync-placement-publication-storage.ts";
|
|
20
20
|
import { readEffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
|
|
@@ -22,7 +22,8 @@ import { isLocalKey, localKeyOptInMessage, readShardDescriptor, shardDir, userSh
|
|
|
22
22
|
import { projectState } from "./lifecycle.ts";
|
|
23
23
|
import { SyncPlacementJournalError, type PlacementRealm } from "./sync-placement-journal-format.ts";
|
|
24
24
|
import type { SyncOptions, SyncResult } from "./sync.ts";
|
|
25
|
-
import { bindPlacementAdvertisement } from "./sync-placement-advertisement.ts";
|
|
25
|
+
import { bindPlacementAdvertisement, releasePlacementRun } from "./sync-placement-advertisement.ts";
|
|
26
|
+
import { PLACEMENT_RETAINED_STOP_MESSAGE, placementStoppedMessage } from "./sync-placement-refusal.ts";
|
|
26
27
|
import type { MemoryStore } from "./store.ts";
|
|
27
28
|
|
|
28
29
|
const digest = (value: string) => createHash("sha256").update(value).digest("hex");
|
|
@@ -101,7 +102,12 @@ function journalRefusal(error: unknown): (SyncResult & { placementRealms: Placem
|
|
|
101
102
|
|
|
102
103
|
export async function syncPlacementInventory(home: string, callerOpts: SyncOptions, ports: PlacementInventoryPorts): Promise<SyncResult & { placementRealms: PlacementRealmResult[] }> {
|
|
103
104
|
// #626: one remote advertisement per run, shared by its publications (never one a caller passed in).
|
|
105
|
+
// #656: the same scope keeps the visibility answer and the placement storage memos across batches; both end here, on every path.
|
|
104
106
|
const opts: SyncOptions = bindPlacementAdvertisement({ ...callerOpts });
|
|
107
|
+
try { return await runPlacementInventory(home, opts, ports); }
|
|
108
|
+
finally { releasePlacementRun(opts); releasePlacementStorageCaches(); }
|
|
109
|
+
}
|
|
110
|
+
async function runPlacementInventory(home: string, opts: SyncOptions, ports: PlacementInventoryPorts): Promise<SyncResult & { placementRealms: PlacementRealmResult[] }> {
|
|
105
111
|
let local: InventoryRealm[], missing: string[], inactive: string[], retained: string[] | undefined;
|
|
106
112
|
try {
|
|
107
113
|
// #288 step 3: a started checkpoint pauses every placement effect before any journal read, with its own cause and next step.
|
|
@@ -149,7 +155,15 @@ export async function syncPlacementInventory(home: string, callerOpts: SyncOptio
|
|
|
149
155
|
for (const [index, batch] of batches.entries()) {
|
|
150
156
|
if (!batch.length) continue;
|
|
151
157
|
if (stopped) { for (const realm of batch) realms.push({ realm: label(realm), outcome: "not-run" }); continue; }
|
|
152
|
-
if (opts.signal?.aborted) {
|
|
158
|
+
if (opts.signal?.aborted) {
|
|
159
|
+
// #657: the first batch of a resumed run is a retained attempt that may already have published, so it stays unknown.
|
|
160
|
+
const retainedFirst = index === 0 && resumed !== undefined;
|
|
161
|
+
stopped = retainedFirst
|
|
162
|
+
? { ok: false, pushed: false, entries: 0, error: PLACEMENT_RETAINED_STOP_MESSAGE, failure: { cause: "stopped" }, placementPublication: { outcome: "unknown", withheld: 0, exported: 0, policyCeiling: "last-positive-check-before-in-flight-push" } }
|
|
163
|
+
: { ok: false, pushed: false, entries: 0, error: placementStoppedMessage(results.length ? "between publications" : "start of the run"), failure: { cause: "stopped" } };
|
|
164
|
+
for (const realm of batch) realms.push({ realm: label(realm), outcome: retainedFirst ? "unknown" : "not-run", ...(retainedFirst ? { publication: index + 1 } : {}) });
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
153
167
|
let result = await attempt(batch);
|
|
154
168
|
// #578 Q2: by here the publication has returned, so its transport released every mutation and sync lock it took
|
|
155
169
|
// (sync-placement-transport.ts finally) and `attempt` closed the stores it opened. The checkpoint fence takes those
|
|
@@ -161,7 +175,9 @@ export async function syncPlacementInventory(home: string, callerOpts: SyncOptio
|
|
|
161
175
|
else result = { ...result, error: [result.error, ran.message].filter(Boolean).join(" "), failure: { cause: "checkpoint-refused" } };
|
|
162
176
|
}
|
|
163
177
|
results.push(result);
|
|
164
|
-
|
|
178
|
+
// #657: a batch stopped before any attempt existed did not run; "not-run" keeps the sidecar readable by N-1 status readers.
|
|
179
|
+
const outcome: PlacementRealmOutcome = result.ok ? result.placementPublication?.outcome ?? "not-needed" : result.placementPublication?.outcome === "unknown" ? "unknown"
|
|
180
|
+
: result.failure?.cause === "stopped" ? "not-run" : "failed";
|
|
165
181
|
for (const realm of batch) realms.push({ realm: label(realm), outcome, publication: index + 1 });
|
|
166
182
|
if (!result.ok) stopped = result;
|
|
167
183
|
else completed++;
|