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
106 changes: 78 additions & 28 deletions loopx/cli_commands/quota_should_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@

import argparse
from collections.abc import Callable, Mapping
from dataclasses import dataclass, field
from dataclasses import dataclass, field, replace
from pathlib import Path
from typing import TYPE_CHECKING, Any

from ..capabilities.progress_review.context import external_progress_review_context
from ..control_plane.effect_runtime import EffectRuntimeRejected
from ..control_plane.quota.effective_action import EffectiveAction
from ..control_plane.quota.effect_program import SettlementIdentity
from ..control_plane.quota.error_codes import HeartbeatReceiptIdentityConflictError
Expand All @@ -18,6 +19,12 @@
find_heartbeat_receipt,
heartbeat_receipt_request_subject,
heartbeat_receipt_view,
repair_orphaned_identity_upgrade_heartbeat_receipt,
repair_orphaned_identity_upgrade_heartbeat_receipts_for_agent,
)
from ..control_plane.quota.semantic_replan_guard_merge import (
has_orphaned_identity_upgrade_replan_guard,
is_malformed_settlement_state_error,
)
from ..control_plane.turn_driver.codex_context import context_delivery_for_arguments
from ..file_lock import LockAcquireTimeoutError
Expand Down Expand Up @@ -430,6 +437,28 @@ def execute_quota_should_run(
execution.heartbeat_receipt_existing = action_selection.receipt
execution.heartbeat_receipt_existing_status = "replayed"
execution.heartbeat_receipt_existing_appended = False
mutable_should_run = (
not getattr(args, "dry_run", False)
and not getattr(args, "scheduler_observation", False)
)
if (
mutable_should_run
and heartbeat_turn_id
and has_orphaned_identity_upgrade_replan_guard(execution.heartbeat_receipt_existing)
):
repaired_receipt, repaired = repair_orphaned_identity_upgrade_heartbeat_receipt(
runtime_root,
goal_id=args.goal_id,
agent_id=args.agent_id,
turn_instance_id=heartbeat_turn_id,
goal_ref=goal_ref,
)
if repaired and repaired_receipt is not None:
action_selection = replace(action_selection, receipt=repaired_receipt)
execution.action_selection = action_selection
execution.heartbeat_receipt_existing = repaired_receipt
execution.heartbeat_receipt_existing_status = "upgraded"
execution.heartbeat_receipt_existing_appended = True

context_projector = turn_context_projector(
registry_path=registry_path,
Expand All @@ -440,39 +469,56 @@ def execute_quota_should_run(
)
complete_context = not getattr(args, "scheduler_observation", False)
outcome_navigation = complete_context and context_delivery_for_arguments(args)["progressive_enabled"]
payload = export("build_live_quota_should_run_decision")(
status_payload,
goal_id=args.goal_id,
agent_id=args.agent_id,
inline_goal_source=complete_context,
available_capabilities=args.available_capabilities,
include_scheduler_detail="scheduler" in detail_sections,
include_agent_todo_detail="agent-todos" in detail_sections,
codex_app_current_rrule=args.app_automation_current_rrule,
registry_path=registry_path,
runtime_root=runtime_root,
host_observation_resolver=export("resolve_codex_app_automation_rrule"),
scheduler_execution_context=scheduler_context,
operator_inbox_urgency_projector=operator_inbox_urgency_projector,
bounded_research_frontier_projector=export(
decision_builder = export("build_live_quota_should_run_decision")
decision_kwargs = {
"goal_id": args.goal_id,
"agent_id": args.agent_id,
"inline_goal_source": complete_context,
"available_capabilities": args.available_capabilities,
"include_scheduler_detail": "scheduler" in detail_sections,
"include_agent_todo_detail": "agent-todos" in detail_sections,
"codex_app_current_rrule": args.app_automation_current_rrule,
"registry_path": registry_path,
"runtime_root": runtime_root,
"host_observation_resolver": export("resolve_codex_app_automation_rrule"),
"scheduler_execution_context": scheduler_context,
"operator_inbox_urgency_projector": operator_inbox_urgency_projector,
"bounded_research_frontier_projector": export(
"project_live_explore_composition_frontier"
),
progress_review_context_reader=external_progress_review_context,
receipt_bound_todo_id=action_selection.receipt_bound_todo_id,
requested_action_todo_id=action_selection.requested_todo_id_for_decision,
receipt_bound_replan_obligation_id=(
"progress_review_context_reader": external_progress_review_context,
"receipt_bound_todo_id": action_selection.receipt_bound_todo_id,
"requested_action_todo_id": action_selection.requested_todo_id_for_decision,
"receipt_bound_replan_obligation_id": (
action_selection.receipt_bound_replan_obligation_id
),
retained_action_selection_todo_id=(
"retained_action_selection_todo_id": (
action_selection.retained_todo_id_for_decision
),
turn_instance_id=heartbeat_turn_id,
interaction_projection_hooks=interaction_projection_hooks,
turn_start_hook_dispatch=turn_start_hook_dispatch,
turn_context_projector=context_projector,
context_navigation=outcome_navigation,
goal_ref=goal_ref,
)
"turn_instance_id": heartbeat_turn_id,
"interaction_projection_hooks": interaction_projection_hooks,
"turn_start_hook_dispatch": turn_start_hook_dispatch,
"turn_context_projector": context_projector,
"context_navigation": outcome_navigation,
"goal_ref": goal_ref,
}
try:
payload = decision_builder(status_payload, **decision_kwargs)
except (ValueError, EffectRuntimeRejected) as exc:
if (
mutable_should_run
and is_malformed_settlement_state_error(exc)
and repair_orphaned_identity_upgrade_heartbeat_receipts_for_agent(
runtime_root,
goal_id=args.goal_id,
agent_id=args.agent_id,
goal_ref=goal_ref,
)
> 0
):
payload = decision_builder(status_payload, **decision_kwargs)
else:
raise
execution.payload = payload
action_selection_preflight = export("reconcile_requested_quota_action_selection")(
payload,
Expand Down Expand Up @@ -520,6 +566,7 @@ def execute_quota_should_run(
execution.heartbeat_receipt_existing
and not execution.upgrade_recovery_wait
):
prior_repaired = execution.heartbeat_receipt_existing_appended
(
execution.heartbeat_receipt_existing,
execution.heartbeat_receipt_existing_status,
Expand All @@ -536,6 +583,9 @@ def execute_quota_should_run(
scheduler_execution_context=context.scheduler_context,
status_payload=status_payload,
)
if prior_repaired and not execution.heartbeat_receipt_existing_appended:
execution.heartbeat_receipt_existing_status = "upgraded"
execution.heartbeat_receipt_existing_appended = True
else:
(
execution.payload,
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 @@ -392,6 +392,7 @@ export function createEffectRuntimeHandlers(
["quota.settlement.read", lazyHandler(() => import("./quota/settlement_readback.ts"), ({readQuotaSettlement}) => readQuotaSettlement)],
["quota.execution_loss_closeout.commit", lazyHandler(() => import("./quota/execution_loss_closeout.ts"), ({commitExecutionLossCloseout}) => commitExecutionLossCloseout)],
["quota.heartbeat_receipt.select", lazyHandler(() => import("./quota/heartbeat_receipt_identity.ts"), ({projectHeartbeatReceiptSelection}) => projectHeartbeatReceiptSelection)],
["quota.semantic_replan_guard.validate", lazyHandler(() => import("./quota/semantic_replan_guard.ts"), ({validateSemanticReplanGuard}) => validateSemanticReplanGuard)],
[
"quota.prior_host_turn_closeout.preflight",
lazyHandler(() => import("./quota/unsettled_host_turn_recovery.ts"), ({preflightPriorHostTurnCloseout}) => preflightPriorHostTurnCloseout),
Expand Down
6 changes: 6 additions & 0 deletions loopx/control_plane/quota/error_codes.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ class HeartbeatReceiptIdentityConflictError(ValueError):
"""Public-safe diagnostic for a same-turn settlement identity conflict."""


class MalformedSettlementStateError(ValueError):
"""Public-safe diagnostic for persisted settlement state rejected by TS readback."""

diagnostic_code = "malformed_settlement_state"


class QuotaRunIndexConflict(ValueError):
"""A quota spend was definitively rejected by the run-index CAS."""

Expand Down
73 changes: 66 additions & 7 deletions loopx/control_plane/quota/heartbeat_receipt.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@
from .effective_action import EffectiveAction
from .effect_program import SettlementBindingKind, SettlementIdentity
from .error_codes import HeartbeatReceiptIdentityConflictError
from .semantic_replan_guard_merge import (
SEMANTIC_REPLAN_REVIEW_FIELDS,
append_repaired_identity_upgrade_receipt,
compute_repaired_identity_upgrade_replan_guard_details,
merge_semantic_replan_guard_details,
repair_orphaned_identity_upgrade_heartbeat_receipt as repair_orphaned_identity_upgrade_heartbeat_receipt, # noqa: F401
repair_orphaned_identity_upgrade_heartbeat_receipts_for_agent as repair_orphaned_identity_upgrade_heartbeat_receipts_for_agent, # noqa: F401
strip_semantic_replan_companions,
)
from .settlement_workspace_causality import (
delivery_workspace_causality_from_event_details,
)
Expand All @@ -26,12 +35,11 @@
HEARTBEAT_RECEIPT_SCHEMA_VERSION = "heartbeat_quota_receipt_v0"


def _heartbeat_receipt_events(
def _agent_heartbeat_receipt_events(
events: list[dict[str, object]],
*,
goal_id: str,
agent_id: str,
turn_instance_id: str,
goal_ref: Mapping[str, object] | None,
) -> list[dict[str, object]]:
from ..goals.source_session_registry_state import exact_goal_ref
Expand All @@ -52,7 +60,6 @@ def _heartbeat_receipt_events(
if event.get("event_kind") == "quota_should_run"
and str(event.get("goal_id") or "") == goal_id
and str(event.get("agent_id") or "") == agent_id
and str(event.get("run_id") or "") == turn_instance_id
and (
event.get("goal_ref") == expected_goal_ref
if expected_goal_ref is not None
Expand All @@ -61,6 +68,23 @@ def _heartbeat_receipt_events(
]


def _heartbeat_receipt_events(
events: list[dict[str, object]],
*,
goal_id: str,
agent_id: str,
turn_instance_id: str,
goal_ref: Mapping[str, object] | None,
) -> list[dict[str, object]]:
return [
event
for event in _agent_heartbeat_receipt_events(
events, goal_id=goal_id, agent_id=agent_id, goal_ref=goal_ref,
)
if str(event.get("run_id") or "") == turn_instance_id
]


def heartbeat_receipt_request_subject(event: Mapping[str, object] | None) -> dict | None:
"""Transport the original request's path-free identity from scalar event details."""
details = (event or {}).get("details")
Expand Down Expand Up @@ -241,6 +265,14 @@ def ensure_turn_heartbeat_settlement_receipt(
and normalized_semantic_replan_obligation_id is None
):
raise ValueError("Turn semantic replan obligation id is malformed")
if (
semantic_replan_guard_scoped
and semantic_replan_capability_guard is not None
and normalized_semantic_replan_obligation_id is None
):
raise ValueError(
"Turn semantic replan capability guard requires a selected obligation"
)

if quota_spend_source is not None and quota_spend_source not in TURN_SCOPED_SLOT_SPEND_SOURCES:
raise ValueError("Turn quota spend source must be heartbeat or visible-goal")
Expand Down Expand Up @@ -355,13 +387,21 @@ def ensure_turn_heartbeat_settlement_receipt(
if task_lease_epoch is None:
details.pop("prepared_lease_epoch", None)
if semantic_replan_guard_scoped:
if semantic_replan_capability_guard is not None and any(
field in details for field in SEMANTIC_REPLAN_REVIEW_FIELDS
):
raise HeartbeatReceiptIdentityConflictError(
"Turn heartbeat receipt belongs to a review guard"
)
details["semantic_replan_obligation_id"] = (
normalized_semantic_replan_obligation_id or ""
)
if semantic_replan_capability_guard is not None:
details["semantic_replan_capability_id"] = semantic_replan_capability_guard["capability_id"]
details["semantic_replan_gap_id"] = semantic_replan_capability_guard["gap_id"]
details["semantic_replan_frontier_revision"] = semantic_replan_capability_guard["frontier_revision"]
elif normalized_semantic_replan_obligation_id is None:
details = strip_semantic_replan_companions(details)
if (source := previous_source or quota_spend_source) is not None:
details["quota_spend_source"] = source
source_event_id = (
Expand Down Expand Up @@ -613,13 +653,32 @@ def upgrade_identityless_heartbeat_receipt(
else {}
)
if str(existing_details.get("settlement_effect_id") or "").strip():
repaired_details = (
compute_repaired_identity_upgrade_replan_guard_details(
effective, matching
)
)
if repaired_details is not None:
repaired = append_repaired_identity_upgrade_receipt(
log_path,
goal_id=goal_id,
agent_id=agent_id,
turn_instance_id=turn_instance_id,
effective=effective,
repaired_details=repaired_details,
goal_ref=goal_ref,
)
return repaired, True
return effective, False

# The effective receipt was read while holding the rollout lock. Keep
# fields appended by a concurrent same-Turn revision unless this
# correction explicitly replaces them.
corrected_details = dict(effective_details)
corrected_details.update(details)
# non-conflicting fields appended by a concurrent same-Turn revision,
# while stripping orphaned semantic replan companion metadata whenever
# the guard selection clears, rotates, or changes kind.
corrected_details = merge_semantic_replan_guard_details(
effective_details,
details,
)
corrected_details.update(
{
"turn_instance_id": turn_instance_id,
Expand Down
Loading
Loading