Skip to content

Commit a13fc62

Browse files
authored
fix(chat): observe report quota outside publication locks (#7714)
Qualified head: 7b64579. Exact-head author-owned approval review: #pullrequestreview-5707589199. Merge readiness returned ready with no unresolved threads. The existing maintainer self-merge authorization and configured wait_for_ci=false policy apply; admin is used for the GitHub author-owned review gate after local qualification. Validation: 26 native File/SQLite cases; unchanged-base quota2 and ordinary native6 controls; final same-harness base lock counterexample; standard six direct/two selected premerge checks; Ruff and public/private scan. No timeout, budget or recovery condition was relaxed. Earlier15s waiter variability remains disclosed; no real account switching, installed adoption or natural delivery is certified by these synthetic checks. Unrelated holds remain. Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent 2f544f9 commit a13fc62

2 files changed

Lines changed: 135 additions & 5 deletions

File tree

‎loopx/capabilities/native_chat/steward_turn.py‎

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -445,7 +445,8 @@ def no_model(*_args):
445445

446446
def _prepare_submission(self, binding_id: str, *, turn_instance_id: str, todo_id: str | None,
447447
validation_command: Sequence[str] | None, work_kind: str,
448-
monitor_deadline: str | None, report_window: dict[str, Any] | None) -> dict[str, Any]:
448+
monitor_deadline: str | None, report_window: dict[str, Any] | None,
449+
quota_observation: dict[str, Any] | None = None) -> dict[str, Any]:
449450
"""Read original request/recovery identity without accepting any work."""
450451
binding = next((row for row in self.bindings.read()["bindings"] if row["binding_id"] == binding_id), None)
451452
if binding is None:
@@ -464,6 +465,16 @@ def _prepare_submission(self, binding_id: str, *, turn_instance_id: str, todo_id
464465
report_subscription_revision=report_window["subscription_revision"])
465466
client_id = native_steward_client_id(actor, turn_instance_id)
466467
existing = self.store.turn_for_client(actor["session_id"], client_id)
468+
if quota_observation is not None:
469+
if binding != quota_observation["binding"]:
470+
raise ValueError("the original steward authorization changed during quota observation")
471+
# Refence execution evidence after slow metadata IO; ordinary SSE
472+
# read counters do not change the original request or its effects.
473+
original = quota_observation["original"]
474+
if existing is None or any(existing.get(key) != original.get(key) for key in (
475+
"turn_id", "client_turn_id", "status", "loopx_request", "response",
476+
"upstream_turn_id", "delta_count", "error_code", "error", "loopx_execution")):
477+
raise ValueError("the original report changed during quota observation")
467478
launch_recovery = None
468479
selection_recovery = None
469480
if existing is not None:
@@ -478,7 +489,9 @@ def _prepare_submission(self, binding_id: str, *, turn_instance_id: str, todo_id
478489
retained = report_turn(self.store, actor, report_window)
479490
if retained is not None and retained["turn_id"] != existing["turn_id"]:
480491
return {"turn": retained}
481-
quota_request = self.report_quota_request(existing)
492+
if quota_observation is None:
493+
return {"turn": existing, "quota_probe": {"original": existing, "binding": binding}}
494+
quota_request = quota_observation["request"]
482495
if quota_request is not None:
483496
request = quota_request
484497
client_id = native_steward_client_id(actor, request["turn_instance_id"])
@@ -538,8 +551,14 @@ def submit(self, binding_id: str, *, turn_instance_id: str, todo_id: str | None
538551
monitor_deadline=monitor_deadline, report_window=report_window)
539552
with controller.lock, exclusive_file_lock(self.bindings.path, operation="inspect_native_steward_turn"):
540553
prepared = self._prepare_submission(binding_id, **parameters)
541-
if "turn" in prepared:
542-
return prepared["turn"], False
554+
quota_observation = None
555+
if "quota_probe" in prepared:
556+
quota_observation = prepared["quota_probe"]
557+
quota_observation["request"] = self.report_quota_request(quota_observation["original"])
558+
with controller.lock, exclusive_file_lock(self.bindings.path, operation="inspect_native_steward_turn"):
559+
prepared = self._prepare_submission(binding_id, **parameters, quota_observation=quota_observation)
560+
if "turn" in prepared:
561+
return prepared["turn"], False
543562
observed = self._observe(prepared["request"]["actor"])
544563
retained = None
545564
if work_kind == "monitor":
@@ -549,7 +568,7 @@ def submit(self, binding_id: str, *, turn_instance_id: str, todo_id: str | None
549568
retained = native_command(controller, ["task-lease", "inspect", "--goal-id", prepared["request"]["actor"]["goal_id"],
550569
"--todo-id", todo_id]).get("lease")
551570
with controller.lock, exclusive_file_lock(self.bindings.path, operation="admit_native_steward_turn"):
552-
current = self._prepare_submission(binding_id, **parameters)
571+
current = self._prepare_submission(binding_id, **parameters, quota_observation=quota_observation)
553572
if "turn" in current:
554573
return current["turn"], False
555574
if current["request"] != prepared["request"] or current["client_id"] != prepared["client_id"]:

‎tests/test_native_steward_reports.py‎

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -634,6 +634,117 @@ def observe(**kwargs):
634634
assert frozen == (original_path.read_bytes(), journal_path.read_bytes())
635635

636636

637+
@pytest.mark.parametrize("provider", ["file", "sqlite"])
638+
@pytest.mark.parametrize("change", ["unrelated_input", "read_counter", "queued_input", "binding_scope",
639+
"original_changed", "original_changed_after_identity"])
640+
def test_report_quota_observation_keeps_publication_available_and_rechecks_original(
641+
steward, tmp_path, monkeypatch, provider, change):
642+
import copy
643+
import threading
644+
import time
645+
from loopx.chat_agent import CodexChatAgentError
646+
from loopx.file_lock import exclusive_file_lock
647+
from loopx.capabilities.native_chat.codex_adapter import CodexAppServerAdapter
648+
from loopx.capabilities.native_chat.steward_turn import StewardTurnHost, native_steward_client_id
649+
from loopx.control_plane.turn_driver.journal_store import turn_journal_path
650+
651+
sid, actor, reports, _ = configured(steward, tmp_path, monkeypatch, provider)
652+
store, runtime, _, transport, binding, capture, _ = steward
653+
install_model(steward, tmp_path, sid)
654+
655+
def exhausted(_adapter, _prompt, event_sink):
656+
event_sink("turn.started", {"upstream_turn_id": "quota-refused-native-turn"})
657+
raise CodexChatAgentError("The provider allowance was exhausted.")
658+
659+
monkeypatch.setattr(CodexAppServerAdapter, "start_turn", exhausted)
660+
original = finish(runtime, pump_steward_monitors(runtime)[0])
661+
native = original["response"]["native_loopx"]
662+
assert native["status"] == "failed" and native["host_failure"]["kind"] == "unknown"
663+
_, window = reports.current_window(binding["binding_id"])
664+
journal = turn_journal_path(reports.root, goal_id=actor["goal_id"], turn_key=native["resume_turn_key"])
665+
original_journal, calls = journal.read_bytes(), capture.read_bytes()
666+
other = store.create_session(goal_id=actor["goal_id"], agent_id="codex", adapter_kind="codex_app_server",
667+
upstream_thread_id="unrelated-user-thread")
668+
entered, released = threading.Event(), threading.Event()
669+
results, errors, observations = [], [], []
670+
proof = {"thread_id": store.load_session(sid)["upstream_thread_id"],
671+
"turn_id": original["upstream_turn_id"], "only_original_user_item": True,
672+
"codex_error_info": "usageLimitExceeded", "quota_available": change not in {"unrelated_input", "read_counter"},
673+
"quota_observed_at": time.time()}
674+
675+
def observe(**_kwargs):
676+
observations.append(_kwargs)
677+
entered.set()
678+
assert released.wait(10), "quota observation fixture was not released"
679+
return dict(proof)
680+
681+
def change_original():
682+
changed = copy.deepcopy(original["response"])
683+
changed["native_loopx"]["reason"] = "Retained source changed during observation"
684+
store.update_turn(sid, original["turn_id"], response=changed)
685+
686+
observe_identity = StewardTurnHost._observe
687+
688+
def identity(host, actor):
689+
observed = observe_identity(host, actor)
690+
if change == "original_changed_after_identity":
691+
with runtime.lock:
692+
change_original()
693+
return observed
694+
695+
def submit():
696+
try:
697+
request = original["loopx_request"]
698+
results.append(StewardTurnHost(runtime).submit(binding["binding_id"], report_window=window,
699+
**{key: request[key] for key in ("turn_instance_id", "todo_id", "work_kind", "validation_command")}))
700+
except Exception as exc:
701+
errors.append(exc)
702+
703+
monkeypatch.setattr(CodexAppServerAdapter, "failed_request_observation", staticmethod(observe))
704+
monkeypatch.setattr(StewardTurnHost, "_observe", identity)
705+
worker = threading.Thread(target=submit)
706+
worker.start()
707+
available = False
708+
queued = None
709+
try:
710+
assert entered.wait(5)
711+
available = runtime.lock.acquire(timeout=.5)
712+
if available:
713+
with exclusive_file_lock(transport.bindings.path, timeout_seconds=.5):
714+
if change in {"unrelated_input", "queued_input"}:
715+
queued, created = store.create_queued_turn(other["session_id"] if change == "unrelated_input" else sid,
716+
client_turn_id="human-during-quota", message="Keep this ordinary input available", origin="web")
717+
assert created
718+
elif change == "original_changed":
719+
change_original()
720+
elif change == "read_counter":
721+
store.update_turn(sid, original["turn_id"],
722+
sse_reconnect_count=original["sse_reconnect_count"] + 1)
723+
if change == "binding_scope":
724+
transport.bindings.configure(transport_ref="steward-app", project_ref=binding["project_ref"],
725+
executor_endpoint_id="codex", context_kind="steward", goal_scope="selected")
726+
finally:
727+
if available:
728+
runtime.lock.release()
729+
else:
730+
proof["quota_available"] = False # A failing baseline must not start model work.
731+
released.set()
732+
worker.join(10)
733+
assert not worker.is_alive()
734+
assert available, "quota metadata IO prevented ordinary input and binding publication"
735+
assert len(observations) == 1
736+
assert journal.read_bytes() == original_journal and capture.read_bytes() == calls
737+
continued = native_steward_client_id(actor, original["loopx_request"]["turn_instance_id"] + ".quota-recovery")
738+
assert store.turn_for_client(sid, continued) is None
739+
if change in {"unrelated_input", "read_counter"}:
740+
assert not errors and results == [(store.load_turn(sid, original["turn_id"]), False)]
741+
if queued:
742+
assert store.load_turn(other["session_id"], queued["turn_id"])["status"] == "queued"
743+
else:
744+
assert len(errors) == 1 and isinstance(errors[0], ValueError), errors
745+
assert results == []
746+
747+
637748
@pytest.mark.parametrize("provider", ["file", "sqlite"])
638749
@pytest.mark.parametrize("local_session", [False, True])
639750
@pytest.mark.parametrize("replan_outcome", ["settled", "wait", "invalid_semantic", "already_admitted", "retained_probe"])

0 commit comments

Comments
 (0)