Skip to content

Commit 2df3a60

Browse files
fix(scheduler): scope heartbeat receipt scans to one Goal instance
A rollout-event log is shared by every Goal that reuses a display name, so the successor scan could let another instance's receipt expire an admitted Turn's receipt. Resolve the follower's exact GoalRef in the native transport and compare receipts only inside the writer's projection scope: legacy facts compare with legacy facts, and an exact GoalRef only with the same instance. An explicit scope that is malformed or names another goal fails closed with heartbeat_receipt_scope_invalid / heartbeat_receipt_scope_mismatch. Python decision entry points forward the resolved goal_ref, and tests cover ACK and host-failure writebacks on both providers plus the unscoped legacy path. Signed-off-by: GZY-SUPER-HACKER <162807803+GZY-SUPER-HACKER@users.noreply.github.com>
1 parent 7b14e33 commit 2df3a60

9 files changed

Lines changed: 331 additions & 16 deletions

File tree

‎loopx/cli_commands/quota_scheduler_followup.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,7 @@ def build_scheduler_followup_payload(
229229
observed_host_rrule=observed_rrule,
230230
failure_kind=args.failure_kind,
231231
turn_instance_id=turn_instance_id,
232+
goal_ref=goal_ref,
232233
)
233234
return record_quota_scheduler_ack(
234235
status_payload,
@@ -250,4 +251,5 @@ def build_scheduler_followup_payload(
250251
operator_inbox_urgency_projector=operator_inbox_urgency_projector,
251252
before_decision=before_decision,
252253
turn_instance_id=turn_instance_id,
254+
goal_ref=goal_ref,
253255
)

‎loopx/control_plane/quota/scheduler_ack.py‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import json
66
import subprocess
7+
from collections.abc import Mapping
78
from pathlib import Path
89

910
from ..effect_runtime import _node_executable
@@ -185,19 +186,23 @@ def _run_native_followup(
185186
use_current_hint: bool,
186187
reason_summary: str | None,
187188
turn_instance_id: str | None = None,
189+
goal_ref: Mapping[str, object] | None = None,
188190
) -> dict[str, Any]:
189191
"""Decision-free compatibility transport for Python callers.
190192
191193
A caller that already bound the follow-up to a Turn passes it here, so the
192194
native transaction applies the same heartbeat-receipt fence (missing or
193-
superseded) as the generated route. Callers without a Turn keep the
194-
receipt-less compatibility request.
195+
superseded) as the generated route. The exact GoalRef this caller resolved
196+
travels with it, so the native successor scan compares receipts inside the
197+
same instance instead of across every goal that shares the log. Callers
198+
without a Turn keep the receipt-less compatibility request.
195199
"""
196200

197201
request = {
198202
"schema_version": _FOLLOWUP_REQUEST_SCHEMA,
199203
"runtime_root": str(runtime_root),
200204
"turn_instance_id": turn_instance_id,
205+
"goal_ref": dict(goal_ref) if goal_ref is not None else None,
201206
"require_heartbeat_receipt": turn_instance_id is not None,
202207
"before": before,
203208
"host_facts": host_facts,
@@ -306,6 +311,7 @@ def record_quota_scheduler_ack_for_decision(
306311
use_current_hint: bool = False,
307312
host_match_observed: bool = False,
308313
turn_instance_id: str | None = None,
314+
goal_ref: Mapping[str, object] | None = None,
309315
) -> dict[str, Any]:
310316
state_key = _followup_state_key(before, surface=surface, state_key=state_key)
311317
safe_agent_id = normalize_todo_claimed_by(agent_id)
@@ -376,6 +382,7 @@ def record_quota_scheduler_ack_for_decision(
376382
use_current_hint=use_current_hint,
377383
reason_summary=reason_summary,
378384
turn_instance_id=turn_instance_id,
385+
goal_ref=goal_ref,
379386
)
380387
except ValueError as exc:
381388
return _failure_payload(
@@ -406,6 +413,7 @@ def record_quota_scheduler_failure_for_decision(
406413
failure_kind: str = "host_tool_failure",
407414
generated_at: str | None = None,
408415
turn_instance_id: str | None = None,
416+
goal_ref: Mapping[str, object] | None = None,
409417
) -> dict[str, Any]:
410418
state_key = _followup_state_key(before, surface=surface, state_key=state_key)
411419
safe_agent_id = normalize_todo_claimed_by(agent_id)
@@ -454,6 +462,7 @@ def record_quota_scheduler_failure_for_decision(
454462
use_current_hint=False,
455463
reason_summary=None,
456464
turn_instance_id=turn_instance_id,
465+
goal_ref=goal_ref,
457466
)
458467
except ValueError as exc:
459468
return _failure_payload(

‎loopx/control_plane/quota/source_admission.ts‎

Lines changed: 46 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -113,14 +113,56 @@ export function requireQuotaOwnerProjection(
113113
}
114114
}
115115

116-
export function quotaOwnerOwnsProjection(
117-
owner: QuotaAccountingOwner,
116+
/**
117+
* The Goal-instance scope one persisted fact was written under.
118+
*
119+
* `alias` is the legacy projection: the fact carries no `goal_ref` at all.
120+
* Anything else is the one Goal instance the writer presented, so two goals
121+
* that share a display name stay separate even inside one shared log.
122+
*/
123+
export type QuotaProjectionScope =
124+
| Readonly<{ kind: "alias" }>
125+
| Readonly<{ kind: "exact_source"; goalRef: ExactGoalRef }>;
126+
127+
/**
128+
* Read one fact's scope, or null when its `goal_ref` is not a usable scope.
129+
*
130+
* Absent and unparseable refs are different facts: absent is the legacy
131+
* projection every pre-instance writer produced, while a present-but-unusable
132+
* ref belongs to no scope at all and must not be compared loosely.
133+
*/
134+
export function quotaProjectionScope(
135+
value: unknown,
136+
): QuotaProjectionScope | null {
137+
if (value === undefined) return { kind: "alias" };
138+
const projected = parseExactGoalRef(value);
139+
return projected.kind === "parsed"
140+
? { kind: "exact_source", goalRef: projected.value }
141+
: null;
142+
}
143+
144+
/**
145+
* One judge for "did this fact belong to that scope".
146+
*
147+
* Legacy facts only compare with legacy facts and an exact GoalRef only
148+
* compares with that same instance, so a caller cannot widen a scope by
149+
* asking a looser question than the writer answered.
150+
*/
151+
export function quotaScopeOwnsProjection(
152+
scope: QuotaProjectionScope,
118153
value: unknown,
119154
): boolean {
120-
if (owner.kind === "alias") return value === undefined;
155+
if (scope.kind === "alias") return value === undefined;
121156
const projected = parseExactGoalRef(value);
122157
return projected.kind === "parsed"
123-
&& sameGoalRef(projected.value, owner.goalRef);
158+
&& sameGoalRef(projected.value, scope.goalRef);
159+
}
160+
161+
export function quotaOwnerOwnsProjection(
162+
owner: QuotaAccountingOwner,
163+
value: unknown,
164+
): boolean {
165+
return quotaScopeOwnsProjection(owner, value);
124166
}
125167

126168
function quotaSourceLock(

‎loopx/control_plane/rollout_receipt_log.ts‎

Lines changed: 51 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@ import { relative, resolve, sep } from "node:path";
1111

1212
import type { JsonObject } from "./effect_program.ts";
1313
import { EffectRuntimeRequestError } from "./effect_runtime_errors.ts";
14+
import {
15+
quotaProjectionScope,
16+
quotaScopeOwnsProjection,
17+
type QuotaProjectionScope,
18+
} from "./quota/source_admission.ts";
1419
import { requireNonEmptyString } from "./runtime_decode.ts";
1520
import { readReceiptLogSnapshot } from "./runtime/receipt_log_snapshot.ts";
1621

@@ -172,7 +177,9 @@ export async function heartbeatReceiptStatus(params: {
172177
goalId: string;
173178
agentId: string;
174179
turnInstanceId: string;
180+
goalRef?: unknown;
175181
}): Promise<HeartbeatReceiptStatus> {
182+
const requestedScope = requestedReceiptScope(params.goalId, params.goalRef);
176183
const snapshot = await readGoalRolloutEventSnapshot(
177184
params.runtimeRoot,
178185
params.goalId,
@@ -183,21 +190,59 @@ export async function heartbeatReceiptStatus(params: {
183190
params.agentId,
184191
);
185192
if (snapshot === null || receipts === null) return "missing";
186-
const firstReceipt = receipts.find(
187-
(event) => event.run_id === params.turnInstanceId,
193+
const firstReceipt = receipts.find((event) =>
194+
event.run_id === params.turnInstanceId &&
195+
(requestedScope === null ||
196+
quotaScopeOwnsProjection(requestedScope, event.goal_ref))
188197
);
189-
const firstMatch = firstReceipt === undefined
190-
? -1
191-
: snapshot.events.indexOf(firstReceipt);
198+
if (firstReceipt === undefined) return "missing";
199+
const firstMatch = snapshot.events.indexOf(firstReceipt);
192200
if (firstMatch < 0) return "missing";
201+
// The receipt itself states the scope its successor scan may use: a legacy
202+
// receipt is only superseded by another legacy receipt, and an instance
203+
// receipt only by that same Goal instance. A differently named Goal that
204+
// happens to share this log therefore cannot expire an admitted Turn, and an
205+
// unscopable `goal_ref` fails closed instead of authorizing a writeback.
206+
const receiptScope = quotaProjectionScope(firstReceipt.goal_ref);
207+
if (receiptScope === null) return "missing";
193208
// Only a real Turn receipt expires an admitted one. Identity-less quota rows
194209
// are diagnostics: the protocol neither grants them host writeback nor lets
195210
// them supersede the receipt they follow, so the successor scan reuses the
196211
// discovery predicate rather than re-deciding what a receipt is.
197212
return snapshot.events.slice(firstMatch + 1).some((event) =>
198213
isHeartbeatReceiptEvent(event, params.goalId, params.agentId) &&
199-
event.run_id !== params.turnInstanceId
214+
event.run_id !== params.turnInstanceId &&
215+
quotaScopeOwnsProjection(receiptScope, event.goal_ref)
200216
)
201217
? "stale"
202218
: "fresh";
203219
}
220+
221+
/**
222+
* Resolve the scope a caller asked the receipt fence to run in.
223+
*
224+
* Absent means "use the scope the matching receipt states", so the persisted
225+
* receipt stays the only authority. A caller that does know its Goal instance
226+
* passes it, and a malformed or foreign scope is refused rather than silently
227+
* widening the comparison.
228+
*/
229+
function requestedReceiptScope(
230+
goalId: string,
231+
value: unknown,
232+
): QuotaProjectionScope | null {
233+
if (value === undefined || value === null) return null;
234+
const scope = quotaProjectionScope(value);
235+
if (scope === null || scope.kind === "alias") {
236+
throw new EffectRuntimeRequestError(
237+
"heartbeat receipt scope requires goal_id and goal_instance_id",
238+
"heartbeat_receipt_scope_invalid",
239+
);
240+
}
241+
if (scope.goalRef.goalId.value !== goalId) {
242+
throw new EffectRuntimeRequestError(
243+
"heartbeat receipt scope does not belong to the requested goal",
244+
"heartbeat_receipt_scope_mismatch",
245+
);
246+
}
247+
return scope;
248+
}

‎loopx/control_plane/scheduler/heartbeat_commit.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,8 @@ export interface SchedulerHeartbeatCommitResult extends JsonObject {
171171

172172
export interface SchedulerHeartbeatCommitOptions {
173173
readonly heartbeatReceiptTurnInstanceId?: string | null;
174+
/** The Goal instance the caller bound the follow-up to, when it knows it. */
175+
readonly heartbeatReceiptGoalRef?: JsonObject | null;
174176
}
175177

176178
function stableValue(value: unknown): unknown {
@@ -853,6 +855,7 @@ export async function evaluateSchedulerHeartbeatCommit(
853855
goalId: request.scope.goalId,
854856
agentId: request.scope.agentId,
855857
turnInstanceId: receiptTurnInstanceId,
858+
goalRef: options.heartbeatReceiptGoalRef,
856859
});
857860
if (status !== "fresh") {
858861
return result(

‎loopx/control_plane/scheduler/heartbeat_followup.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ export interface SchedulerHeartbeatFollowupRequest extends JsonObject {
3333
schema_version: typeof SCHEDULER_HEARTBEAT_FOLLOWUP_REQUEST_SCHEMA;
3434
runtime_root: string;
3535
turn_instance_id: string | null;
36+
/** The Goal instance the Python transport resolved for this follow-up. */
37+
goal_ref: JsonObject | null;
3638
require_heartbeat_receipt: boolean;
3739
before: JsonObject;
3840
host_facts: JsonObject;
@@ -95,6 +97,9 @@ function requestObject(value: unknown): SchedulerHeartbeatFollowupRequest {
9597
schema_version: SCHEDULER_HEARTBEAT_FOLLOWUP_REQUEST_SCHEMA,
9698
runtime_root: runtimeRoot,
9799
turn_instance_id: turnInstanceId,
100+
goal_ref: input.goal_ref === undefined || input.goal_ref === null
101+
? null
102+
: requireJsonObject(input.goal_ref, "goal_ref"),
98103
require_heartbeat_receipt: requireReceipt,
99104
before: requireJsonObject(input.before ?? {}, "before"),
100105
host_facts: hostFacts,
@@ -341,6 +346,7 @@ export async function evaluateSchedulerHeartbeatFollowup(
341346
goalId: String(facts.goal_id),
342347
agentId: String(facts.agent_id),
343348
turnInstanceId: String(request.turn_instance_id),
349+
goalRef: request.goal_ref,
344350
});
345351
if (status !== "fresh") return receiptFailure(request, status);
346352
}
@@ -351,6 +357,9 @@ export async function evaluateSchedulerHeartbeatFollowup(
351357
heartbeatReceiptTurnInstanceId: request.require_heartbeat_receipt
352358
? request.turn_instance_id
353359
: null,
360+
heartbeatReceiptGoalRef: request.require_heartbeat_receipt
361+
? request.goal_ref
362+
: null,
354363
});
355364
const receiptStatus = commitReceiptFailureStatus(commit);
356365
if (receiptStatus !== null) return receiptFailure(request, receiptStatus);

‎loopx/quota.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1224,6 +1224,7 @@ def record_quota_scheduler_ack(
12241224
operator_inbox_urgency_projector: Callable[..., dict[str, Any]] | None = None,
12251225
before_decision: Mapping[str, Any] | None = None,
12261226
turn_instance_id: str | None = None,
1227+
goal_ref: Mapping[str, Any] | None = None,
12271228
) -> dict[str, Any]:
12281229
safe_goal_id = _validate_goal_id_path_segment(str(goal_id or ""))
12291230
safe_agent_id = normalize_todo_claimed_by(agent_id)
@@ -1259,6 +1260,7 @@ def record_quota_scheduler_ack(
12591260
use_current_hint=use_current_hint,
12601261
host_match_observed=host_match_observed,
12611262
turn_instance_id=turn_instance_id,
1263+
goal_ref=goal_ref,
12621264
)
12631265

12641266

0 commit comments

Comments
 (0)