Skip to content

Commit a994c2b

Browse files
committed
fix(pi): round-8 cluster — marker isolation, contention fallback, signature preservation, stream guards
- #4 HIGH: ctx-session-upgrade isolates queueAndApplyPiRecompMarker in try/catch (round-7 fixed the sibling ctx-recomp but not this path) — a marker throw no longer skips refresh signals, memory migration, and the Complete message. - #5 MED: cache_invalid materialize path gains the PiMaterializeContentionError fallback (fresh non-persisted m[0]) the primary path already had. - #6 MED: toolCall rewrites (dedup-replace + sentinel) spread the existing part so optional thoughtSignature survives instead of being dropped. - #7 MED: guard the <new-memories> wrapper — skip when budget trims to zero (parity with OpenCode renderM1's if(block)). - Oracle3 HIGH: non-throwing 'error' listeners on child stdout/stderr pipes (an unguarded pipe error crashed the HOST process). - Oracle3 LOW: pre-abort accounting wrapped in the same best-effort try/catch as settle(). - Oracle3 MED: session-activation marker re-arm gated on appendCompaction+ getBranch availability — re-signaling every turn when the drain can't apply would force per-turn materialization with no progress. - #8 MED: rolling-nudge synthetic inherits the latest assistant timestamp instead of Date.now() (deterministic across defer passes). - #3: documented in PARITY.md (cleared-thinking keeps signature, matches shipped OpenCode — do not flag). Pi tsc + biome clean; affected suites green.
1 parent e45ff78 commit a994c2b

7 files changed

Lines changed: 112 additions & 16 deletions

File tree

‎packages/pi-plugin/PARITY.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,26 @@ stamps on send.
162162

163163
---
164164

165+
## 9. Cleared reasoning keeps its original signature (matches OpenCode)
166+
167+
When Magic Context clears an aged reasoning/thinking block, it rewrites the
168+
thinking text to a `[cleared]` placeholder but **preserves the original
169+
`thinkingSignature`/`thoughtSignature`**. This is INTENTIONAL and byte-for-byte
170+
matches OpenCode's shipped `clearOldReasoning` (`strip-content.ts`), which runs
171+
in production against Anthropic.
172+
173+
- Pi: `reasoning-replay-pi.ts` `setPiThinkingCleared` keeps the signature.
174+
- OpenCode: `clearOldReasoning` keeps the signature.
175+
176+
Why it does NOT cause provider rejection: the cleared block is replayed only to
177+
the SAME provider that produced the signature, and the signature still matches
178+
the (now-placeholder) block's position in the assistant turn. Stripping the
179+
signature would be MORE likely to trigger a rejection, not less. Do not "fix"
180+
this by nulling the signature — that diverges from the shipped OpenCode behavior
181+
and removes the provider's own integrity token.
182+
183+
---
184+
165185
## Maintenance
166186

167187
Update this file whenever a deliberate Pi↔OpenCode divergence is introduced or

‎packages/pi-plugin/src/commands/ctx-session-upgrade.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
isRecompFailure,
1414
} from "@magic-context/core/hooks/magic-context/recomp-orchestrator";
1515
import { describeError } from "@magic-context/core/shared/error-message";
16+
import { sessionLog } from "@magic-context/core/shared/logger";
1617
import type { SubagentRunner } from "@magic-context/core/shared/subagent-runner";
1718
import {
1819
signalPiHistoryRefresh,
@@ -248,7 +249,19 @@ export function registerCtxSessionUpgradeCommand(
248249
// upgrade republishes compartments but the entire pre-upgrade JSONL
249250
// branch stays visible and grows unbounded until a later incremental
250251
// historian pass advances the marker. Shared with /ctx-recomp.
251-
queueAndApplyPiRecompMarker({ db: deps.db, sessionId, ctx });
252+
//
253+
// Isolated in its own try/catch: marker staging is best-effort (the
254+
// next incremental historian pass re-stages a covering marker), so a
255+
// throw here must NOT skip the refresh signals, the memory migration,
256+
// or the "Complete" message below — the recomp already published.
257+
try {
258+
queueAndApplyPiRecompMarker({ db: deps.db, sessionId, ctx });
259+
} catch (markerError) {
260+
sessionLog(
261+
sessionId,
262+
`pi /ctx-session-upgrade marker staging failed (non-fatal, recomp already published): ${describeError(markerError).brief}`,
263+
);
264+
}
252265

253266
signalPiHistoryRefresh(sessionId);
254267
signalPiPendingMaterialization(sessionId);

‎packages/pi-plugin/src/index.ts‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -850,9 +850,22 @@ export default async function (pi: ExtensionAPI): Promise<void> {
850850
// the marker would then sit undrained (the drain is signal-driven, and
851851
// startup-only rehydration never re-fires). Re-signal here when this
852852
// session has a durable pending marker so the next pass drains it.
853+
//
854+
// Gate on the same APIs the drain itself requires
855+
// (sessionManager.appendCompaction + getBranch): when they're
856+
// unavailable the drain skips-and-PRESERVES the signal, so
857+
// re-signaling every turn would force materialization repeatedly
858+
// with no way to make progress (a per-turn cache bust). Only re-arm
859+
// when the marker can actually be applied.
853860
try {
854-
const pending = getPendingPiCompactionMarkerState(db, sessionId);
855-
if (pending) {
861+
const smForDrain = sm as {
862+
appendCompaction?: unknown;
863+
getBranch?: unknown;
864+
};
865+
const canDrain =
866+
typeof smForDrain.appendCompaction === "function" &&
867+
typeof smForDrain.getBranch === "function";
868+
if (canDrain && getPendingPiCompactionMarkerState(db, sessionId)) {
856869
signalPiDeferredHistoryRefresh(sessionId);
857870
signalPiPendingMaterialization(sessionId);
858871
}

‎packages/pi-plugin/src/inject-compartments-pi.ts‎

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1201,7 +1201,13 @@ export function renderM1Pi(
12011201
newMemories,
12021202
Math.max(1, Math.floor(memoryBudget * 0.25)),
12031203
).renderOrder;
1204-
sections.push(renderMemoryBlockV2(trimmedNewMemories, "new-memories"));
1204+
// Guard against an empty wrapper: if the budget trims every new memory to
1205+
// zero, renderMemoryBlockV2 would emit an empty <new-memories></new-memories>
1206+
// shell, which both wastes a (tiny) m[1] block and diverges from OpenCode's
1207+
// renderM1 (which guards with `if (block)`). Only push when content remains.
1208+
if (trimmedNewMemories.length > 0) {
1209+
sections.push(renderMemoryBlockV2(trimmedNewMemories, "new-memories"));
1210+
}
12051211
}
12061212

12071213
// new-user-profile delta: when the global user-profile version advanced since
@@ -1328,10 +1334,28 @@ export function injectM0M1Pi(
13281334
markers = getCachedMarkers(db, state, currentCompartments);
13291335
if (!m0 || !markers) {
13301336
decision = { value: true, reason: "cache_invalid" };
1331-
const result = materializeM0PiWithRetry(state, db);
1332-
m0 = result.m0;
1333-
markers = result.snapshotMarkers;
1334-
materialized = true;
1337+
try {
1338+
const result = materializeM0PiWithRetry(state, db);
1339+
m0 = result.m0;
1340+
markers = result.snapshotMarkers;
1341+
materialized = true;
1342+
} catch (error) {
1343+
if (!(error instanceof PiMaterializeContentionError)) throw error;
1344+
// Cache was already invalid (no usable cached m[0]/markers to reuse)
1345+
// AND we lost the materialize lock to a sibling process. Dropping
1346+
// injection would lose the whole history block, so render a fresh
1347+
// non-persisted m[0] as a last resort — the next pass re-materializes
1348+
// and persists. Mirrors the no-cached-fallback branch of the primary
1349+
// materialize path above.
1350+
const fresh = renderFreshM0PiNonPersisted(state, db);
1351+
m0 = fresh.m0;
1352+
markers = fresh.snapshotMarkers;
1353+
contentionExhausted = true;
1354+
logSession(
1355+
state.sessionId,
1356+
"pi m[0] cache_invalid materialization contention exhausted; rendered fresh non-persisted m[0]",
1357+
);
1358+
}
13351359
}
13361360
}
13371361

‎packages/pi-plugin/src/nudge-injector.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,11 @@ function createAssistantNudgeMessage(
9797
model: latestAssistant?.model ?? "magic-context/nudge",
9898
usage: latestAssistant?.usage ?? createZeroUsage(),
9999
stopReason: "stop",
100-
timestamp: Date.now(),
100+
// Deterministic timestamp: this synthetic message is re-created on every
101+
// pass (it is not persisted back to source), so Date.now() would differ
102+
// pass-to-pass. Inherit the latest assistant's stable timestamp (0 when
103+
// none) so the injected message is byte-identical across defer passes.
104+
timestamp: latestAssistant?.timestamp ?? 0,
101105
} satisfies PiAssistantMessage;
102106
}
103107

‎packages/pi-plugin/src/subagent-runner.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,17 @@ export class PiSubagentRunner implements SubagentRunner {
292292
error: "pi subagent aborted by caller",
293293
durationMs: Date.now() - startTime,
294294
};
295-
recordAccounting(result);
295+
// Same best-effort contract as settle(): accounting must never throw
296+
// out of the return path (a DB write failure here would propagate to
297+
// the caller as a spurious spawn error). Telemetry is best-effort.
298+
try {
299+
recordAccounting(result);
300+
} catch (err) {
301+
sessionLog(
302+
options.accountingSessionId ?? "subagent",
303+
`subagent accounting failed (continuing): ${err instanceof Error ? err.message : String(err)}`,
304+
);
305+
}
296306
return result;
297307
}
298308
// Large prompts (e.g. a ~50K-token historian chunk ≈ 200 KB) overflow
@@ -423,6 +433,11 @@ export class PiSubagentRunner implements SubagentRunner {
423433
}
424434
emitProgress({ type: "stderr", chunk: text });
425435
});
436+
// A pipe 'error' (EPIPE/ECONNRESET on the child's stderr, e.g. child
437+
// died mid-write) emits on the stream; with no listener Node rethrows
438+
// it as an unhandled exception and crashes the HOST process. Swallow
439+
// it — child death is already handled via 'close'/'error' on the child.
440+
child.stderr?.on("error", () => {});
426441

427442
// Track the final assistant text from `agent_end`. We don't
428443
// resolve eagerly on `agent_end` — we wait for child exit so
@@ -455,6 +470,10 @@ export class PiSubagentRunner implements SubagentRunner {
455470
});
456471
return;
457472
}
473+
// Same host-crash guard as stderr: an unguarded 'error' on the stdout
474+
// pipe (child died mid-stream) would rethrow as an unhandled exception.
475+
// readline does not attach its own error listener to the input stream.
476+
child.stdout.on("error", () => {});
458477
const rl = createInterface({
459478
input: child.stdout,
460479
crlfDelay: Number.POSITIVE_INFINITY,

‎packages/pi-plugin/src/transcript-pi.ts‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -652,10 +652,11 @@ function createPiAssistantPart(
652652
// Non-serializable args still need to be replaceable.
653653
}
654654
const newContent = current.slice();
655+
// Spread the existing part so optional fields (thoughtSignature)
656+
// survive the rewrite — some providers reject a tool call whose
657+
// signature was stripped on re-send. Only `arguments` changes.
655658
newContent[partIndex] = {
656-
type: "toolCall",
657-
id: p.id,
658-
name: p.name,
659+
...p,
659660
arguments: replacementArgs,
660661
};
661662
working[messageIndex] = {
@@ -714,10 +715,12 @@ function createPiAssistantPart(
714715
const existing = current[partIndex];
715716
const newContent = current.slice();
716717
if (existing && existing.type === "toolCall") {
718+
// Spread the existing part so optional fields (thoughtSignature)
719+
// survive the sentinel rewrite — the toolCall shell must stay a
720+
// faithful, provider-acceptable function_call/tool_use; only the
721+
// bulk `arguments` payload is reduced to the marker.
717722
newContent[partIndex] = {
718-
type: "toolCall",
719-
id: existing.id,
720-
name: existing.name,
723+
...existing,
721724
arguments: { __magic_context_dropped__: sentinelText },
722725
};
723726
} else {

0 commit comments

Comments
 (0)