instar 1.3.515 → 1.3.516
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/HybridLogicalClock.d.ts +200 -0
- package/dist/core/HybridLogicalClock.d.ts.map +1 -0
- package/dist/core/HybridLogicalClock.js +288 -0
- package/dist/core/HybridLogicalClock.js.map +1 -0
- package/package.json +1 -1
- package/src/data/builtin-manifest.json +2 -2
- package/upgrades/1.3.516.md +55 -0
- package/upgrades/side-effects/replicated-store-foundation-hlc-primitive.md +98 -0
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HybridLogicalClock — a pure, dependency-injected total-order clock (WS2
|
|
3
|
+
* replicated-store foundation, Component 1).
|
|
4
|
+
*
|
|
5
|
+
* Spec: docs/specs/multi-machine-replicated-store-foundation.md §3 (the whole
|
|
6
|
+
* section), §10.2 (the maxDriftMs clamp invariant), §13 build order step 1,
|
|
7
|
+
* §15 risk-5/risk-6 (maxDriftMs sourcing — BLOCKER-5).
|
|
8
|
+
*
|
|
9
|
+
* HLC combines physical wall-clock time (so order tracks real time and is
|
|
10
|
+
* human-readable) with a logical counter (so causality survives clock skew and
|
|
11
|
+
* equal-millisecond ties). It is the load-bearing total order WS2 merges rely
|
|
12
|
+
* on: "merges order by HLC, never raw wall-clock" (master spec line 229).
|
|
13
|
+
*
|
|
14
|
+
* Design contract (§3.6 Purity + testability):
|
|
15
|
+
* - Imports NOTHING but its injected seams. No `fs`, no `Date` (only via the
|
|
16
|
+
* injected `now`), no network. Every operation is a pure function of
|
|
17
|
+
* `(last, input, now())`.
|
|
18
|
+
* - The clock (`now`), the `node` id, and persistence (`persist.load/save`)
|
|
19
|
+
* are constructor deps, so every dangerous property — monotonicity, the
|
|
20
|
+
* skew bound, restart-monotonicity — is unit-testable with in-memory fakes.
|
|
21
|
+
*
|
|
22
|
+
* Posture (§11): machine-local-by-design. Each machine has its own clock; the
|
|
23
|
+
* clocks CONVERGE via receive() but are never shared state. The HLC TIMESTAMPS
|
|
24
|
+
* are replicated (one per record, §4); the clock OBJECT is not.
|
|
25
|
+
*/
|
|
26
|
+
/**
|
|
27
|
+
* An HLC value. Carried on each replicated record as the `hlc` field (§4).
|
|
28
|
+
* The triple `(physical, logical, node)` is a globally-unique, totally-ordered
|
|
29
|
+
* stamp (node ids are unique across the pool, so distinct-machine stamps are
|
|
30
|
+
* never "equal" in sort position — §3.3).
|
|
31
|
+
*/
|
|
32
|
+
export interface HlcTimestamp {
|
|
33
|
+
/** Physical time in ms since epoch (the LARGEST seen, not necessarily now). */
|
|
34
|
+
physical: number;
|
|
35
|
+
/** Logical counter — breaks ties at equal physical and advances under skew. */
|
|
36
|
+
logical: number;
|
|
37
|
+
/** Node (machine) id of the clock that STAMPED this timestamp. The
|
|
38
|
+
* tie-breaker of LAST resort and the carrier of the origin tag (§7). */
|
|
39
|
+
node: string;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* The persistence seam (§3.5). Injected so crash-safety is unit-testable with
|
|
43
|
+
* an in-memory fake. `save` is expected to be ATOMIC (temp + rename) in the
|
|
44
|
+
* real implementation; the clock calls it on EVERY advance.
|
|
45
|
+
*/
|
|
46
|
+
export interface HlcPersistence {
|
|
47
|
+
/** Load the last durable stamp, or null if fresh (first boot). */
|
|
48
|
+
load(): HlcTimestamp | null;
|
|
49
|
+
/** Persist the last issued stamp atomically. Called on every advance. */
|
|
50
|
+
save(t: HlcTimestamp): void;
|
|
51
|
+
}
|
|
52
|
+
/** Constructor config (§3.2). */
|
|
53
|
+
export interface HybridLogicalClockConfig {
|
|
54
|
+
/** This machine's id — the `node` stamped on every timestamp this clock issues. */
|
|
55
|
+
node: string;
|
|
56
|
+
/** INJECTED physical-time source (ms since epoch). Tests pass a fake clock. */
|
|
57
|
+
now: () => number;
|
|
58
|
+
/**
|
|
59
|
+
* FIXED bounded-drift ceiling (§3.4, BLOCKER-5). Default 5 minutes, CLAMPED
|
|
60
|
+
* to [60s, 15min]. NOT derived from any "measured pool skew" — no such numeric
|
|
61
|
+
* quantity exists today (ClockSkewStatus is a 3-value categorical enum).
|
|
62
|
+
*/
|
|
63
|
+
maxDriftMs?: number;
|
|
64
|
+
/** Persistence seam (§3.5). Omitted ⇒ the clock keeps `last` only in memory. */
|
|
65
|
+
persist?: HlcPersistence;
|
|
66
|
+
/**
|
|
67
|
+
* Optional structured logger for the at-most-once breadcrumbs the spec
|
|
68
|
+
* mandates (a regressed-wall-clock-on-load note, §3.5; a clamp note). Defaults
|
|
69
|
+
* to a no-op so the primitive stays import-free.
|
|
70
|
+
*/
|
|
71
|
+
log?: (event: string, detail: Record<string, unknown>) => void;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* A rejected receive (§3.4). Returned (never thrown into the hot path silently)
|
|
75
|
+
* when a remote timestamp exceeds the pool-relative reference by more than the
|
|
76
|
+
* clamped maxDriftMs. The local clock is NOT advanced and the caller MUST
|
|
77
|
+
* quarantine the record (§5, failure-class `skew-suspicious`).
|
|
78
|
+
*/
|
|
79
|
+
export interface SkewRejection {
|
|
80
|
+
rejected: true;
|
|
81
|
+
reason: 'skew-ahead';
|
|
82
|
+
/** The remote timestamp that was rejected. */
|
|
83
|
+
remote: HlcTimestamp;
|
|
84
|
+
/** The pool-relative reference R the remote was measured against. */
|
|
85
|
+
reference: number;
|
|
86
|
+
/** The clamped drift ceiling that R + ceiling was exceeded by. */
|
|
87
|
+
maxDriftMs: number;
|
|
88
|
+
}
|
|
89
|
+
/** The result of receive(): either the merged stamp, or a typed rejection. */
|
|
90
|
+
export type ReceiveResult = {
|
|
91
|
+
rejected: false;
|
|
92
|
+
hlc: HlcTimestamp;
|
|
93
|
+
} | SkewRejection;
|
|
94
|
+
/** Options for a single receive() call (§3.4 pool-relative reference). */
|
|
95
|
+
export interface ReceiveOptions {
|
|
96
|
+
/**
|
|
97
|
+
* An OBSERVED pool-relative physical-time floor (e.g. the observed-pool-median
|
|
98
|
+
* physical time carried in the capacity heartbeat, §3.4). The drift check
|
|
99
|
+
* references `R = max(last.physical, poolReference ?? 0)`, NOT the bare local
|
|
100
|
+
* `now()` — so a receiver whose own NTP is behind does not falsely reject
|
|
101
|
+
* ahead-but-honest peers. Omitted ⇒ R = last.physical.
|
|
102
|
+
*/
|
|
103
|
+
poolReference?: number;
|
|
104
|
+
}
|
|
105
|
+
/** The default bounded-drift ceiling: 5 minutes (§3.4). */
|
|
106
|
+
export declare const DEFAULT_MAX_DRIFT_MS: number;
|
|
107
|
+
/** The floor of the maxDriftMs clamp (§3.4 / §10.2): 60 seconds. */
|
|
108
|
+
export declare const MIN_MAX_DRIFT_MS: number;
|
|
109
|
+
/** The ceiling of the maxDriftMs clamp (§3.4 / §10.2): 15 minutes. */
|
|
110
|
+
export declare const MAX_MAX_DRIFT_MS: number;
|
|
111
|
+
/**
|
|
112
|
+
* Clamp a configured maxDriftMs to the [60s, 15min] window (§3.4, §10.2).
|
|
113
|
+
*
|
|
114
|
+
* This is the helper `validateStateSyncInvariants` (§10.2) uses for the
|
|
115
|
+
* `maxDriftMs` knob: a value below the floor would start rejecting ordinary NTP
|
|
116
|
+
* jitter; a value above the ceiling would defeat the fast-clock defense. The
|
|
117
|
+
* spec's §10.2 invariant REJECTS an out-of-range value at config resolution;
|
|
118
|
+
* this clamp helper is the in-clock guard so the primitive is correct even if a
|
|
119
|
+
* caller hands it a raw value. A non-finite/undefined input falls back to the
|
|
120
|
+
* default.
|
|
121
|
+
*/
|
|
122
|
+
export declare function clampMaxDriftMs(value: number | undefined): number;
|
|
123
|
+
/** Type guard: is a receive() result a skew rejection? */
|
|
124
|
+
export declare function isSkewRejection(r: ReceiveResult): r is SkewRejection;
|
|
125
|
+
/**
|
|
126
|
+
* Serialize an HlcTimestamp to the compact wire/disk form (§3.5).
|
|
127
|
+
*
|
|
128
|
+
* Default form is a 3-field JSON object (carried on each record as `hlc`). The
|
|
129
|
+
* string form `"<physical>:<logical>:<node>"` is for embedding in a key — and
|
|
130
|
+
* because a node id MAY contain a `:`, the node is the LAST segment and parse
|
|
131
|
+
* splits on the FIRST TWO colons only (physical and logical are numeric and
|
|
132
|
+
* colon-free), so the round-trip is lossless for any node id.
|
|
133
|
+
*/
|
|
134
|
+
export declare function serializeHlc(t: HlcTimestamp): string;
|
|
135
|
+
/** Serialize to the compact key-string form `"<physical>:<logical>:<node>"`. */
|
|
136
|
+
export declare function serializeHlcKey(t: HlcTimestamp): string;
|
|
137
|
+
/**
|
|
138
|
+
* Parse the JSON object form (§3.5). Throws on malformed input — a record whose
|
|
139
|
+
* `hlc` cannot be parsed is a schema reject upstream, never a silent default.
|
|
140
|
+
*/
|
|
141
|
+
export declare function parseHlc(input: string): HlcTimestamp;
|
|
142
|
+
/** Parse the key-string form `"<physical>:<logical>:<node>"` (§3.5). */
|
|
143
|
+
export declare function parseHlcKey(input: string): HlcTimestamp;
|
|
144
|
+
/**
|
|
145
|
+
* Validate + narrow an unknown value to an HlcTimestamp. The single chokepoint
|
|
146
|
+
* both parsers and receive() funnel untrusted input through (§3.5): physical and
|
|
147
|
+
* logical must be finite non-negative integers; node must be a non-empty string.
|
|
148
|
+
*/
|
|
149
|
+
export declare function coerceHlc(raw: unknown): HlcTimestamp;
|
|
150
|
+
export declare class HybridLogicalClock {
|
|
151
|
+
private readonly node;
|
|
152
|
+
private readonly now;
|
|
153
|
+
private readonly maxDriftMs;
|
|
154
|
+
private readonly persist?;
|
|
155
|
+
private readonly log;
|
|
156
|
+
/** The largest stamp this clock has issued (the floor for every advance). */
|
|
157
|
+
private last;
|
|
158
|
+
constructor(config: HybridLogicalClockConfig);
|
|
159
|
+
/** The largest stamp issued so far (a copy — never the internal reference). */
|
|
160
|
+
current(): HlcTimestamp;
|
|
161
|
+
/** The clamped drift ceiling this clock enforces (§3.4). */
|
|
162
|
+
getMaxDriftMs(): number;
|
|
163
|
+
/**
|
|
164
|
+
* tick() — local-event advance (§3.2.1). Called when THIS machine AUTHORS a
|
|
165
|
+
* record. `pt = max(now(), last.physical)`; `logical = (pt === last.physical)
|
|
166
|
+
* ? last.logical + 1 : 0`. Persists and returns the new stamp.
|
|
167
|
+
*
|
|
168
|
+
* Monotonicity guarantee: the returned stamp is strictly greater (by compare)
|
|
169
|
+
* than every previous tick()/receive() result on this clock — even if the wall
|
|
170
|
+
* clock jumps backward, because physical never regresses.
|
|
171
|
+
*/
|
|
172
|
+
tick(): HlcTimestamp;
|
|
173
|
+
/**
|
|
174
|
+
* receive(remote) — merge an inbound peer stamp (§3.2.2 + §3.4). Runs the
|
|
175
|
+
* bounded-drift check FIRST; on rejection the local clock does NOT advance and
|
|
176
|
+
* a typed SkewRejection is returned (the caller quarantines the record).
|
|
177
|
+
*
|
|
178
|
+
* Otherwise the canonical HLC merge (Kulkarni et al.):
|
|
179
|
+
* pt = max(now(), last.physical, remote.physical)
|
|
180
|
+
* - pt === last.physical === remote.physical → max(last.logical, remote.logical)+1
|
|
181
|
+
* - pt === last.physical → last.logical + 1
|
|
182
|
+
* - pt === remote.physical → remote.logical + 1
|
|
183
|
+
* - else → 0
|
|
184
|
+
*
|
|
185
|
+
* Monotonic vs BOTH local and remote: the receiving clock can never go
|
|
186
|
+
* backward, and a received record's causal position is preserved.
|
|
187
|
+
*/
|
|
188
|
+
receive(remote: HlcTimestamp, options?: ReceiveOptions): ReceiveResult;
|
|
189
|
+
/** Advance `last` and persist atomically (§3.5 — persist on EVERY advance). */
|
|
190
|
+
private commit;
|
|
191
|
+
/**
|
|
192
|
+
* compare(a, b) — the STRICT TOTAL ORDER (§3.3, static + pure). Compares
|
|
193
|
+
* physical, then logical, then node id (lexicographic). Returns 0 ONLY for an
|
|
194
|
+
* identical triple — because node ids are unique, two distinct-machine stamps
|
|
195
|
+
* are NEVER "equal" in sort position. This totality is what makes a
|
|
196
|
+
* deterministic merge across the pool possible.
|
|
197
|
+
*/
|
|
198
|
+
static compare(a: HlcTimestamp, b: HlcTimestamp): -1 | 0 | 1;
|
|
199
|
+
}
|
|
200
|
+
//# sourceMappingURL=HybridLogicalClock.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"HybridLogicalClock.d.ts","sourceRoot":"","sources":["../../src/core/HybridLogicalClock.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH;;;;;GAKG;AACH,MAAM,WAAW,YAAY;IAC3B,+EAA+E;IAC/E,QAAQ,EAAE,MAAM,CAAC;IACjB,+EAA+E;IAC/E,OAAO,EAAE,MAAM,CAAC;IAChB;6EACyE;IACzE,IAAI,EAAE,MAAM,CAAC;CACd;AAED;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B,kEAAkE;IAClE,IAAI,IAAI,YAAY,GAAG,IAAI,CAAC;IAC5B,yEAAyE;IACzE,IAAI,CAAC,CAAC,EAAE,YAAY,GAAG,IAAI,CAAC;CAC7B;AAED,iCAAiC;AACjC,MAAM,WAAW,wBAAwB;IACvC,mFAAmF;IACnF,IAAI,EAAE,MAAM,CAAC;IACb,+EAA+E;IAC/E,GAAG,EAAE,MAAM,MAAM,CAAC;IAClB;;;;OAIG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,gFAAgF;IAChF,OAAO,CAAC,EAAE,cAAc,CAAC;IACzB;;;;OAIG;IACH,GAAG,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;CAChE;AAED;;;;;GAKG;AACH,MAAM,WAAW,aAAa;IAC5B,QAAQ,EAAE,IAAI,CAAC;IACf,MAAM,EAAE,YAAY,CAAC;IACrB,8CAA8C;IAC9C,MAAM,EAAE,YAAY,CAAC;IACrB,qEAAqE;IACrE,SAAS,EAAE,MAAM,CAAC;IAClB,kEAAkE;IAClE,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,8EAA8E;AAC9E,MAAM,MAAM,aAAa,GACrB;IAAE,QAAQ,EAAE,KAAK,CAAC;IAAC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;IAC/E,OAAO,IAAI,YAAY;IAIvB,4DAA4D;IAC5D,aAAa,IAAI,MAAM;IAIvB;;;;;;;;OAQG;IACH,IAAI,IAAI,YAAY;IAQpB;;;;;;;;;;;;;;OAcG;IACH,OAAO,CAAC,MAAM,EAAE,YAAY,EAAE,OAAO,GAAE,cAAmB,GAAG,aAAa;IAkC1E,+EAA+E;IAC/E,OAAO,CAAC,MAAM;IAKd;;;;;;OAMG;IACH,MAAM,CAAC,OAAO,CAAC,CAAC,EAAE,YAAY,EAAE,CAAC,EAAE,YAAY,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC;CAM7D"}
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HybridLogicalClock — a pure, dependency-injected total-order clock (WS2
|
|
3
|
+
* replicated-store foundation, Component 1).
|
|
4
|
+
*
|
|
5
|
+
* Spec: docs/specs/multi-machine-replicated-store-foundation.md §3 (the whole
|
|
6
|
+
* section), §10.2 (the maxDriftMs clamp invariant), §13 build order step 1,
|
|
7
|
+
* §15 risk-5/risk-6 (maxDriftMs sourcing — BLOCKER-5).
|
|
8
|
+
*
|
|
9
|
+
* HLC combines physical wall-clock time (so order tracks real time and is
|
|
10
|
+
* human-readable) with a logical counter (so causality survives clock skew and
|
|
11
|
+
* equal-millisecond ties). It is the load-bearing total order WS2 merges rely
|
|
12
|
+
* on: "merges order by HLC, never raw wall-clock" (master spec line 229).
|
|
13
|
+
*
|
|
14
|
+
* Design contract (§3.6 Purity + testability):
|
|
15
|
+
* - Imports NOTHING but its injected seams. No `fs`, no `Date` (only via the
|
|
16
|
+
* injected `now`), no network. Every operation is a pure function of
|
|
17
|
+
* `(last, input, now())`.
|
|
18
|
+
* - The clock (`now`), the `node` id, and persistence (`persist.load/save`)
|
|
19
|
+
* are constructor deps, so every dangerous property — monotonicity, the
|
|
20
|
+
* skew bound, restart-monotonicity — is unit-testable with in-memory fakes.
|
|
21
|
+
*
|
|
22
|
+
* Posture (§11): machine-local-by-design. Each machine has its own clock; the
|
|
23
|
+
* clocks CONVERGE via receive() but are never shared state. The HLC TIMESTAMPS
|
|
24
|
+
* are replicated (one per record, §4); the clock OBJECT is not.
|
|
25
|
+
*/
|
|
26
|
+
/** The default bounded-drift ceiling: 5 minutes (§3.4). */
|
|
27
|
+
export const DEFAULT_MAX_DRIFT_MS = 5 * 60 * 1000;
|
|
28
|
+
/** The floor of the maxDriftMs clamp (§3.4 / §10.2): 60 seconds. */
|
|
29
|
+
export const MIN_MAX_DRIFT_MS = 60 * 1000;
|
|
30
|
+
/** The ceiling of the maxDriftMs clamp (§3.4 / §10.2): 15 minutes. */
|
|
31
|
+
export const MAX_MAX_DRIFT_MS = 15 * 60 * 1000;
|
|
32
|
+
/**
|
|
33
|
+
* Clamp a configured maxDriftMs to the [60s, 15min] window (§3.4, §10.2).
|
|
34
|
+
*
|
|
35
|
+
* This is the helper `validateStateSyncInvariants` (§10.2) uses for the
|
|
36
|
+
* `maxDriftMs` knob: a value below the floor would start rejecting ordinary NTP
|
|
37
|
+
* jitter; a value above the ceiling would defeat the fast-clock defense. The
|
|
38
|
+
* spec's §10.2 invariant REJECTS an out-of-range value at config resolution;
|
|
39
|
+
* this clamp helper is the in-clock guard so the primitive is correct even if a
|
|
40
|
+
* caller hands it a raw value. A non-finite/undefined input falls back to the
|
|
41
|
+
* default.
|
|
42
|
+
*/
|
|
43
|
+
export function clampMaxDriftMs(value) {
|
|
44
|
+
if (value === undefined || !Number.isFinite(value))
|
|
45
|
+
return DEFAULT_MAX_DRIFT_MS;
|
|
46
|
+
if (value < MIN_MAX_DRIFT_MS)
|
|
47
|
+
return MIN_MAX_DRIFT_MS;
|
|
48
|
+
if (value > MAX_MAX_DRIFT_MS)
|
|
49
|
+
return MAX_MAX_DRIFT_MS;
|
|
50
|
+
return value;
|
|
51
|
+
}
|
|
52
|
+
/** Type guard: is a receive() result a skew rejection? */
|
|
53
|
+
export function isSkewRejection(r) {
|
|
54
|
+
return r.rejected === true;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Serialize an HlcTimestamp to the compact wire/disk form (§3.5).
|
|
58
|
+
*
|
|
59
|
+
* Default form is a 3-field JSON object (carried on each record as `hlc`). The
|
|
60
|
+
* string form `"<physical>:<logical>:<node>"` is for embedding in a key — and
|
|
61
|
+
* because a node id MAY contain a `:`, the node is the LAST segment and parse
|
|
62
|
+
* splits on the FIRST TWO colons only (physical and logical are numeric and
|
|
63
|
+
* colon-free), so the round-trip is lossless for any node id.
|
|
64
|
+
*/
|
|
65
|
+
export function serializeHlc(t) {
|
|
66
|
+
return JSON.stringify({ physical: t.physical, logical: t.logical, node: t.node });
|
|
67
|
+
}
|
|
68
|
+
/** Serialize to the compact key-string form `"<physical>:<logical>:<node>"`. */
|
|
69
|
+
export function serializeHlcKey(t) {
|
|
70
|
+
return `${t.physical}:${t.logical}:${t.node}`;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Parse the JSON object form (§3.5). Throws on malformed input — a record whose
|
|
74
|
+
* `hlc` cannot be parsed is a schema reject upstream, never a silent default.
|
|
75
|
+
*/
|
|
76
|
+
export function parseHlc(input) {
|
|
77
|
+
let raw;
|
|
78
|
+
try {
|
|
79
|
+
raw = JSON.parse(input);
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
throw new Error(`parseHlc: not valid JSON: ${truncateForError(input)}`);
|
|
83
|
+
}
|
|
84
|
+
return coerceHlc(raw);
|
|
85
|
+
}
|
|
86
|
+
/** Parse the key-string form `"<physical>:<logical>:<node>"` (§3.5). */
|
|
87
|
+
export function parseHlcKey(input) {
|
|
88
|
+
if (typeof input !== 'string') {
|
|
89
|
+
throw new Error('parseHlcKey: input is not a string');
|
|
90
|
+
}
|
|
91
|
+
// Split on the FIRST TWO colons only — the node id may contain colons.
|
|
92
|
+
const firstColon = input.indexOf(':');
|
|
93
|
+
const secondColon = firstColon < 0 ? -1 : input.indexOf(':', firstColon + 1);
|
|
94
|
+
if (firstColon < 0 || secondColon < 0) {
|
|
95
|
+
throw new Error(`parseHlcKey: expected "<physical>:<logical>:<node>", got: ${truncateForError(input)}`);
|
|
96
|
+
}
|
|
97
|
+
const physical = Number(input.slice(0, firstColon));
|
|
98
|
+
const logical = Number(input.slice(firstColon + 1, secondColon));
|
|
99
|
+
const node = input.slice(secondColon + 1);
|
|
100
|
+
return coerceHlc({ physical, logical, node });
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Validate + narrow an unknown value to an HlcTimestamp. The single chokepoint
|
|
104
|
+
* both parsers and receive() funnel untrusted input through (§3.5): physical and
|
|
105
|
+
* logical must be finite non-negative integers; node must be a non-empty string.
|
|
106
|
+
*/
|
|
107
|
+
export function coerceHlc(raw) {
|
|
108
|
+
if (typeof raw !== 'object' || raw === null) {
|
|
109
|
+
throw new Error('coerceHlc: not an object');
|
|
110
|
+
}
|
|
111
|
+
const obj = raw;
|
|
112
|
+
const { physical, logical, node } = obj;
|
|
113
|
+
if (typeof physical !== 'number' || !Number.isInteger(physical) || physical < 0) {
|
|
114
|
+
throw new Error(`coerceHlc: physical must be a non-negative integer, got ${String(physical)}`);
|
|
115
|
+
}
|
|
116
|
+
if (typeof logical !== 'number' || !Number.isInteger(logical) || logical < 0) {
|
|
117
|
+
throw new Error(`coerceHlc: logical must be a non-negative integer, got ${String(logical)}`);
|
|
118
|
+
}
|
|
119
|
+
if (typeof node !== 'string' || node.length === 0) {
|
|
120
|
+
throw new Error('coerceHlc: node must be a non-empty string');
|
|
121
|
+
}
|
|
122
|
+
return { physical, logical, node };
|
|
123
|
+
}
|
|
124
|
+
function truncateForError(s) {
|
|
125
|
+
const str = String(s);
|
|
126
|
+
return str.length > 80 ? `${str.slice(0, 80)}…` : str;
|
|
127
|
+
}
|
|
128
|
+
export class HybridLogicalClock {
|
|
129
|
+
node;
|
|
130
|
+
now;
|
|
131
|
+
maxDriftMs;
|
|
132
|
+
persist;
|
|
133
|
+
log;
|
|
134
|
+
/** The largest stamp this clock has issued (the floor for every advance). */
|
|
135
|
+
last;
|
|
136
|
+
constructor(config) {
|
|
137
|
+
if (typeof config.node !== 'string' || config.node.length === 0) {
|
|
138
|
+
throw new Error('HybridLogicalClock: node id must be a non-empty string');
|
|
139
|
+
}
|
|
140
|
+
this.node = config.node;
|
|
141
|
+
this.now = config.now;
|
|
142
|
+
this.maxDriftMs = clampMaxDriftMs(config.maxDriftMs);
|
|
143
|
+
this.persist = config.persist;
|
|
144
|
+
this.log = config.log ?? (() => { });
|
|
145
|
+
const loaded = this.persist?.load() ?? null;
|
|
146
|
+
// Validate the durable stamp through the same chokepoint a parser uses. A
|
|
147
|
+
// CORRUPT (non-null but malformed) load must NOT crash construction (§3.5,
|
|
148
|
+
// "Distrust Temporary Success"): a poisoned/partially-written persistence row
|
|
149
|
+
// would otherwise brick every consumer that boots the clock. We fail TOWARD a
|
|
150
|
+
// fresh-but-monotonic clock (monotonic relative to wall time) and log once,
|
|
151
|
+
// mirroring the missing-file (null) path — never throw out of the constructor.
|
|
152
|
+
let safeLoaded;
|
|
153
|
+
if (loaded === null) {
|
|
154
|
+
safeLoaded = null;
|
|
155
|
+
}
|
|
156
|
+
else {
|
|
157
|
+
try {
|
|
158
|
+
safeLoaded = coerceHlc(loaded);
|
|
159
|
+
}
|
|
160
|
+
catch (err) {
|
|
161
|
+
// @silent-fallback-ok: a corrupt persisted stamp degrades to the same
|
|
162
|
+
// fresh-but-monotonic clock as the missing-file path (safeLoaded=null
|
|
163
|
+
// below) rather than throwing out of construction — fail toward a usable
|
|
164
|
+
// clock, the safe direction. The discard is logged with context
|
|
165
|
+
// ('hlc-load-corrupt'); it is not a DegradationReporter case.
|
|
166
|
+
this.log('hlc-load-corrupt', {
|
|
167
|
+
error: err instanceof Error ? err.message : String(err),
|
|
168
|
+
});
|
|
169
|
+
safeLoaded = null;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
if (safeLoaded === null) {
|
|
173
|
+
// Fresh (no durable stamp, or a corrupt one we just discarded): start at
|
|
174
|
+
// { physical: now(), logical: 0, node } (§3.5).
|
|
175
|
+
this.last = { physical: this.now(), logical: 0, node: this.node };
|
|
176
|
+
}
|
|
177
|
+
else {
|
|
178
|
+
// Seed last from the durable stamp so a restart cannot rewind below it.
|
|
179
|
+
// We trust our OWN durable past over a regressed wall clock: if the loaded
|
|
180
|
+
// physical is ahead of now() by more than maxDriftMs (a backward wall-clock
|
|
181
|
+
// jump across the restart) we honor the durable floor and log once (§3.5).
|
|
182
|
+
this.last = { physical: safeLoaded.physical, logical: safeLoaded.logical, node: this.node };
|
|
183
|
+
const wall = this.now();
|
|
184
|
+
if (safeLoaded.physical - wall > this.maxDriftMs) {
|
|
185
|
+
this.log('hlc-load-ahead-of-wall', {
|
|
186
|
+
loadedPhysical: safeLoaded.physical,
|
|
187
|
+
wall,
|
|
188
|
+
maxDriftMs: this.maxDriftMs,
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
/** The largest stamp issued so far (a copy — never the internal reference). */
|
|
194
|
+
current() {
|
|
195
|
+
return { ...this.last };
|
|
196
|
+
}
|
|
197
|
+
/** The clamped drift ceiling this clock enforces (§3.4). */
|
|
198
|
+
getMaxDriftMs() {
|
|
199
|
+
return this.maxDriftMs;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* tick() — local-event advance (§3.2.1). Called when THIS machine AUTHORS a
|
|
203
|
+
* record. `pt = max(now(), last.physical)`; `logical = (pt === last.physical)
|
|
204
|
+
* ? last.logical + 1 : 0`. Persists and returns the new stamp.
|
|
205
|
+
*
|
|
206
|
+
* Monotonicity guarantee: the returned stamp is strictly greater (by compare)
|
|
207
|
+
* than every previous tick()/receive() result on this clock — even if the wall
|
|
208
|
+
* clock jumps backward, because physical never regresses.
|
|
209
|
+
*/
|
|
210
|
+
tick() {
|
|
211
|
+
const pt = Math.max(this.now(), this.last.physical);
|
|
212
|
+
const logical = pt === this.last.physical ? this.last.logical + 1 : 0;
|
|
213
|
+
const next = { physical: pt, logical, node: this.node };
|
|
214
|
+
this.commit(next);
|
|
215
|
+
return next;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* receive(remote) — merge an inbound peer stamp (§3.2.2 + §3.4). Runs the
|
|
219
|
+
* bounded-drift check FIRST; on rejection the local clock does NOT advance and
|
|
220
|
+
* a typed SkewRejection is returned (the caller quarantines the record).
|
|
221
|
+
*
|
|
222
|
+
* Otherwise the canonical HLC merge (Kulkarni et al.):
|
|
223
|
+
* pt = max(now(), last.physical, remote.physical)
|
|
224
|
+
* - pt === last.physical === remote.physical → max(last.logical, remote.logical)+1
|
|
225
|
+
* - pt === last.physical → last.logical + 1
|
|
226
|
+
* - pt === remote.physical → remote.logical + 1
|
|
227
|
+
* - else → 0
|
|
228
|
+
*
|
|
229
|
+
* Monotonic vs BOTH local and remote: the receiving clock can never go
|
|
230
|
+
* backward, and a received record's causal position is preserved.
|
|
231
|
+
*/
|
|
232
|
+
receive(remote, options = {}) {
|
|
233
|
+
// Narrow untrusted input through the same chokepoint a parser uses.
|
|
234
|
+
const r = coerceHlc(remote);
|
|
235
|
+
// §3.4 — POOL-RELATIVE reference, never the bare local now(). A slow receiver
|
|
236
|
+
// must not quarantine a legitimately-ahead peer just because its own clock lags.
|
|
237
|
+
const reference = Math.max(this.last.physical, options.poolReference ?? 0);
|
|
238
|
+
if (r.physical - reference > this.maxDriftMs) {
|
|
239
|
+
// Clock NOT advanced — a fast peer cannot drag us into the future.
|
|
240
|
+
return {
|
|
241
|
+
rejected: true,
|
|
242
|
+
reason: 'skew-ahead',
|
|
243
|
+
remote: r,
|
|
244
|
+
reference,
|
|
245
|
+
maxDriftMs: this.maxDriftMs,
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
const pt = Math.max(this.now(), this.last.physical, r.physical);
|
|
249
|
+
let logical;
|
|
250
|
+
if (pt === this.last.physical && pt === r.physical) {
|
|
251
|
+
logical = Math.max(this.last.logical, r.logical) + 1;
|
|
252
|
+
}
|
|
253
|
+
else if (pt === this.last.physical) {
|
|
254
|
+
logical = this.last.logical + 1;
|
|
255
|
+
}
|
|
256
|
+
else if (pt === r.physical) {
|
|
257
|
+
logical = r.logical + 1;
|
|
258
|
+
}
|
|
259
|
+
else {
|
|
260
|
+
logical = 0;
|
|
261
|
+
}
|
|
262
|
+
const next = { physical: pt, logical, node: this.node };
|
|
263
|
+
this.commit(next);
|
|
264
|
+
return { rejected: false, hlc: next };
|
|
265
|
+
}
|
|
266
|
+
/** Advance `last` and persist atomically (§3.5 — persist on EVERY advance). */
|
|
267
|
+
commit(next) {
|
|
268
|
+
this.last = next;
|
|
269
|
+
this.persist?.save({ ...next });
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* compare(a, b) — the STRICT TOTAL ORDER (§3.3, static + pure). Compares
|
|
273
|
+
* physical, then logical, then node id (lexicographic). Returns 0 ONLY for an
|
|
274
|
+
* identical triple — because node ids are unique, two distinct-machine stamps
|
|
275
|
+
* are NEVER "equal" in sort position. This totality is what makes a
|
|
276
|
+
* deterministic merge across the pool possible.
|
|
277
|
+
*/
|
|
278
|
+
static compare(a, b) {
|
|
279
|
+
if (a.physical !== b.physical)
|
|
280
|
+
return a.physical < b.physical ? -1 : 1;
|
|
281
|
+
if (a.logical !== b.logical)
|
|
282
|
+
return a.logical < b.logical ? -1 : 1;
|
|
283
|
+
if (a.node !== b.node)
|
|
284
|
+
return a.node < b.node ? -1 : 1;
|
|
285
|
+
return 0;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
//# sourceMappingURL=HybridLogicalClock.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"HybridLogicalClock.js","sourceRoot":"","sources":["../../src/core/HybridLogicalClock.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAsFH,2DAA2D;AAC3D,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,GA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AAC;CACF"}
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "./builtin-manifest.schema.json",
|
|
3
3
|
"schemaVersion": 1,
|
|
4
|
-
"generatedAt": "2026-06-13T07:
|
|
5
|
-
"instarVersion": "1.3.
|
|
4
|
+
"generatedAt": "2026-06-13T07:45:14.251Z",
|
|
5
|
+
"instarVersion": "1.3.516",
|
|
6
6
|
"entryCount": 201,
|
|
7
7
|
"entries": {
|
|
8
8
|
"hook:session-start": {
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# Upgrade Guide — vNEXT
|
|
2
|
+
|
|
3
|
+
<!-- assembled-by: assemble-next-md -->
|
|
4
|
+
<!-- bump: patch -->
|
|
5
|
+
|
|
6
|
+
## What Changed
|
|
7
|
+
|
|
8
|
+
- **New `src/core/HybridLogicalClock.ts`** — the first primitive of the WS2
|
|
9
|
+
replicated-store foundation (spec `multi-machine-replicated-store-foundation.md` §3,
|
|
10
|
+
build-order Step 1). A pure, dependency-injected hybrid logical clock that will give
|
|
11
|
+
every cross-machine replicated change a well-defined total order:
|
|
12
|
+
- `tick()` — local-event advance (physical never regresses; same-ms bumps the logical
|
|
13
|
+
counter); strictly monotonic.
|
|
14
|
+
- `receive(remote, { poolReference })` — canonical HLC merge across all four
|
|
15
|
+
physical-comparison branches; monotonic vs both local and remote.
|
|
16
|
+
- `static compare(a, b)` — strict total order (physical → logical → node tie-break).
|
|
17
|
+
- **Skew-rejection** — a poison-future remote clock (physical beyond a POOL-RELATIVE
|
|
18
|
+
reference + a FIXED `maxDriftMs` clamped to [60s, 15min]) is rejected as a typed
|
|
19
|
+
result and never advances the clock; a legitimately-ahead peer or a slow local
|
|
20
|
+
receiver is never wrongly rejected.
|
|
21
|
+
- **Restart-monotonic** via injected atomic persistence; a corrupt durable stamp
|
|
22
|
+
fails toward a fresh-but-monotonic clock (never crashes construction).
|
|
23
|
+
- Pure + injected (clock / nodeId / persistence are constructor seams) — no ambient
|
|
24
|
+
`Date.now()`/`fs` in the hot path.
|
|
25
|
+
|
|
26
|
+
This primitive is **inert** — nothing imports it yet. Its consumers are the subsequent
|
|
27
|
+
foundation steps (journal-kind envelope → snapshot-then-tail → quarantine ring →
|
|
28
|
+
union-reader), sequenced in the spec's build order §13.
|
|
29
|
+
|
|
30
|
+
## What to Tell Your User
|
|
31
|
+
|
|
32
|
+
Nothing changes for you yet — this is internal groundwork. It's the clock that will let
|
|
33
|
+
your agent keep one coherent memory across multiple machines (so a preference or
|
|
34
|
+
relationship learned on one machine orders correctly against changes on another). The
|
|
35
|
+
machine-spanning memory features that use it land in the following steps.
|
|
36
|
+
|
|
37
|
+
## Summary of New Capabilities
|
|
38
|
+
|
|
39
|
+
- Internal foundation primitive `HybridLogicalClock` (cross-machine total-order clock
|
|
40
|
+
with pool-relative skew-rejection + restart-monotonicity). Not yet wired to any
|
|
41
|
+
feature — it is the substrate the WS2 memory-replication steps build on.
|
|
42
|
+
|
|
43
|
+
## Evidence
|
|
44
|
+
|
|
45
|
+
- `tests/unit/HybridLogicalClock.test.ts` (44, new): tick monotonicity + same-ms
|
|
46
|
+
logical bump; receive merge correctness for all four branches + monotonicity vs both
|
|
47
|
+
sides; `compare()` total-order incl. node tie-break + identical-triple equality;
|
|
48
|
+
skew-rejection on a poison-future remote with both boundary sides; pool-relative
|
|
49
|
+
reference (a slow receiver does NOT reject a within-bound ahead peer); the
|
|
50
|
+
[60s,15min] clamp; restart-monotonicity from persisted state; persist-on-advance;
|
|
51
|
+
corrupt-persisted-stamp degradation across 8 malformed shapes; serialize/parse
|
|
52
|
+
round-trips + malformed-input rejection. `tsc --noEmit` clean; full lint chain green.
|
|
53
|
+
- Adversarial review: distributed-correctness brute-forced 3456 merge tuples vs the
|
|
54
|
+
canonical Kulkarni HLC merge (zero mismatches); integration-purity MEDIUM (corrupt
|
|
55
|
+
stamp crash) fixed.
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# Side-Effects Review — Replicated-store foundation Step 1: HybridLogicalClock primitive
|
|
2
|
+
|
|
3
|
+
**Version / slug:** `replicated-store-foundation-hlc-primitive`
|
|
4
|
+
**Date:** `2026-06-13`
|
|
5
|
+
**Author:** `Instar Agent (echo)`
|
|
6
|
+
**Spec:** `docs/specs/multi-machine-replicated-store-foundation.md` §3 (converged + approved), build-order Step 1
|
|
7
|
+
**Second-pass reviewer:** 2 adversarial lenses (distributed-correctness / integration-and-purity) — distributed-correctness CONCUR (brute-forced 3456 merge tuples vs the canonical Kulkarni HLC merge, zero mismatches); integration-purity raised 1 MEDIUM (corrupt persisted stamp crashed construction) — FIXED.
|
|
8
|
+
|
|
9
|
+
## Summary of the change
|
|
10
|
+
|
|
11
|
+
The first primitive of the WS2 replicated-store foundation: `src/core/HybridLogicalClock.ts` — a
|
|
12
|
+
pure, dependency-injected hybrid logical clock that gives every replicated change a
|
|
13
|
+
well-defined cross-machine total order. Operations: `tick()` (local-event advance,
|
|
14
|
+
physical never regresses, same-ms bumps logical), `receive(remote, {poolReference})`
|
|
15
|
+
(canonical HLC merge across all four physical-comparison branches), `static compare()`
|
|
16
|
+
(strict total order: physical → logical → node tie-break). Skew-rejection is
|
|
17
|
+
POOL-RELATIVE (reference = max(last.physical, poolReference), not the bare receiver
|
|
18
|
+
now()) with a FIXED `maxDriftMs` clamped to [60s, 15min] — honoring the spec's
|
|
19
|
+
BLOCKER-5 resolution (a 3-value enum is not a numeric skew source). Restart-monotonic
|
|
20
|
+
via injected atomic persistence; a corrupt durable stamp fails toward a fresh-but-
|
|
21
|
+
monotonic clock (never crashes construction). Files: `src/core/HybridLogicalClock.ts`
|
|
22
|
+
(new), `tests/unit/HybridLogicalClock.test.ts` (new, 44 tests).
|
|
23
|
+
|
|
24
|
+
This is a PURE LIBRARY with NO wiring yet — its consumers are the subsequent
|
|
25
|
+
foundation steps (journal-kind envelope, snapshot-then-tail, quarantine ring,
|
|
26
|
+
union-reader), per the spec's own build order §13. It is inert (changes no existing
|
|
27
|
+
behavior) until a later step consumes it.
|
|
28
|
+
|
|
29
|
+
## Decision-point inventory
|
|
30
|
+
|
|
31
|
+
- No block/allow/gate surface. A clock primitive is mechanism, not authority. The only
|
|
32
|
+
"decision" is `receive()`'s skew-rejection — a typed return value, not a behavior
|
|
33
|
+
gate on anything that exists today (nothing calls it yet).
|
|
34
|
+
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
## 1. Over-block
|
|
38
|
+
N/A — no gate. `receive()`'s skew-rejection rejects a poison-future remote clock
|
|
39
|
+
(physical > pool-relative reference + clamped maxDriftMs); the pool-relative reference
|
|
40
|
+
+ [60s,15min] clamp ensure a legitimately-ahead peer or a slow receiver is never
|
|
41
|
+
wrongly rejected (proven by tests on both sides of the boundary).
|
|
42
|
+
|
|
43
|
+
## 2. Under-block
|
|
44
|
+
A within-bound skewed clock is accepted (by design — the bound tolerates real drift).
|
|
45
|
+
The primitive does not by itself defend against a sustained-malicious clock beyond the
|
|
46
|
+
drift bound; that is the quarantine ring's job (a later step). Stated honestly.
|
|
47
|
+
|
|
48
|
+
## 3. Level-of-abstraction fit
|
|
49
|
+
Right layer — a self-contained core primitive with all I/O (clock, nodeId,
|
|
50
|
+
persistence) injected, exactly the spec's §3 shape. It layers ON the existing
|
|
51
|
+
CoherenceJournal transport without modifying it (this PR touches neither
|
|
52
|
+
CoherenceJournal nor JournalSyncApplier).
|
|
53
|
+
|
|
54
|
+
## 4. Signal vs authority compliance
|
|
55
|
+
Pure mechanism. No blocking authority. The skew-rejection is a returned typed result
|
|
56
|
+
the (future) caller decides on, not a gate the primitive enforces.
|
|
57
|
+
|
|
58
|
+
## 5. Interactions
|
|
59
|
+
None today — nothing imports it yet. It cannot shadow, double-fire, or race with any
|
|
60
|
+
existing code because it is unconsumed. Designed so the later journal-kind step embeds
|
|
61
|
+
its serialized form in the replicated-record envelope.
|
|
62
|
+
|
|
63
|
+
## 6. External surfaces
|
|
64
|
+
No route, no config flag, no mesh verb, no CLI. No change visible to other agents,
|
|
65
|
+
users, or systems. Net-new module only.
|
|
66
|
+
|
|
67
|
+
## Framework generality
|
|
68
|
+
No framework-launch abstraction touched (does not modify `frameworkSessionLaunch.ts`).
|
|
69
|
+
A clock primitive is framework-agnostic. N/A beyond that.
|
|
70
|
+
|
|
71
|
+
## 7. Multi-machine posture (Cross-Machine Coherence)
|
|
72
|
+
**machine-local BY DESIGN (this slice)** — each machine runs its own HLC; the clock is
|
|
73
|
+
not itself replicated. Its PURPOSE is to become the cross-machine ordering substrate:
|
|
74
|
+
later steps stamp replicated journal records with this HLC so the union-reader can
|
|
75
|
+
order changes from all machines deterministically. Phase-C clean: the node-id space is
|
|
76
|
+
unbounded (any string), skew handling is pool-relative (no 2-peer / no-LAN assumption),
|
|
77
|
+
and there are no per-pool-size structures in the primitive.
|
|
78
|
+
|
|
79
|
+
## 8. Rollback cost
|
|
80
|
+
Trivial: a new unconsumed file. Reverting deletes `HybridLogicalClock.ts` + its test;
|
|
81
|
+
nothing depends on it, no durable state, no migration.
|
|
82
|
+
|
|
83
|
+
---
|
|
84
|
+
|
|
85
|
+
## Second-pass review (2 adversarial lenses)
|
|
86
|
+
|
|
87
|
+
- **distributed-correctness:** CONCUR. Brute-forced 3456 (lastP,lastL,remP,remL,now)
|
|
88
|
+
tuples against the canonical Kulkarni et al. HLC merge — zero mismatches; no
|
|
89
|
+
off-by-one in any of the four branches; `compare()` verified a strict total order
|
|
90
|
+
with deterministic node tie-break. Skew-rejection sound + pool-relative.
|
|
91
|
+
- **integration-and-purity:** 1 MEDIUM — a non-null malformed persisted stamp threw
|
|
92
|
+
out of the constructor instead of degrading. FIXED: `coerceHlc(loaded)` is wrapped;
|
|
93
|
+
a corrupt durable stamp logs `hlc-load-corrupt` once and degrades to the same
|
|
94
|
+
fresh-clock path as the missing-file case, then ticks monotonically. Proven by an
|
|
95
|
+
8-corrupt-shape table-driven test. Purity confirmed: clock/nodeId/persistence all
|
|
96
|
+
injected; no ambient Date.now()/fs in the hot path.
|
|
97
|
+
|
|
98
|
+
Verdict: correct + pure + bounded; ship.
|