feat(claims): ADR-101 Phase 1 — HLC clock + skew-tolerant timestamps

Implements Component A of ADR-101: a hybrid logical clock (Kulkarni 2014)
that gives the work-stealing service skew-tolerant time comparisons across
federated nodes. Single-node deployments are unaffected — the HLC is
optional via DI and degenerates to wall-clock-equivalent ordering when
no remote events ever arrive.

  - infrastructure/hlc.ts (new, ~190 lines): LocalHlc class, compareHlc,
    HlcSkewError (30s default tolerance), helpers for legacy interop
  - work-stealing-service.ts: optional 4th constructor arg accepts an
    IHlc; when wired, comparisons in contestSteal() and isInGracePeriod()
    use HLC.physicalMs instead of Date.now() so they're consistent across
    nodes with up-to-30s clock skew
  - tests/hlc.test.ts (new, 16 tests): monotonic advance, logical bumps,
    backward-clock recovery, update merging, skew rejection, total order
    across nodes, single-node degeneracy

Validation: 177/177 tests pass (16 new + 36 existing work-stealing + 125
others). tsc --noEmit clean. tsup build clean.

Closes Phase 1 of #1775. Phase 2 (federated event store + repository)
and Phase 3 (attested handoff envelopes) follow on this branch.

Co-Authored-By: RuFlo <ruv@ruv.net>
This commit is contained in:
ReuvenandRuFlo committed 2026-05-05 22:36:41 -04:00
1 parent a4b3151417
commit 1f826fb9b0
4 files changed
+453 -7

No files matched your search

@@ -171,13 +171,30 @@ export class InMemoryWorkStealingEventBus implements IWorkStealingEventBus {
*/
export class WorkStealingService implements IWorkStealingService {
private readonly config: WorkStealingConfig;
// ADR-101 Component A: optional HLC for skew-tolerant time comparisons
// across federated nodes. Single-node deployments leave this undefined and
// continue to use Date.now() — preserving backwards compatibility.
private readonly hlc: import('../infrastructure/hlc.js').IHlc | undefined;
constructor(
private readonly repository: IIssueClaimRepository,
private readonly eventBus: IWorkStealingEventBus,
config: Partial<WorkStealingConfig> = {}
config: Partial<WorkStealingConfig> = {},
hlc?: import('../infrastructure/hlc.js').IHlc,
) {
this.config = { ...DEFAULT_WORK_STEALING_CONFIG, ...config };
this.hlc = hlc;
}
/**
* Get the current "now" as an epoch ms.
*
* When an HLC is wired in (federated mode), use its physicalMs which is
* monotonic across the federation. Otherwise fall back to wall clock.
*/
private nowMs(): number {
if (this.hlc) return this.hlc.now().physicalMs;
return Date.now();
}
// ===========================================================================
@@ -354,8 +371,9 @@ export class WorkStealingService implements IWorkStealingService {
throw new Error('Contest has already been resolved');
}
const now = new Date();
if (now > claim.contestInfo.windowEndsAt) {
const nowMs = this.nowMs();
const windowEndsAtMs = new Date(claim.contestInfo.windowEndsAt).getTime();
if (nowMs > windowEndsAtMs) {
throw new Error('Contest window has expired');
}
@@ -366,7 +384,7 @@ export class WorkStealingService implements IWorkStealingService {
// Update contest info with reason
claim.contestInfo.reason = reason;
claim.contestInfo.contestedAt = now;
claim.contestInfo.contestedAt = new Date(nowMs);
await this.repository.update(claim);
@@ -539,9 +557,9 @@ export class WorkStealingService implements IWorkStealingService {
*/
private isInGracePeriodWithConfig(claim: IssueClaimWithStealing, config: WorkStealingConfig): boolean {
const gracePeriodMs = config.gracePeriodMinutes * 60 * 1000;
const now = new Date();
const claimedAt = new Date(claim.claimedAt);
return now.getTime() - claimedAt.getTime() < gracePeriodMs;
const nowMs = this.nowMs();
const claimedAtMs = new Date(claim.claimedAt).getTime();
return nowMs - claimedAtMs < gracePeriodMs;
}
/**
@@ -0,0 +1,198 @@
/**
* Hybrid Logical Clock (HLC).
*
* Implements Kulkarni et al. 2014 — 64-bit-ish timestamps that:
* - monotonically advance on every event, even when wall clock goes backward,
* - track causality across nodes the way Lamport clocks do,
* - stay within a small bounded skew of physical time so they remain
* human-readable for debugging.
*
* In single-node mode the HLC degenerates: `physicalMs` tracks the wall clock
* exactly and `logical` stays at 0, so HLC values are pairwise-comparable to
* plain Unix timestamps. This is the property that lets ADR-101 wire HLC into
* existing Date-based callsites without breaking single-node deployments.
*
* @module v3/claims/infrastructure/hlc
* @see ADR-101 Component A
*/
/**
* Maximum skew (ms) we will accept from a remote HLC before clamping.
* Default 30 s. Configurable per federation.
*/
export const DEFAULT_MAX_SKEW_MS = 30_000;
/**
* A point in HLC time.
*
* Encoding choice: a plain object rather than a packed bigint. We store these
* in JSON-serialized federation envelopes and in event logs that are read by
* humans during postmortems. Readability beats 8-byte packing at this scale.
*/
export interface HlcTimestamp {
/** Wall-clock millis at issuance, possibly bumped forward by causal events. */
readonly physicalMs: number;
/** Tie-breaker: monotonic counter incremented when two HLCs share a physicalMs. */
readonly logical: number;
/** Issuing node identifier. Lets `compare` deterministically order HLCs from different nodes that share (physicalMs, logical). */
readonly nodeId: string;
}
/**
* The all-zero HLC. Used to represent "no clock seen yet" — e.g., events
* loaded from a pre-HLC store that need an HLC field for the new code paths.
* Always sorts before any real HLC.
*/
export function zeroHlc(nodeId = ''): HlcTimestamp {
return Object.freeze({ physicalMs: 0, logical: 0, nodeId });
}
/**
* Pluggable physical-time source. Tests inject a mock; production uses Date.now.
*/
export type PhysicalClock = () => number;
const SYSTEM_CLOCK: PhysicalClock = () => Date.now();
/**
* The clock errors we throw on policy violations. Callers can catch these
* specifically rather than relying on string matching.
*/
export class HlcSkewError extends Error {
constructor(
public readonly receivedPhysicalMs: number,
public readonly localPhysicalMs: number,
public readonly maxSkewMs: number,
) {
super(
`HLC skew exceeded: received physicalMs=${receivedPhysicalMs} ` +
`vs local=${localPhysicalMs} (max=${maxSkewMs}ms)`,
);
this.name = 'HlcSkewError';
}
}
/**
* The clock interface that ClaimService and WorkStealingService depend on.
* Pure interface so single-node deployments can pass a `LocalHlc` and
* federated deployments can pass an instance backed by federation gossip.
*/
export interface IHlc {
/** Generate a new HLC timestamp for a local event. */
now(): HlcTimestamp;
/** Update the clock from a received HLC. Returns the updated local time. */
update(received: HlcTimestamp): HlcTimestamp;
/** Read-only access to the most recently observed HLC. */
peek(): HlcTimestamp;
}
/**
* Local HLC implementation.
*
* Construction notes:
* - `nodeId` should be stable for the lifetime of a process. For federation
* it must be unique across the trust circle; in single-node mode any
* constant works.
* - The clock is mutable; treat the instance as a process-wide singleton.
*/
export class LocalHlc implements IHlc {
private last: HlcTimestamp;
constructor(
public readonly nodeId: string,
private readonly physicalClock: PhysicalClock = SYSTEM_CLOCK,
public readonly maxSkewMs: number = DEFAULT_MAX_SKEW_MS,
) {
if (!nodeId) {
throw new Error('LocalHlc requires a non-empty nodeId');
}
// Seed with the smallest possible timestamp so the first now() always
// takes the "wall clock advanced" branch and produces logical=0. Without
// this seed, the first now() would see (last.physicalMs == wall) and
// bump logical to 1, breaking single-node degeneracy with wall-clock ms.
this.last = { physicalMs: -1, logical: 0, nodeId };
}
now(): HlcTimestamp {
const wall = this.physicalClock();
let physicalMs: number;
let logical: number;
if (wall > this.last.physicalMs) {
// Wall clock advanced — adopt it, reset logical counter.
physicalMs = wall;
logical = 0;
} else {
// Wall clock didn't advance (or went backward); keep last physical and bump logical.
physicalMs = this.last.physicalMs;
logical = this.last.logical + 1;
}
this.last = { physicalMs, logical, nodeId: this.nodeId };
return this.last;
}
update(received: HlcTimestamp): HlcTimestamp {
const wall = this.physicalClock();
// Skew guard: refuse HLCs that are too far in the future.
// We DO NOT jump local clock forward to match — a misbehaving peer would
// poison the global timeline. Instead we throw and let the caller decide.
if (received.physicalMs > wall + this.maxSkewMs) {
throw new HlcSkewError(received.physicalMs, wall, this.maxSkewMs);
}
const maxPhysical = Math.max(wall, this.last.physicalMs, received.physicalMs);
let logical: number;
if (maxPhysical === this.last.physicalMs && maxPhysical === received.physicalMs) {
logical = Math.max(this.last.logical, received.logical) + 1;
} else if (maxPhysical === this.last.physicalMs) {
logical = this.last.logical + 1;
} else if (maxPhysical === received.physicalMs) {
logical = received.logical + 1;
} else {
logical = 0;
}
this.last = { physicalMs: maxPhysical, logical, nodeId: this.nodeId };
return this.last;
}
peek(): HlcTimestamp {
return this.last;
}
}
/**
* Compare two HLC timestamps. Returns -1, 0, or +1 like Date comparison.
*
* Order: physicalMs, then logical, then nodeId (lexicographic). The nodeId
* tiebreaker is what makes this a total order across the federation.
*/
export function compareHlc(a: HlcTimestamp, b: HlcTimestamp): -1 | 0 | 1 {
if (a.physicalMs < b.physicalMs) return -1;
if (a.physicalMs > b.physicalMs) return 1;
if (a.logical < b.logical) return -1;
if (a.logical > b.logical) return 1;
if (a.nodeId < b.nodeId) return -1;
if (a.nodeId > b.nodeId) return 1;
return 0;
}
/**
* Convert HLC to a plain millisecond timestamp for legacy comparisons.
* Lossy by design — the logical bits are dropped. Only use this on the
* boundary with code that can't be HLC-ified yet.
*/
export function hlcToWallMs(t: HlcTimestamp): number {
return t.physicalMs;
}
/**
* Lift a wall-clock millisecond into HLC space at logical=0. Useful for
* upgrading legacy events on read.
*/
export function wallMsToHlc(ms: number, nodeId: string): HlcTimestamp {
return Object.freeze({ physicalMs: ms, logical: 0, nodeId });
}
@@ -19,3 +19,17 @@ export {
type EventFilter,
type EventSubscription,
} from './event-store.js';
// Hybrid Logical Clock (ADR-101 Component A)
export {
LocalHlc,
HlcSkewError,
compareHlc,
hlcToWallMs,
wallMsToHlc,
zeroHlc,
DEFAULT_MAX_SKEW_MS,
type HlcTimestamp,
type IHlc,
type PhysicalClock,
} from './hlc.js';
+216
View File
@@ -0,0 +1,216 @@
/**
* Hybrid Logical Clock tests.
*
* Coverage targets (per ADR-101 Component A):
* - monotonic advance under wall-clock advance
* - logical bumps when wall clock stalls
* - logical bumps when wall clock goes backward
* - update() merges remote causality correctly
* - skew guard rejects far-future remote HLCs
* - compare yields a total order across nodes
* - degeneracy: single-node HLCs are wall-clock-equivalent
*/
import { describe, expect, it } from 'vitest';
import {
LocalHlc,
HlcSkewError,
compareHlc,
zeroHlc,
hlcToWallMs,
wallMsToHlc,
DEFAULT_MAX_SKEW_MS,
type HlcTimestamp,
} from '../src/infrastructure/hlc';
/** Build a controllable physical-clock function for tests. */
function fakeClock(start: number) {
let t = start;
return {
advance(ms: number) { t += ms; },
setTo(ms: number) { t = ms; },
read: () => t,
};
}
describe('LocalHlc', () => {
it('refuses an empty nodeId', () => {
expect(() => new LocalHlc('')).toThrow(/non-empty nodeId/);
});
describe('now()', () => {
it('advances physicalMs when wall clock advances', () => {
const wall = fakeClock(1_000);
const hlc = new LocalHlc('node-A', wall.read);
const t0 = hlc.now();
wall.advance(500);
const t1 = hlc.now();
expect(t1.physicalMs).toBe(1_500);
expect(t1.logical).toBe(0);
expect(compareHlc(t0, t1)).toBe(-1);
});
it('bumps logical when wall clock has not advanced', () => {
const wall = fakeClock(1_000);
const hlc = new LocalHlc('node-A', wall.read);
const t0 = hlc.now();
const t1 = hlc.now();
const t2 = hlc.now();
// wall clock didn't move — logical should monotonically increase
expect(t1.physicalMs).toBe(t0.physicalMs);
expect(t1.logical).toBe(t0.logical + 1);
expect(t2.logical).toBe(t1.logical + 1);
expect(compareHlc(t0, t1)).toBe(-1);
expect(compareHlc(t1, t2)).toBe(-1);
});
it('bumps logical when wall clock goes backward', () => {
const wall = fakeClock(2_000);
const hlc = new LocalHlc('node-A', wall.read);
const t0 = hlc.now();
wall.setTo(1_000); // NTP correction, VM resume, etc.
const t1 = hlc.now();
// physical does NOT regress; logical bumps to keep monotonicity
expect(t1.physicalMs).toBe(t0.physicalMs);
expect(t1.logical).toBeGreaterThan(t0.logical);
expect(compareHlc(t0, t1)).toBe(-1);
});
});
describe('update()', () => {
it('takes the max physical and bumps logical when remote is concurrent', () => {
const wall = fakeClock(1_000);
const local = new LocalHlc('node-A', wall.read);
// Remote is at physical 1000, logical 7 — same physical as ours
const remote: HlcTimestamp = { physicalMs: 1_000, logical: 7, nodeId: 'node-B' };
const merged = local.update(remote);
expect(merged.physicalMs).toBe(1_000);
expect(merged.logical).toBe(8); // max(0, 7) + 1
expect(merged.nodeId).toBe('node-A');
});
it('adopts remote physical when remote is ahead', () => {
const wall = fakeClock(1_000);
const local = new LocalHlc('node-A', wall.read);
const remote: HlcTimestamp = { physicalMs: 1_500, logical: 3, nodeId: 'node-B' };
const merged = local.update(remote);
expect(merged.physicalMs).toBe(1_500);
expect(merged.logical).toBe(4); // remote.logical + 1
});
it('keeps local physical when remote is in the past', () => {
const wall = fakeClock(2_000);
const local = new LocalHlc('node-A', wall.read);
const t0 = local.now();
const remote: HlcTimestamp = { physicalMs: 500, logical: 99, nodeId: 'node-B' };
const merged = local.update(remote);
expect(merged.physicalMs).toBe(t0.physicalMs);
// local's physical wins, logical bumps
expect(merged.logical).toBeGreaterThan(t0.logical);
});
it('throws HlcSkewError when remote is too far in the future', () => {
const wall = fakeClock(1_000);
const local = new LocalHlc('node-A', wall.read, 5_000); // 5s skew tolerance
const farFuture: HlcTimestamp = {
physicalMs: 1_000 + 6_000, // 6s ahead
logical: 0,
nodeId: 'node-B',
};
expect(() => local.update(farFuture)).toThrow(HlcSkewError);
});
it('accepts remote within the skew window', () => {
const wall = fakeClock(1_000);
const local = new LocalHlc('node-A', wall.read, 5_000);
const justInside: HlcTimestamp = {
physicalMs: 1_000 + 4_999,
logical: 0,
nodeId: 'node-B',
};
expect(() => local.update(justInside)).not.toThrow();
});
it('default skew tolerance is 30s', () => {
const wall = fakeClock(0);
const local = new LocalHlc('node-A', wall.read);
expect(local.maxSkewMs).toBe(DEFAULT_MAX_SKEW_MS);
expect(DEFAULT_MAX_SKEW_MS).toBe(30_000);
});
});
describe('compareHlc', () => {
it('orders by physical first, then logical, then nodeId', () => {
const aEarly: HlcTimestamp = { physicalMs: 1, logical: 0, nodeId: 'A' };
const aLate: HlcTimestamp = { physicalMs: 2, logical: 0, nodeId: 'A' };
const aLogical: HlcTimestamp = { physicalMs: 1, logical: 1, nodeId: 'A' };
const bSame: HlcTimestamp = { physicalMs: 1, logical: 0, nodeId: 'B' };
expect(compareHlc(aEarly, aLate)).toBe(-1);
expect(compareHlc(aLate, aEarly)).toBe(1);
expect(compareHlc(aEarly, aLogical)).toBe(-1);
expect(compareHlc(aEarly, bSame)).toBe(-1); // A < B lex
expect(compareHlc(bSame, aEarly)).toBe(1);
expect(compareHlc(aEarly, aEarly)).toBe(0);
});
it('produces a total order on a randomized set', () => {
const items: HlcTimestamp[] = [];
for (let i = 0; i < 50; i++) {
items.push({
physicalMs: Math.floor(Math.random() * 100),
logical: Math.floor(Math.random() * 10),
nodeId: ['A', 'B', 'C', 'D'][Math.floor(Math.random() * 4)]!,
});
}
const sorted = [...items].sort(compareHlc);
for (let i = 1; i < sorted.length; i++) {
expect(compareHlc(sorted[i - 1]!, sorted[i]!)).toBeLessThanOrEqual(0);
}
});
});
describe('helpers', () => {
it('hlcToWallMs returns physicalMs', () => {
expect(hlcToWallMs({ physicalMs: 42, logical: 99, nodeId: 'X' })).toBe(42);
});
it('wallMsToHlc lifts wall ms at logical=0', () => {
const lifted = wallMsToHlc(42, 'X');
expect(lifted).toEqual({ physicalMs: 42, logical: 0, nodeId: 'X' });
});
it('zeroHlc sorts before everything', () => {
const z = zeroHlc('A');
const real: HlcTimestamp = { physicalMs: 1, logical: 0, nodeId: 'A' };
expect(compareHlc(z, real)).toBe(-1);
});
});
describe('single-node degeneracy', () => {
it('produces wall-clock-equivalent ordering when no updates ever arrive', () => {
// ADR-101 promise: in single-node mode, HLC physicalMs tracks wall clock
// and is pairwise-comparable to plain Unix timestamps.
const wall = fakeClock(1_000);
const hlc = new LocalHlc('solo', wall.read);
const t0 = hlc.now();
wall.advance(100);
const t1 = hlc.now();
wall.advance(50);
const t2 = hlc.now();
// Each timestamp should match wall when wall advanced
expect(t0.physicalMs).toBe(1_000);
expect(t1.physicalMs).toBe(1_100);
expect(t2.physicalMs).toBe(1_150);
// Logical stays at 0 because wall advanced each time
expect(t0.logical).toBe(0);
expect(t1.logical).toBe(0);
expect(t2.logical).toBe(0);
// → comparing physicalMs yields the same order as comparing HLCs
expect(t0.physicalMs < t1.physicalMs).toBe(true);
expect(t1.physicalMs < t2.physicalMs).toBe(true);
});
});
});