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
8 changes: 7 additions & 1 deletion loopx/capabilities/explore/result_writeback.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@

from ...agent_registry import require_registered_agent_id
from ...control_plane.capability_hooks import PostWritebackHookRegistration
from ...control_plane.effect_runtime import effect_runtime_result
from ...control_plane.effect_runtime import (
effect_runtime_request_scope,
effect_runtime_result,
)
from ...control_plane.coordination.local_authority import (
read_canonical_todos_if_promoted,
)
Expand All @@ -33,6 +36,7 @@
)


@effect_runtime_request_scope()
def normalize_result_attachment(
attachment, *, other_attachment=..., vision_packet=None, scope_context=None
):
Expand Down Expand Up @@ -419,6 +423,7 @@ def _committed_finding_feedback(*, registry_path, runtime_root, goal_id, agent_i
))


@effect_runtime_request_scope()
def record_work_finding(attachment, *, registry_path, runtime_root, goal_id, agent_id,
todo_id, turn_instance_id):
"""Record a finding on an open owned Todo without committing a Turn."""
Expand Down Expand Up @@ -491,6 +496,7 @@ def record_work_finding(attachment, *, registry_path, runtime_root, goal_id, age
return result


@effect_runtime_request_scope()
def deliver_result_attachment(
*,
payload,
Expand Down
141 changes: 74 additions & 67 deletions loopx/control_plane/quota/execution_preparation.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@
require_shadow_primary_write_allowed,
shadow_maintenance_lock_target,
)
from ..effect_runtime import CANONICAL_AUTHORITY_WRITE_TIMEOUT_SECONDS, effect_runtime_result
from ..effect_runtime import (
CANONICAL_AUTHORITY_WRITE_TIMEOUT_SECONDS,
effect_runtime_request_scope,
effect_runtime_result,
)
from ..goals.activation import goal_is_stopped
from ..todos.contract import normalize_todo_claimed_by, normalize_todo_id
from ..work_items.action_selection_contract import (
Expand All @@ -43,6 +47,7 @@ def _unavailable_facts(*, goal_id: str, todo_id: str, agent_id: str) -> dict[str
}


@effect_runtime_request_scope()
def project_selected_todo_execution_preparation(
*,
runtime_root: str | Path | None,
Expand Down Expand Up @@ -226,6 +231,7 @@ def commit_execution_loss_closeout(
return result


@effect_runtime_request_scope()
def read_active_task_lease_epoch(
*,
runtime_root: Path,
Expand Down Expand Up @@ -469,72 +475,73 @@ def guard_first_writeback_execution(
allow_same_generation_lease_renewal: bool = False,
validation_recovery_turn_instance_id: str | None = None,
) -> Iterator[None]:
prepared_lease = settlement.prepared_lease
prepared_required = settlement.prepared_lease_required or prepared_lease is not None
if (requested_proof is None and not prepared_required
and not local_authority_is_promoted(runtime_root=runtime_root, goal_id=goal_id)):
yield
return

# The typed receipt owner positively admits a non-delivery planning review.
# A selected Todo supplies context; it is not business execution. Explicit
# or previously prepared execution proofs retain the original lease gate.
planning_only = (getattr(settlement, "replan_execution_pending", False)
and not prepared_required and requested_proof is None)

# Legacy spend acquires maintenance before the run index. Try maintenance
# once here so this order cannot block a competing accounting process.
with ExitStack() as locks:
locks.enter_context(exclusive_mutation_file_lock(
shadow_maintenance_lock_target(runtime_root, goal_id),
timeout_seconds=0,
operation="refresh-state-execution",
))
require_shadow_primary_write_allowed(runtime_root, goal_id)
snapshot = None
if not planning_only:
snapshot = _read_execution_snapshot(runtime_root, goal_id, todo_id)
if snapshot is None:
raise RefreshTaskLeaseUnavailable("The selected Todo's execution authority could not be read.")
if prepared_required and snapshot.get("handoff_mode") != "hard_lease":
raise RefreshTaskLeaseUnavailable("The Todo's original hard-lease authority is unavailable.")
if snapshot.get("handoff_mode") == "hard_lease":
if not _hard_lease_execution_bound(
snapshot=snapshot,
goal_id=goal_id,
todo_id=todo_id,
agent_id=agent_id,
requested_proof=requested_proof,
settlement=settlement,
allow_same_generation_lease_renewal=allow_same_generation_lease_renewal,
validation_recovery_turn_instance_id=validation_recovery_turn_instance_id,
):
raise RefreshTaskLeaseUnavailable(
"The original writeback needs a current task lease recorded for this Turn. "
"Read the same Todo and Turn through its current guard before retrying."
)
if (
snapshot["todo"].get("status") == "done"
and prepared_required
and settlement.completion_event is None
and not _todo_superseded_for_turn(settlement, todo_id=todo_id, agent_id=agent_id)
):
raise RefreshTaskLeaseUnavailable("The completed Todo is missing this Turn's completion receipt.")
if planning_only or (snapshot is not None and snapshot.get("handoff_mode") == "hard_lease"):
goal = locked_goal
if goal is None:
source, _ = load_recommendation_source_goal(registry_path, goal_id)
invoked = registry_path.resolve()
for registry in dict.fromkeys((source, invoked)):
locks.enter_context(exclusive_cross_runtime_file_lock(
registry, timeout_seconds=0, operation="refresh-state-execution",
))
current_source, goal = load_recommendation_source_goal(registry_path, goal_id)
if current_source != source or goal is None:
raise RefreshTaskLeaseUnavailable("The Goal source changed before this writeback committed.")
if goal_is_stopped(goal):
raise RefreshTaskLeaseUnavailable("The Goal was stopped before this writeback committed.")
yield
with effect_runtime_request_scope():
prepared_lease = settlement.prepared_lease
prepared_required = settlement.prepared_lease_required or prepared_lease is not None
if (requested_proof is None and not prepared_required
and not local_authority_is_promoted(runtime_root=runtime_root, goal_id=goal_id)):
yield
return

# The typed receipt owner positively admits a non-delivery planning review.
# A selected Todo supplies context; it is not business execution. Explicit
# or previously prepared execution proofs retain the original lease gate.
planning_only = (getattr(settlement, "replan_execution_pending", False)
and not prepared_required and requested_proof is None)

# Legacy spend acquires maintenance before the run index. Try maintenance
# once here so this order cannot block a competing accounting process.
with ExitStack() as locks:
locks.enter_context(exclusive_mutation_file_lock(
shadow_maintenance_lock_target(runtime_root, goal_id),
timeout_seconds=0,
operation="refresh-state-execution",
))
require_shadow_primary_write_allowed(runtime_root, goal_id)
snapshot = None
if not planning_only:
snapshot = _read_execution_snapshot(runtime_root, goal_id, todo_id)
if snapshot is None:
raise RefreshTaskLeaseUnavailable("The selected Todo's execution authority could not be read.")
if prepared_required and snapshot.get("handoff_mode") != "hard_lease":
raise RefreshTaskLeaseUnavailable("The Todo's original hard-lease authority is unavailable.")
if snapshot.get("handoff_mode") == "hard_lease":
if not _hard_lease_execution_bound(
snapshot=snapshot,
goal_id=goal_id,
todo_id=todo_id,
agent_id=agent_id,
requested_proof=requested_proof,
settlement=settlement,
allow_same_generation_lease_renewal=allow_same_generation_lease_renewal,
validation_recovery_turn_instance_id=validation_recovery_turn_instance_id,
):
raise RefreshTaskLeaseUnavailable(
"The original writeback needs a current task lease recorded for this Turn. "
"Read the same Todo and Turn through its current guard before retrying."
)
if (
snapshot["todo"].get("status") == "done"
and prepared_required
and settlement.completion_event is None
and not _todo_superseded_for_turn(settlement, todo_id=todo_id, agent_id=agent_id)
):
raise RefreshTaskLeaseUnavailable("The completed Todo is missing this Turn's completion receipt.")
if planning_only or (snapshot is not None and snapshot.get("handoff_mode") == "hard_lease"):
goal = locked_goal
if goal is None:
source, _ = load_recommendation_source_goal(registry_path, goal_id)
invoked = registry_path.resolve()
for registry in dict.fromkeys((source, invoked)):
locks.enter_context(exclusive_cross_runtime_file_lock(
registry, timeout_seconds=0, operation="refresh-state-execution",
))
current_source, goal = load_recommendation_source_goal(registry_path, goal_id)
if current_source != source or goal is None:
raise RefreshTaskLeaseUnavailable("The Goal source changed before this writeback committed.")
if goal_is_stopped(goal):
raise RefreshTaskLeaseUnavailable("The Goal was stopped before this writeback committed.")
yield


def apply_selected_todo_execution_preparation(
Expand Down
45 changes: 39 additions & 6 deletions tests/control_plane/test_context_delivery_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
"""
from __future__ import annotations

from contextlib import redirect_stderr, redirect_stdout
from copy import deepcopy
import hashlib
import io
import json
import os
from pathlib import Path
Expand All @@ -22,11 +24,41 @@
build_turn_envelope, prepare_context_delivery, restore_context_delivery,
)
from test_quota_settlement_cli import (
AGENT_ID, GOAL_ID, TODO_ID,
_heartbeat_receipt_count, _run_cli, _spend_run_count, _write_fixture,
AGENT_ID, GOAL_ID, REPO_ROOT, TODO_ID,
_heartbeat_receipt_count, _run_cli as _run_cli_subprocess, _spend_run_count, _write_fixture,
)


def _run_cli(
registry_path: Path,
runtime: Path,
*args: str,
cwd: Path = REPO_ROOT,
raw_guard: bool = True,
via_subprocess: bool = False,
) -> tuple[int, dict]:
if via_subprocess:
return _run_cli_subprocess(registry_path, runtime, *args, cwd=cwd, raw_guard=raw_guard)
from loopx.entrypoint import main as loopx_entrypoint_main

if raw_guard and args[:2] == ("quota", "should-run") and "--context-delivery" not in args:
args = (*args, "--context-delivery", "off")
argv = ["--registry", str(registry_path), "--runtime-root", str(runtime), "--format", "json", *args]
stdout = io.StringIO()
stderr = io.StringIO()
previous = Path.cwd()
os.chdir(cwd)
try:
with redirect_stdout(stdout), redirect_stderr(stderr):
try:
rc = loopx_entrypoint_main(argv)
except SystemExit as exc:
rc = exc.code if isinstance(exc.code, int) else (0 if exc.code is None else 1)
finally:
os.chdir(previous)
return rc, json.loads(stdout.getvalue())


def _native_reader_args(command):
from loopx.cli import build_parser
from loopx.command_invocation import current_loopx_cli_argv
Expand Down Expand Up @@ -390,7 +422,7 @@ def test_real_cli_host_rendezvous_sends_delta_and_keeps_same_capture_full(tmp_pa
scope = dict(goal_id=GOAL_ID, agent_id=AGENT_ID, session_id="host-session", context_epoch="epoch-1")
saved = []

def invoke(host_request, *, opt_in=True, native_context=False, setting="on"):
def invoke(host_request, *, opt_in=True, native_context=False, setting="on", via_subprocess=False):
with tempfile.TemporaryDirectory(prefix="context-host-", dir="/tmp") as short:
endpoint = Path(short).resolve() / "host.sock"
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as server:
Expand Down Expand Up @@ -422,19 +454,20 @@ def release():
"--turn-instance-id", "host-context-delivery",
"--context-delivery", setting,
"--decision-output-root", str(root), "--decision-handoff-socket", str(endpoint),
*(["--codex-context-dir", str(native_directory)] if native_context else []), cwd=project)
*(["--codex-context-dir", str(native_directory)] if native_context else []),
cwd=project, via_subprocess=via_subprocess)
path, raw = future.result(timeout=30)
assert code == 0, wire
assert path.read_bytes() == raw
saved.append((path, raw))
return wire, path.parent

cold, first = invoke({"scope": scope})
cold, first = invoke({"scope": scope}, via_subprocess=True)
assert cold["mode"] == "full"
assert source_ref in json.dumps(cold["context"])
assert json.loads((first / "projection.json").read_bytes()) == cold["context"]
warm, second = invoke({"scope": scope, "baseline": cold,
"retained": {"complete": True, "target": cold["target"]}})
"retained": {"complete": True, "target": cold["target"]}}, via_subprocess=True)
assert warm["mode"] == "delta"
assert source_ref not in json.dumps(warm["changes"])
projection = json.loads((second / "projection.json").read_bytes())
Expand Down
57 changes: 57 additions & 0 deletions tests/control_plane/test_explore_settlement_attachment.py
Original file line number Diff line number Diff line change
Expand Up @@ -504,3 +504,60 @@ def test_turn_recovers_committed_yardstick_after_disable(tmp_path, monkeypatch,
test_turn_recovers_requested_delivery_from_original_run(
tmp_path, monkeypatch, provider, "progress", "turn", with_yardstick=True,
)


def test_explore_result_writeback_chains_share_one_effect_runtime_scope(tmp_path, monkeypatch):
from loopx.capabilities.explore import result_writeback
from loopx.control_plane import effect_runtime
from tests.control_plane.test_explore_result_writeback import ATTACHMENT, payload

(tmp_path / "finding").mkdir()
(tmp_path / "delivery").mkdir()
args_a = fixture(tmp_path / "finding")
args_b = fixture(tmp_path / "delivery")
fingerprints = []
rpc_calls = []
orig_fp = effect_runtime._runtime_fingerprint
orig_rpc = effect_runtime.effect_runtime_result

def spy_fp():
value = orig_fp()
fingerprints.append(value)
return value

def spy_rpc(method, *args, **kwargs):
rpc_calls.append(method)
return orig_rpc(method, *args, **kwargs)

monkeypatch.setattr(effect_runtime, "_runtime_fingerprint", spy_fp)
monkeypatch.setattr(result_writeback, "effect_runtime_result", spy_rpc)

finding = result_writeback.record_work_finding(deepcopy(ATTACHMENT), **args_a)
assert finding["ok"] is True
assert len(fingerprints) == 1
assert len(rpc_calls) >= 2

before_norm = len(rpc_calls)
shorthand = {
"schema_version": "explore_result_attachment_v0",
"node_id": ATTACHMENT["node_id"],
"input_revision": "fixture-v2",
"observation": "Follow-up bound observation.",
"interpretation": "Still bounded by the recorded scope.",
"status": "refuted",
"evidence_refs": ["validation:counterexample-2"],
}
scope_ctx = {
**{k: v for k, v in args_a.items() if k != "runtime_root"},
"runtime_root_override": str(args_a["runtime_root"]),
}
normalized = result_writeback.normalize_result_attachment(shorthand, scope_context=scope_ctx)
assert normalized["question"] == ATTACHMENT["question"]
assert len(fingerprints) == 2
assert len(rpc_calls) - before_norm >= 1

before_delivery = len(rpc_calls)
delivered = result_writeback.deliver_result_attachment(payload=payload(), **args_b)
assert delivered["ok"] is True
assert len(fingerprints) == 3
assert len(rpc_calls) - before_delivery >= 2
Loading
Loading