Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 60 additions & 9 deletions pm-stack/aggregator/src/sources/live.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2047,14 +2047,6 @@ export function liveSource(
? await opts.hasEvent("orchestration-published", publishRef).catch(() => false)
: false;
if (opts?.onEvent && section.runId !== lastOrchEventRunId && !alreadyRecorded) {
opts.onEvent({
actor: "orchestrator",
kind: "orchestration-published",
ref: `orchestration:${section.runId}`,
summary:
`orchestration run ${section.runId} published: ` +
`${section.tiers.needsDrew.length} needs-user, ${section.tiers.needsOrchestrator.length} needs-orchestrator`,
});
for (const action of section.actions) {
opts.onEvent({
at: action.at,
Expand All @@ -2079,10 +2071,69 @@ export function liveSource(
}
}
}
// #17453: the publish marker is emitted LAST. EventsStore
// serializes record() calls, so a durable marker now proves
// the run's action/tier-change siblings were recorded before
// it — a crash mid-publish loses the marker, not a sibling,
// and the replay guard below can trust the marker again.
opts.onEvent({
actor: "orchestrator",
kind: "orchestration-published",
ref: `orchestration:${section.runId}`,
summary:
`orchestration run ${section.runId} published: ` +
`${section.tiers.needsDrew.length} needs-user, ${section.tiers.needsOrchestrator.length} needs-orchestrator`,
});
lastOrchEventRunId = section.runId;
lastOrchTierById = tierById;
} else if (alreadyRecorded) {
// The durable publication event proves this run was already emitted.
// #17453: a durable marker alone does not prove this run was
// FULLY emitted — under the pre-#17453 marker-first order a
// crash (or a sibling write dropped by validation) after the
// marker persisted left a marker-only store, and treating it
// as complete lost the run's action/tier-change events
// permanently: the tier baseline advanced past them, so no
// later diff could regenerate them. Reconcile instead:
// re-emit exactly the action siblings whose durable identity
// is absent, and — when any sibling proves the publish was
// partial (or there are no actions to prove it complete) —
// the tier changes computed from this process's baseline.
// hasEvent failures stay fail-open (catch → false: emit,
// preferring a visible duplicate over silent loss).
if (opts?.onEvent && section.runId !== lastOrchEventRunId) {
let anyActionMissing = false;
for (const action of section.actions) {
const ref = orchestrationActionRef(action.target);
const recorded = opts.hasEvent
? await opts.hasEvent(action.kind, ref).catch(() => false)
: false;
if (!recorded) {
anyActionMissing = true;
opts.onEvent({
at: action.at,
actor: "orchestrator",
kind: action.kind,
ref,
summary: capUnits(action.summary, 500),
});
}
}
if (lastOrchEventRunId !== null && (anyActionMissing || section.actions.length === 0)) {
const allIds = new Set([...lastOrchTierById.keys(), ...tierById.keys()]);
for (const id of allIds) {
const prev = lastOrchTierById.get(id);
const tier = tierById.get(id);
if (prev !== tier) {
opts.onEvent({
actor: "orchestrator",
kind: "tier-change",
ref: id,
summary: capUnits(`tier ${prev ?? "—"} → ${tier ?? "—"} (run ${section.runId})`, 500),
});
}
}
}
}
lastOrchEventRunId = section.runId;
lastOrchTierById = tierById;
}
Expand Down
118 changes: 117 additions & 1 deletion pm-stack/aggregator/test/orchestration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -536,7 +536,10 @@ describe("live source orchestration states (#1140)", () => {
const opts = {
onEvent: (event: { kind: string; ref: string }) => {
events.push(event);
if (event.kind === "orchestration-published") persisted.add(`${event.kind}:${event.ref}`);
// A fully emitted run: every event is durable, not just the
// marker (#17453 — a marker-only store is the partial state the
// reconciliation test below seeds on purpose).
persisted.add(`${event.kind}:${event.ref}`);
},
hasEvent: async (kind: string, ref: string) => persisted.has(`${kind}:${ref}`),
};
Expand All @@ -546,6 +549,119 @@ describe("live source orchestration states (#1140)", () => {
expect(events).toHaveLength(firstRunCount);
});

test("a marker-only durable store is reconciled, not treated as fully emitted (#17453)", async () => {
const dir = await mkdtemp(join(tmpdir(), "pm-orch-reconcile-"));
const feedFile = join(dir, "fleet-feed.json");
const cfg = loadConfig({
PM_AGG_SOURCE: "live",
PM_AGG_FEED_FILE: feedFile,
PM_AGG_REGISTRY_FILE: join(dir, "registry.json"),
PM_PROJECTOR_URL: "off",
});
const writeSection = async (section: any) =>
writeFile(
feedFile,
JSON.stringify({
version: 1,
generatedAt: new Date().toISOString(),
quota: { pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } },
attention: [],
orchestration: section,
}),
);
const persisted = new Set<string>();
const events: Array<{ kind: string; ref: string; summary: string }> = [];
const opts = {
onEvent: (event: { kind: string; ref: string; summary: string }) => {
events.push(event);
persisted.add(`${event.kind}:${event.ref}`);
},
hasEvent: async (kind: string, ref: string) => persisted.has(`${kind}:${ref}`),
};
const src = liveSource(cfg, opts);
// Run A is published and fully emitted in this process, so the tier
// baseline ({code#812: needs-user}) is present.
await writeSection(LIVE_SHAPE);
await src.orchestration();
const afterA = events.length;
expect(afterA).toBeGreaterThan(0);
// Run B's publish was partially emitted before a restart: ONLY its
// orchestration-published marker reached the durable store; its
// action and tier-change siblings were lost. B moves code#812 to
// needs-orchestrator and carries its own distinct action.
persisted.add("orchestration-published:orchestration:orch-B");
const runB = {
...LIVE_SHAPE,
runId: "orch-B",
generatedAt: new Date().toISOString(),
provenance: { ...LIVE_SHAPE.provenance, runId: "orch-B" },
tiers: {
needsDrew: [],
needsOrchestrator: [{ ...LIVE_SHAPE.tiers.needsDrew[0] }],
},
actions: [
{
at: "2026-10-27T04:14:56Z",
kind: "verify",
target: "laptop attention",
summary: "Reviewed laptop attention for run B.",
},
],
};
await writeSection(runB);
await src.orchestration();
const reconciled = events.slice(afterA);
// The missing siblings are emitted exactly once; the marker is NOT
// re-emitted.
expect(reconciled.map((event) => `${event.kind}:${event.ref}`).sort()).toEqual([
"tier-change:developing-today/code#812",
"verify:laptop-attention",
]);
expect(reconciled.find((event) => event.kind === "tier-change")?.summary).toContain(
"needs-user → needs-orchestrator",
);
// A re-read in this process emits nothing further, and a fresh
// source (restart) against the now-complete store also emits
// nothing: the reconciliation is exactly-once.
await src.orchestration();
expect(events).toHaveLength(afterA + 2);
await liveSource(cfg, opts).orchestration();
expect(events).toHaveLength(afterA + 2);
});

test("a failing hasEvent stays fail-open: the run emits in full (#17453)", async () => {
const dir = await mkdtemp(join(tmpdir(), "pm-orch-failopen-"));
const feedFile = join(dir, "fleet-feed.json");
const cfg = loadConfig({
PM_AGG_SOURCE: "live",
PM_AGG_FEED_FILE: feedFile,
PM_AGG_REGISTRY_FILE: join(dir, "registry.json"),
PM_PROJECTOR_URL: "off",
});
await writeFile(
feedFile,
JSON.stringify({
version: 1,
generatedAt: new Date().toISOString(),
quota: { pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } },
attention: [],
orchestration: LIVE_SHAPE,
}),
);
const events: Array<{ kind: string; ref: string }> = [];
const src = liveSource(cfg, {
onEvent: (event: { kind: string; ref: string }) => events.push(event),
hasEvent: async () => {
throw new Error("store unavailable");
},
});
await src.orchestration();
// Duplicates over silent loss: with the durable check failing, the
// run is treated as not recorded and emits its full event set.
expect(events.map((event) => event.kind)).toContain("orchestration-published");
expect(events.map((event) => event.kind)).toContain("verify");
});

test("registry merge emits events for every newly merged session", async () => {
const dir = await mkdtemp(join(tmpdir(), "pm-registry-events-"));
const feedFile = join(dir, "fleet-feed.json");
Expand Down