Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,22 @@ proof into their manual writeback, retaining pagination, recovery and once-only
settlement assertions. This retires a duplicate read classifier; full C1/C4/C9
cutover, installed/native adoption and method/outcome benefit remain open.

**Source checkpoint: heartbeat binding ownership (2026-11-21).** Python receipt
readers and locked binders now reuse the existing TypeScript heartbeat binding
and effective-receipt rules. Their file/GoalRef filtering and append-only IO stay
local. One pure batch projection returns an index and binding; Python returns
the original record, retaining unknown details and exact numbers. Repeated
binding-fact projections may be cached, while files, lease readiness, admission
and settlement are read under their original owners. This retires Python's
parallel binding-conflict and effective-receipt reductions. The prior reader
accepted noncanonical Todo ids that the existing settlement owner rejected;
the reader now reports that same identity conflict without changing the log.
File/SQLite public CLI controls retain selection, obligations, state bytes,
original identity and zero extra spend. These source controls do not qualify
C1 default-channel adoption, installed behavior or model/outcome benefit.
The visible-Goal hard-lease control carries the same guard's proof into manual
writeback and retains rejection of unproven writeback without changing the log.

The first task needs an actual feedback or method-choice requirement. Reuse complete existing paths; real consumers must demonstrate gaps before repairing them rather than manufacturing a failure for the example. Experiments, training and procedural publication retain original authority. This document allocates neither another lane's quota nor a prescribed PR count.

## 12. Consequential choices to confirm
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,18 @@ Python 保留发布、字节预算与 fallback。仅用于本次调用的选项
只结算一次的断言。这退役一个重复读回分类器;完整 C1/C4/C9 切换、已安装/
原生采用及方法/成果收益仍开放。

**源码 checkpoint:heartbeat 绑定所有权(2026-11-21)。** Python 回执读者与
锁内绑定器现复用既有 TypeScript heartbeat 绑定和有效回执规则,文件/GoalRef
过滤与 append-only IO 仍在本地。一份纯批量投影返回索引和绑定;Python 返回
原记录,保留未知详情与精确数值。重复的绑定事实投影可以缓存,文件、租约
readiness、准入和结算仍由原 owner 读取。这退役 Python 的平行绑定冲突判断和
有效回执 reduction。旧读者会接受既有结算 owner 拒绝的非规范 Todo id;新读者
报告同一身份冲突,不修改日志。File/SQLite 真实 CLI 对照保留选择、义务、
状态字节、原身份和零额外扣额。这些源码对照不取得 C1 默认渠道采用、已安装
行为或模型/成果收益资格。
可见 Goal 的硬租约对照把同一 guard 返回的证明带入手工写回,并保留未带
证明时的拒绝与日志不变。

首个任务须确有反馈或方法选择需求。已有链完整时直接复用;有缺口时由真实消费者证明并修复,不为配合示例制造失败。运行实验、训练模型和发布过程各沿原权限,本文不占用其他 lane 配额或预设 PR 数。

## 12. 待确认的关键选择
Expand Down
1 change: 1 addition & 0 deletions loopx/control_plane/effect_runtime_handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,7 @@ export function createEffectRuntimeHandlers(
["quota.spend.commit", lazyHandler(() => import("./quota/spend_commit.ts"), ({evaluateQuotaSpendCommit}) => evaluateQuotaSpendCommit)],
["quota.void.commit", lazyHandler(() => import("./quota/void_commit.ts"), ({evaluateQuotaVoidCommit}) => evaluateQuotaVoidCommit)],
["quota.settlement.read", lazyHandler(() => import("./quota/settlement_readback.ts"), ({readQuotaSettlement}) => readQuotaSettlement)],
["quota.heartbeat_receipt.select", lazyHandler(() => import("./quota/heartbeat_receipt_identity.ts"), ({projectHeartbeatReceiptSelection}) => projectHeartbeatReceiptSelection)],
[
"quota.prior_host_turn_closeout.preflight",
lazyHandler(() => import("./quota/unsettled_host_turn_recovery.ts"), ({preflightPriorHostTurnCloseout}) => preflightPriorHostTurnCloseout),
Expand Down
118 changes: 63 additions & 55 deletions loopx/control_plane/quota/heartbeat_receipt.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from __future__ import annotations

import json
from collections.abc import Callable, Mapping
from functools import lru_cache
from pathlib import Path

from ...file_lock import exclusive_cross_runtime_file_lock
Expand All @@ -11,6 +13,7 @@
rollout_event_log_path,
)
from ..todos.contract import normalize_todo_id, normalize_todo_replan_obligation_id
from ..effect_runtime import EffectRuntimeRejected, effect_runtime_result
from .effective_action import EffectiveAction
from .effect_program import SettlementBindingKind, SettlementIdentity
from .error_codes import HeartbeatReceiptIdentityConflictError
Expand Down Expand Up @@ -66,41 +69,56 @@ def heartbeat_receipt_request_subject(event: Mapping[str, object] | None) -> dic
"request_id", "request_revision", "request_digest", "execution_scope_sha256")}


@lru_cache(maxsize=256)
def _receipt_selection(
facts_json: str,
) -> tuple[int | None, tuple[SettlementBindingKind, str, str] | None]:
"""Cache pure binding facts, never a file read, lease, clock or admission."""
try:
result = effect_runtime_result("quota.heartbeat_receipt.select", json.loads(facts_json))
except EffectRuntimeRejected as exc:
if exc.diagnostic_code == "heartbeat_receipt_identity_conflict":
raise HeartbeatReceiptIdentityConflictError(str(exc)) from None
raise ValueError(str(exc)) from None
index, binding = result.get("index"), result.get("binding")
if index is not None and (type(index) is not int or index < 0):
raise TypeError("TypeScript heartbeat receipt selection index mismatch")
if binding is None:
return index, None
if not isinstance(binding, Mapping):
raise TypeError("TypeScript heartbeat receipt binding shape mismatch")
return index, (
SettlementBindingKind(str(binding["binding_kind"])),
str(binding["binding_id"]), str(binding["effect_id"]),
)


def _select_receipt_facts(
events: list[Mapping[str, object]],
) -> tuple[int | None, tuple[SettlementBindingKind, str, str] | None]:
# Keep unknown details in the reader. Only the shared identity owner's raw
# fields enter this pure projection/cache; no receipt or source is cached.
facts = []
for event in events:
details = event.get("details")
facts.append({"run_id": event.get("run_id"), "details": {
key: details[key] for key in (
"todo_id", "replan_obligation_id", "settlement_effect_id",
"request_id", "request_revision", "request_digest", "execution_scope_sha256",
) if isinstance(details, Mapping) and key in details
}})
first = events[0]
return _receipt_selection(json.dumps({
"goal_id": str(first.get("goal_id") or "").strip(),
"agent_id": str(first.get("agent_id") or "").strip(),
"events": facts,
}, sort_keys=True))


def _receipt_settlement_identity(
event: Mapping[str, object],
) -> tuple[SettlementBindingKind, str, str] | None:
details_value = event.get("details")
details: Mapping[str, object] = (
details_value if isinstance(details_value, Mapping) else {}
)
todo_id = str(details.get("todo_id") or "").strip()
replan_obligation_id = normalize_todo_replan_obligation_id(
details.get("replan_obligation_id")
)
effect_id = str(details.get("settlement_effect_id") or "").strip()
request_subject = heartbeat_receipt_request_subject(event)
if sum(bool(value) for value in (todo_id, replan_obligation_id, request_subject)) > 1:
raise HeartbeatReceiptIdentityConflictError(
"heartbeat receipt has conflicting Todo and autonomous replan bindings"
)
if effect_id and not todo_id and not replan_obligation_id and not request_subject:
raise HeartbeatReceiptIdentityConflictError(
"heartbeat receipt has an effect identity without a Todo or "
"autonomous replan binding; refuse to infer or upgrade it"
)
if not todo_id and not replan_obligation_id and not request_subject:
return None
identity = SettlementIdentity(
goal_id=str(event.get("goal_id") or "").strip(),
agent_id=str(event.get("agent_id") or "").strip(),
todo_id=todo_id or None,
turn_instance_id=str(event.get("run_id") or "").strip(),
replan_obligation_id=replan_obligation_id,
request_subject=request_subject,
)
if not effect_id:
effect_id = identity.effect_id
return identity.binding_kind, identity.binding_id, effect_id
return _select_receipt_facts([event])[1]


def heartbeat_receipt_settlement_todo_id(
Expand Down Expand Up @@ -160,22 +178,13 @@ def heartbeat_receipt_pending_action_todo_id(

def _effective_heartbeat_receipt(
events: list[dict[str, object]],
) -> dict[str, object] | None:
) -> tuple[dict[str, object] | None, tuple[SettlementBindingKind, str, str] | None]:
if not events:
return None
identities: dict[tuple[SettlementBindingKind, str, str], dict[str, object]] = {}
for event in events:
identity = _receipt_settlement_identity(event)
if identity is not None:
identities[identity] = event
if len(identities) > 1:
raise HeartbeatReceiptIdentityConflictError(
"heartbeat receipt has conflicting settlement identities for the "
"same goal, agent, and turn"
)
if identities:
return next(iter(identities.values()))
return events[-1]
return None, None
index, binding = _select_receipt_facts(events)
if index is None or index >= len(events):
raise TypeError("TypeScript heartbeat receipt selection did not address the supplied events")
return events[index], binding


def find_heartbeat_receipt(
Expand All @@ -187,7 +196,7 @@ def find_heartbeat_receipt(
goal_ref: Mapping[str, object] | None = None,
) -> dict[str, object] | None:
events = load_rollout_events(rollout_event_log_path(runtime_root, goal_id))
return _effective_heartbeat_receipt(
event, _ = _effective_heartbeat_receipt(
_heartbeat_receipt_events(
events,
goal_id=goal_id,
Expand All @@ -196,6 +205,7 @@ def find_heartbeat_receipt(
goal_ref=goal_ref,
)
)
return event


def ensure_turn_heartbeat_settlement_receipt(
Expand Down Expand Up @@ -244,13 +254,12 @@ def ensure_turn_heartbeat_settlement_receipt(
turn_instance_id=identity.turn_instance_id,
goal_ref=goal_ref,
)
effective = _effective_heartbeat_receipt(matching)
effective, observed = _effective_heartbeat_receipt(matching)
expected = (
identity.binding_kind,
identity.binding_id,
identity.effect_id,
)
observed = _receipt_settlement_identity(effective) if effective is not None else None
if observed is not None and observed != expected:
raise HeartbeatReceiptIdentityConflictError(
"Turn heartbeat receipt belongs to another settlement identity"
Expand Down Expand Up @@ -411,12 +420,12 @@ def retain_pending_heartbeat_action_selection(
turn_instance_id=turn_instance_id,
goal_ref=goal_ref,
)
effective = _effective_heartbeat_receipt(matching)
effective, binding = _effective_heartbeat_receipt(matching)
if effective is None:
raise ValueError(
"identity-less heartbeat receipt is missing; rerun the original guard"
)
if _receipt_settlement_identity(effective) is not None:
if binding is not None:
raise HeartbeatReceiptIdentityConflictError(
"a settled heartbeat Turn cannot retain a different pending selection"
)
Expand Down Expand Up @@ -537,7 +546,7 @@ def upgrade_identityless_heartbeat_receipt(
turn_instance_id=turn_instance_id,
goal_ref=goal_ref,
)
effective = _effective_heartbeat_receipt(matching)
effective, existing_identity = _effective_heartbeat_receipt(matching)
if effective is None:
raise ValueError(
"identity-less heartbeat receipt is missing; rerun the original guard"
Expand Down Expand Up @@ -571,7 +580,6 @@ def upgrade_identityless_heartbeat_receipt(
raise HeartbeatReceiptIdentityConflictError(
"heartbeat receipt did not admit an autonomous replan successor"
)
existing_identity = _receipt_settlement_identity(effective)
expected_identity = (
expected_identity_value.binding_kind,
expected_identity_value.binding_id,
Expand Down Expand Up @@ -698,7 +706,7 @@ def requalify_bound_heartbeat_receipt(

log_path = rollout_event_log_path(runtime_root, goal_id)
with exclusive_cross_runtime_file_lock(log_path, operation="requalify_heartbeat_work"):
original = _effective_heartbeat_receipt(_heartbeat_receipt_events(
original, _ = _effective_heartbeat_receipt(_heartbeat_receipt_events(
load_rollout_events(log_path), goal_id=goal_id, agent_id=agent_id,
turn_instance_id=turn_instance_id, goal_ref=goal_ref,
))
Expand Down
35 changes: 34 additions & 1 deletion loopx/control_plane/quota/heartbeat_receipt_identity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import type { JsonObject } from "../effect_program.ts";
import {executionRequestSubject, settlementIdentity, type SettlementIdentity, type ExecutionRequestSubject} from "../effect_program.ts";
import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts";
import { BARE_SHA256_PATTERN } from "../content_digest.ts";
import { jsonObject } from "../runtime_decode.ts";
import { jsonObject, requireJsonObject } from "../runtime_decode.ts";
import {nativeChildReportAdmission} from "../capabilities/native_child_admission.ts";
import type {ReceiptBoundReplayPhase} from "./settlement_phase.ts";

Expand Down Expand Up @@ -197,6 +197,39 @@ export function selectEffectiveHeartbeatReceipt<Value>(
: entries.at(-1)!.value;
}

/** Pure transport for Python receipt callers. File/GoalRef scoping stays with
* their locked reader; this projection grants no admission or settlement.
* Return an index so unknown event details and numeric IO stay in that reader. */
export function projectHeartbeatReceiptSelection(value: unknown): JsonObject {
const request = requireJsonObject(value, "heartbeat receipt selection");
if (typeof request.goal_id !== "string" || typeof request.agent_id !== "string" ||
!Array.isArray(request.events)) {
throw new EffectRuntimeRequestError("heartbeat receipt selection requires scoped event facts");
}
const goalId = request.goal_id, agentId = request.agent_id;
const entries = request.events.map((value, index) => ({
fact: heartbeatReceiptFactFromEvent(requireJsonObject(value, "heartbeat receipt event")),
value: index,
}));
const index = selectEffectiveHeartbeatReceipt(goalId, agentId, entries);
if (index === null) return {index: null, binding: null};
const fact = entries[index]!.fact;
const binding = heartbeatReceiptBinding(goalId, agentId, fact);
if (binding === null) return {index, binding: null};
// The original receipt may omit its derived effect. Preserve any declared
// effect verbatim, including a conflicting one, just as the shared rule does.
return {index, binding: {
binding_kind: binding.binding_kind,
binding_id: binding.binding_id,
effect_id: binding.settlement_effect_id ?? settlementIdentity({
goal_id: goalId, agent_id: agentId, turn_instance_id: fact.run_id ?? "",
todo_id: fact.todo_id,
replan_obligation_id: normalizeHeartbeatReplanObligationId(fact.replan_obligation_id),
request_subject: fact.request_subject,
}).effect_id,
}};
}

/**
* The first bound receipt for one Turn, used only as the admission clock.
*
Expand Down
62 changes: 62 additions & 0 deletions tests/control_plane/test_heartbeat_receipt.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
retain_pending_heartbeat_action_selection,
upgrade_identityless_heartbeat_receipt,
)
from loopx.control_plane.quota.error_codes import HeartbeatReceiptIdentityConflictError
from loopx.control_plane.quota.settlement import read_heartbeat_settlement
from loopx.rollout_event_log import (
append_rollout_event,
build_rollout_event,
Expand All @@ -27,6 +29,66 @@
EFFECT_ID = f"{GOAL_ID}:{AGENT_ID}:{TODO_ID}:{TURN_ID}"


@pytest.mark.parametrize("todo_id", ["todo_BAD_ID", "not_a_todo", "todo_a", "todo_" + "x" * 65])
def test_receipt_reader_rejects_the_same_illegal_binding_as_settlement(
tmp_path: Path, todo_id: str,
) -> None:
_append_receipt(tmp_path, todo_id=todo_id, effect_id=f"{GOAL_ID}:{AGENT_ID}:{todo_id}:{TURN_ID}")
path = rollout_event_log_path(tmp_path, GOAL_ID)
original = path.read_bytes()
typed = read_heartbeat_settlement(
tmp_path, goal_id=GOAL_ID, agent_id=AGENT_ID, todo_id=None,
turn_instance_id=TURN_ID, resolve_original_binding=True,
)
assert typed is not None and typed.identity.failure is not None
reason = "heartbeat receipt declares a Todo binding that is not a legal Todo id"
assert typed.identity.failure.reason == reason
with pytest.raises(HeartbeatReceiptIdentityConflictError, match="not a legal Todo id") as rejected:
find_heartbeat_receipt(tmp_path, goal_id=GOAL_ID, agent_id=AGENT_ID, turn_instance_id=TURN_ID)
assert str(rejected.value) == reason
assert path.read_bytes() == original


def test_binding_projection_does_not_cache_or_roundtrip_receipt_details(tmp_path: Path) -> None:
# Two fresh logs have identical binding facts and different unconsumed
# details. A pure selection may be reused; the event must be read afresh.
for ordinal in (1, 2):
runtime = tmp_path / str(ordinal)
event = build_rollout_event(
goal_id=GOAL_ID, event_kind="quota_should_run", agent_id=AGENT_ID,
run_id=TURN_ID, status="normal_run", details={
"todo_id": TODO_ID, "settlement_effect_id": EFFECT_ID,
"opaque_observation": ordinal, "exact_integer": 2**60 + ordinal,
},
)
recorded = append_rollout_event(rollout_event_log_path(runtime, GOAL_ID), event)
read = find_heartbeat_receipt(runtime, goal_id=GOAL_ID, agent_id=AGENT_ID, turn_instance_id=TURN_ID)
assert read == recorded
assert read["details"]["opaque_observation"] == ordinal
assert read["details"]["exact_integer"] == 2**60 + ordinal


@pytest.mark.parametrize("binding_details", [
{"replan_obligation_id": "replan-2222222222222222"},
{"request_id": "a" * 64, "request_revision": 1,
"request_digest": "b" * 64, "execution_scope_sha256": "c" * 64},
])
def test_shared_binding_outranks_a_later_unbound_receipt(
tmp_path: Path, binding_details: dict[str, object],
) -> None:
path = rollout_event_log_path(tmp_path, GOAL_ID)
bound = append_rollout_event(path, build_rollout_event(
goal_id=GOAL_ID, event_kind="quota_should_run", agent_id=AGENT_ID,
run_id=TURN_ID, status="normal_run", details=binding_details,
))
_append_receipt(tmp_path)
before = path.read_bytes()
assert find_heartbeat_receipt(
tmp_path, goal_id=GOAL_ID, agent_id=AGENT_ID, turn_instance_id=TURN_ID,
) == bound
assert path.read_bytes() == before


def _append_receipt(
runtime_root: Path,
*,
Expand Down
Loading
Loading