Skip to content

Commit fa3c7d3

Browse files
authored
Recover a paid Turn's missing checkpoint without reopening delivery (#10121)
Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent f813eed commit fa3c7d3

11 files changed

Lines changed: 129 additions & 39 deletions

‎loopx/control_plane/goals/checkpoint_read_context.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {settlementIdentity} from "../effect_program.ts";
55
import {jsonObject, requireJsonObject, requireNonEmptyString} from "../runtime_decode.ts";
66
import {EffectRuntimeRequestError} from "../effect_runtime_errors.ts";
77
import {canonicalAuthoritySha256} from "../coordination/authority_store_codec.ts";
8-
import {isUnqualifiedBlockedReplanWriteback} from "../quota/settlement_phase.ts";
8+
import {isUnqualifiedBlockedReplanWriteback, needsCheckpointSupplement} from "../quota/settlement_phase.ts";
99
import {todoResumeDependencyId} from "../todos/resume_condition.ts";
1010

1111
const RECEIPT_SCHEMA = "checkpoint_read_context_v1";
@@ -93,7 +93,6 @@ export function evaluateCheckpointReadContext(value: unknown): JsonObject {
9393
const token = request.read_context_id;
9494
if (request.phase === "read") {
9595
const prior = requireJsonObject(request.prior, "committed writeback");
96-
const checkpoint = jsonObject(prior.vision_checkpoint);
9796
const missingQualification = request.writeback_committed === true && request.quota_spend_committed === false &&
9897
typeof identity.replan_obligation_id === "string" &&
9998
jsonObject(request.semantic_replan_guard)?.selected_obligation_id === identity.replan_obligation_id &&
@@ -103,7 +102,7 @@ export function evaluateCheckpointReadContext(value: unknown): JsonObject {
103102
turn_instance_id: requireNonEmptyString(identity.turn_instance_id, "turn_instance_id"),
104103
replan_obligation_id: identity.replan_obligation_id,
105104
}));
106-
if ((checkpoint?.decision !== "missing_required" || checkpoint.satisfied !== false) && !missingQualification) {
105+
if (!needsCheckpointSupplement(prior.vision_checkpoint) && !missingQualification) {
107106
return rejected("checkpoint_context_not_missing");
108107
}
109108
const projected = snapshot(request);

‎loopx/control_plane/quota/blocked_wait.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,11 @@ export function projectReceiptBoundWait(value: unknown): JsonObject {
298298
const completedSettlement = todo.status === "done" && todo.task_class === "advancement_task" &&
299299
request.replay_phase === "settlement_pending" &&
300300
progress?.schema_version === "quota_settlement_progress_v0";
301+
if (request.replay_phase === "settlement_pending" && progress?.state === "settled" &&
302+
progress.schema_version === "quota_settlement_progress_v0" && progress.checkpoint_recovery_required === true) {
303+
return boundRecovery(request, "durable_writeback",
304+
"This Turn already committed its work and debit. Read checkpoint-context and supplement only its missing checkpoint using the original identity and delivery fields.");
305+
}
301306
if (request.replay_phase === "settlement_pending" && writebackRequired &&
302307
progress.state === "writeback_receipt_required") {
303308
return boundRecovery(request, "durable_writeback",

‎loopx/control_plane/quota/refresh_recovery.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts";
55
import { jsonObject, requireJsonObject } from "../runtime_decode.ts";
66
import { normalizeDeliveryWorkspaceSnapshot } from "../agents/delivery_workspace.ts";
77

8+
import {needsCheckpointSupplement} from "./settlement_phase.ts";
89
import { decodeExternalDelivery, type ExternalDeliveryRequest } from "./refresh_external_delivery.ts";
910

1011
export interface RefreshRetryRequest {
@@ -145,7 +146,7 @@ export function refreshRecovery(
145146
}
146147
}
147148
if (wantsVision && digest !== priorDigest) {
148-
if (checkpoint?.decision !== "missing_required" || checkpoint.satisfied !== false) {
149+
if (!needsCheckpointSupplement(checkpoint)) {
149150
return result("reject", "committed_vision_decision_conflict");
150151
}
151152
if (laterAgentVision) return result("reject", "checkpoint_superseded_by_later_vision");

‎loopx/control_plane/quota/settlement.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -231,8 +231,11 @@ def attach_settlement_progress(
231231
argv.extend([
232232
"--format", "json", "checkpoint-context", "--goal-id", identity.goal_id,
233233
"--agent-id", identity.agent_id, "--turn-instance-id", identity.turn_instance_id,
234-
"--replan-obligation-id", str(identity.replan_obligation_id),
235234
])
235+
if identity.todo_id:
236+
argv.extend(["--todo-id", identity.todo_id])
237+
else:
238+
argv.extend(["--replan-obligation-id", str(identity.replan_obligation_id)])
236239
if goal_ref is not None:
237240
argv.extend(["--goal-instance-id", str(goal_ref["goal_instance_id"])])
238241
payload["settlement_progress"]["checkpoint_context_command"] = render_owed_host_command(argv)

‎loopx/control_plane/quota/settlement_phase.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@ import { blockedResumeInstant, isBlockedLifecycleWait, isCausalBlockedWait, isMo
66
import {isExecutionLossCloseout} from "./execution_loss_closeout_record.ts";
77
import { isTurnScopedSettlementOutcome } from "../work_items/delivery_outcome.ts";
88

9+
/** Shared eligibility for reading and supplementing an explicitly missing checkpoint. */
10+
export function needsCheckpointSupplement(value: unknown): boolean {
11+
const checkpoint = jsonObject(value);
12+
return checkpoint?.decision === "missing_required" && checkpoint.satisfied === false;
13+
}
14+
915
function retryDelayIsBounded(seconds: number): boolean {
1016
return Number.isFinite(seconds) && seconds >= 60 && seconds <= 30 * 60;
1117
}

‎loopx/control_plane/quota/settlement_readback.ts‎

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ import {
4848
isAcceptedProgressWriteback,
4949
isAcceptedReplanWriteback,
5050
isCapabilityRetirementWriteback,
51+
needsCheckpointSupplement,
5152
receiptBoundMonitorPhase,
5253
receiptBoundReplayPhase,
5354
type ReceiptBoundReplayPhase,
@@ -1639,14 +1640,14 @@ function readQuotaSettlementFromRequest(
16391640
const spendPendingAfterWriteback = writeback.failure === null && spend.failure !== null;
16401641
const receiptProgress = settlementProgress(identityResult, writeback, spend, writebackRun, spendRun,
16411642
receiptDetails.quota_spend_source ?? spendRun?.source, noSpendKind);
1642-
const progress = missingBlockedReplanQualification
1643+
const replanProgress = missingBlockedReplanQualification
16431644
? {...receiptProgress, state: "writeback_required", next_step: "durable_writeback",
16441645
checkpoint_recovery_required: true}
16451646
: receiptProgress;
16461647
// The Run can commit before the CLI records its refresh event. Its original
16471648
// Todo still owes receipt repair even when the Todo itself remains open.
1648-
const pendingTodoReceipt = identity.binding_kind === "todo" && progress.state === "writeback_receipt_required";
1649-
const replayPhase = monitorPhase === "settled" ? "settled"
1649+
const pendingTodoReceipt = identity.binding_kind === "todo" && receiptProgress.state === "writeback_receipt_required";
1650+
const receiptPhase = monitorPhase === "settled" ? "settled"
16501651
: pendingTodoReceipt ? "settlement_pending" : receiptBoundReplayPhase({
16511652
binding_kind: identity.binding_kind,
16521653
writeback_completes_binding: todoBoundReplan || noSpendKind !== null || progressWriteback ||
@@ -1659,17 +1660,26 @@ function readQuotaSettlementFromRequest(
16591660
no_spend_closeout_present: noSpendKind !== null,
16601661
});
16611662

1663+
// Accounting may be complete while the exact open Todo Turn still owes its
1664+
// explicitly required semantic checkpoint. Never reopen work or debit again.
1665+
const paidMissingCheckpoint = identity.binding_kind === "todo" && receiptPhase === "open" &&
1666+
writeback.failure === null && spend.failure === null && writebackRun?.delivery_outcome === "outcome_progress" &&
1667+
needsCheckpointSupplement(writebackRun.vision_checkpoint);
1668+
// Reuse the refresh owner's supersession fence. Once a later judgment exists
1669+
// the paid original can neither overwrite it nor run its business work again.
1670+
const laterAgentVision = (paidMissingCheckpoint || request.refresh_retry !== null) && writebackRun !== null &&
1671+
snapshot.runs.slice((snapshot.runPositions.get(writebackRun) ?? -1) + 1).some(run =>
1672+
quotaOwnerOwnsProjection(request.owner, run.goal_ref) &&
1673+
run.goal_id === identity.goal_id && run.agent_id === identity.agent_id &&
1674+
(jsonObject(run.agent_vision) !== null || jsonObject(run.vision_checkpoint)?.required === true));
1675+
const progress = paidMissingCheckpoint && !laterAgentVision
1676+
? {...receiptProgress, checkpoint_recovery_required: true} : replanProgress;
1677+
let replayPhase = receiptPhase;
1678+
if (paidMissingCheckpoint) replayPhase = laterAgentVision ? "settled" : "settlement_pending";
1679+
16621680
const refreshDecision = request.refresh_retry === null ? null : refreshRecovery(
16631681
request.refresh_retry, writebackRun, writeback.failure === null,
1664-
workspaceCausality?.requirement,
1665-
writebackRun !== null && snapshot.runs.slice(
1666-
(snapshot.runPositions.get(writebackRun) ?? -1) + 1,
1667-
).filter((run) =>
1668-
quotaOwnerOwnsProjection(request.owner, run.goal_ref)
1669-
).some((run) =>
1670-
run.goal_id === identity.goal_id && run.agent_id === identity.agent_id &&
1671-
(jsonObject(run.agent_vision) !== null || jsonObject(run.vision_checkpoint)?.required === true)
1672-
),
1682+
workspaceCausality?.requirement, laterAgentVision,
16731683
missingBlockedReplanQualification,
16741684
);
16751685
// A non-material poll need not appear as findWriteback's advancement run.
@@ -1922,7 +1932,7 @@ function originalSpendRejection(
19221932
ledger: SpendTerms, receipt: SpendTerms,
19231933
): SettlementResult<JsonObject> | null {
19241934
const progress = requireJsonObject(readback.progress, "quota settlement progress");
1925-
if (progress.checkpoint_recovery_required === true) {
1935+
if (progress.checkpoint_recovery_required === true && progress.state !== "settled") {
19261936
return rejectedSpend("the original blocked writeback requires replan qualification; run checkpoint-context for this same Turn");
19271937
}
19281938
const guard = jsonObject(readback.heartbeat_receipt);

‎loopx/control_plane/quota/turn_envelope.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -449,7 +449,8 @@ function actionProjection(payload: JsonObject, deferSettlement = true, precision
449449
const settlementPlan = jsonObject(cliChannel.settlement_plan) ?? {};
450450
const hasSettlementPlan = Object.keys(settlementPlan).length > 0;
451451
const recovery = object(payload.unsettled_host_turn_recovery);
452-
const receiptBoundSettlementOnly = recovery.scope === "current_turn" && recovery.repair === "quota_spend";
452+
const receiptBoundSettlementOnly = recovery.scope === "current_turn" &&
453+
(recovery.repair === "quota_spend" || recovery.repair === "durable_writeback");
453454
let preserveBoundReplanCommands = replanSettlementOnly;
454455
if (replanPacket && !replanSettlementOnly) {
455456
const writebackContract = object(object(payload.replan_action_packet).writeback_contract);

‎loopx/control_plane/quota/unsettled_host_turn.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -516,6 +516,14 @@ def apply_receipt_bound_wait_recovery(
516516
from ..work_items.action_selection_contract import render_cli_command_prefix
517517

518518
assert settlement_progress is not None
519+
if settlement_progress.get("state") == "settled" and settlement_progress.get("checkpoint_recovery_required") is True:
520+
# attach_settlement_progress has rendered the exact bound read command.
521+
cli = payload["interaction_contract"]["cli_channel"]
522+
cli.pop("settlement_plan", None)
523+
cli.update(next_cli_actions=[payload["settlement_progress"]["checkpoint_context_command"]],
524+
spend_after_validation=False, spend_allowed_now=False,
525+
spend_policy="The original debit is committed. Only its checkpoint supplement is owed.")
526+
return True
519527
plan = build_turn_scoped_cli_settlement_plan(
520528
goal_id=goal_id, agent_id=agent_id, todo_id=todo_id,
521529
turn_instance_id=turn_instance_id,

‎tests/control_plane_ts/quota_settlement_readback.test.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2787,7 +2787,7 @@ test("readback exposes matching supersede_event when records are included", asyn
27872787
}
27882788
});
27892789

2790-
test("default verified writeback without boundary or completion enters settlement_pending until spend settles", async t => {
2790+
test("default writeback keeps accounting and required checkpoint recovery distinct", async t => {
27912791
const missingRequiredCheckpoint = {
27922792
schema_version: "vision_checkpoint_v0",
27932793
agent_id: agentId,
@@ -2802,6 +2802,7 @@ test("default verified writeback without boundary or completion enters settlemen
28022802
removeEvent?: string;
28032803
expectedProgress: string;
28042804
expectedReplayPhase: string;
2805+
owesCheckpoint?: boolean;
28052806
}[] = [
28062807
{
28072808
name: "default writeback without checkpoint stays settlement_pending",
@@ -2823,9 +2824,16 @@ test("default verified writeback without boundary or completion enters settlemen
28232824
expectedReplayPhase: "settlement_pending",
28242825
},
28252826
{
2826-
name: "completed spend without completion or accepted checkpoint stays open",
2827+
name: "completed spend with an explicit missing checkpoint allows only recovery",
28272828
options: {writeback: true, spend: true, visionCheckpoint: missingRequiredCheckpoint},
28282829
expectedProgress: "settled",
2830+
expectedReplayPhase: "settlement_pending",
2831+
owesCheckpoint: true,
2832+
},
2833+
{
2834+
name: "legacy spend without an explicit missing checkpoint retains open replay",
2835+
options: {writeback: true, spend: true},
2836+
expectedProgress: "settled",
28292837
expectedReplayPhase: "open",
28302838
},
28312839
{
@@ -2850,6 +2858,7 @@ test("default verified writeback without boundary or completion enters settlemen
28502858
const readback = await readQuotaSettlement(request(runtimeRoot));
28512859
assert.equal((readback.progress as any)?.state, entry.expectedProgress);
28522860
assert.equal(readback.replay_phase, entry.expectedReplayPhase);
2861+
assert.equal((readback.progress as any).checkpoint_recovery_required === true, entry.owesCheckpoint === true);
28532862
} finally {
28542863
await rm(runtimeRoot, {recursive: true, force: true});
28552864
}

‎tests/control_plane_ts/turn_envelope.test.ts‎

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1232,23 +1232,24 @@ test("a projected successor preserves its original closeout guard in the compact
12321232
assert.deepEqual(quotaActionSignatureDocument(source), turnEnvelopeActionSignatureDocument(envelope));
12331233
});
12341234

1235-
test("receipt-bound settlement recovery transports the original executable command intact", () => {
1236-
const source = payload();
1237-
const command = "loopx --runtime-root /" + "long-path/".repeat(50) +
1238-
" quota spend-slot --goal-id goal-turn-envelope --agent-id agent-ts --todo-id todo-1" +
1239-
" --turn-instance-id turn-original --execute";
1240-
const interaction = source.interaction_contract as JsonObject;
1241-
Object.assign(interaction.agent_channel as JsonObject, {delivery_allowed: false});
1242-
Object.assign(interaction.cli_channel as JsonObject, {next_cli_actions: [command], spend_allowed_now: true});
1243-
source.unsettled_host_turn_recovery = {schema_version: "unsettled_host_turn_recovery_v0",
1244-
scope: "current_turn", repair: "quota_spend", binding_kind: "todo", binding_id: "todo-1",
1245-
turn_instance_id: "turn-original"};
1246-
const envelope = buildTurnEnvelope({payload: source,
1247-
scheduler_execution_args: ""});
1248-
assert.equal((envelope.action as JsonObject).delivery_allowed, false);
1249-
assert.deepEqual((envelope.writeback as JsonObject).next_cli_actions, [command]);
1250-
assert.deepEqual(quotaActionSignatureDocument(source), turnEnvelopeActionSignatureDocument(envelope));
1251-
});
1235+
for (const [repair, subcommand] of [["quota_spend", "quota spend-slot"], ["durable_writeback", "checkpoint-context"]]) {
1236+
test(`receipt-bound ${repair} transports the original executable command intact`, () => {
1237+
const source = payload();
1238+
const spend = repair === "quota_spend";
1239+
const command = "loopx --runtime-root /" + "long-path/".repeat(50) +
1240+
` ${subcommand} --goal-id goal-turn-envelope --agent-id agent-ts --todo-id todo-1` +
1241+
" --turn-instance-id turn-original" + (spend ? " --execute" : "");
1242+
const interaction = source.interaction_contract as JsonObject;
1243+
Object.assign(interaction.agent_channel as JsonObject, {delivery_allowed: false});
1244+
Object.assign(interaction.cli_channel as JsonObject, {next_cli_actions: [command], spend_allowed_now: spend});
1245+
source.unsettled_host_turn_recovery = {schema_version: "unsettled_host_turn_recovery_v0",
1246+
scope: "current_turn", repair, binding_kind: "todo", binding_id: "todo-1", turn_instance_id: "turn-original"};
1247+
const envelope = buildTurnEnvelope({payload: source, scheduler_execution_args: ""});
1248+
assert.equal((envelope.action as JsonObject).delivery_allowed, false);
1249+
assert.deepEqual((envelope.writeback as JsonObject).next_cli_actions, [command]);
1250+
assert.deepEqual(quotaActionSignatureDocument(source), turnEnvelopeActionSignatureDocument(envelope));
1251+
});
1252+
}
12521253

12531254
test("large peer inventories retain scoped gates and signed detail without hiding tasks", () => {
12541255
const source = payload();

0 commit comments

Comments
 (0)