Skip to content

Commit d3d9ad2

Browse files
authored
fix(chat): recover report quota refusals across retained contexts (#7724)
修复同一 Session 更换原生上下文后安全额度失败被遗漏的恢复路径。复用既有原生来源和 typed admission,保留原失败、未知效果及一次续办边界。 验证:32 项报告回归、52 项 TypeScript、15 项原生协议/来源测试及默认 standard premerge 全部通过;原120秒预算保留。精确 head 的完整评审已发布并独立读回;当前 merge readiness ready=true。实际订阅自然切换和生产报告送达仍需原服务验收。
1 parent e8f4c6f commit d3d9ad2

3 files changed

Lines changed: 93 additions & 7 deletions

File tree

‎loopx/capabilities/native_chat/steward_turn.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,10 +232,18 @@ def report_quota_request(self, original: Mapping[str, Any]) -> dict[str, Any] |
232232
session = self.store.load_session(original["session_id"])
233233
if not session or not session.get("codex_home") or not session.get("upstream_thread_id"):
234234
return None
235+
history = session.get("upstream_context_history") or []
236+
if not isinstance(history, list) or any(not isinstance(item, dict)
237+
or not isinstance(item.get("thread_id"), str) or not item["thread_id"]
238+
for item in history):
239+
return None
240+
# Context replacement retains native provenance on this same Session.
241+
# Read the original refusal there; never resume a historical thread.
242+
threads = [session["upstream_thread_id"], *(item["thread_id"] for item in reversed(history))]
235243
proof = CodexAppServerAdapter.failed_request_observation(codex_bin=self.controller.codex_bin,
236244
codex_home=Path(session["codex_home"]),
237245
model_auth_home=checked_session_home(self.controller.codex_home, session),
238-
thread_ids=[session["upstream_thread_id"]], turn_id=original["upstream_turn_id"])
246+
thread_ids=list(dict.fromkeys(threads)), turn_id=original["upstream_turn_id"])
239247
if (not proof or proof.get("only_original_user_item") is not True
240248
or proof.get("codex_error_info") != "usageLimitExceeded" or proof.get("quota_available") is not True):
241249
return None

‎loopx/control_plane/collaboration/steward_managed_mode.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,16 @@ function admitReportQuotaRecovery(params: JsonObject, request: JsonObject, sessi
9696
const lineage = requireJsonObject(receipt.lineage, "original report lineage");
9797
const keys = Object.keys(request).filter(key => key !== "report_quota_recovery");
9898
const accepting = params.turn == null && params.report_settlement_recovery == null;
99+
const history = session.upstream_context_history ?? [];
100+
if (!Array.isArray(history)) throw new EffectRuntimeRequestError("invalid native context provenance");
101+
const nativeThreads = [session.upstream_thread_id, ...history.map(value => {
102+
const item = requireJsonObject(value, "native context provenance");
103+
if (item.manager_context_version !== null && (!Number.isSafeInteger(item.manager_context_version)
104+
|| Number(item.manager_context_version) < 0)) {
105+
throw new EffectRuntimeRequestError("invalid native context provenance");
106+
}
107+
return requireNonEmptyString(item.thread_id, "original native context thread");
108+
})];
99109
if (request.work_kind !== "report" || prior.work_kind !== "report" || prior.report_quota_recovery !== undefined
100110
|| request.resume_turn_key !== undefined || prior.resume_turn_key !== undefined
101111
|| Object.keys(recovery).sort().join() !== "native_observation,original_turn_id"
@@ -119,7 +129,7 @@ function admitReportQuotaRecovery(params: JsonObject, request: JsonObject, sessi
119129
|| ["goal_matches", "owner_matches", "turn_key_matches", "journal_consistent"].some(key => inspection[key] !== true)
120130
|| inspection.journal_status !== "failed"
121131
|| ![null, true].includes(recorded.host_invoked as null | boolean)
122-
|| observation.thread_id !== session.upstream_thread_id || typeof observation.thread_id !== "string" || !observation.thread_id
132+
|| !nativeThreads.includes(observation.thread_id) || typeof observation.thread_id !== "string" || !observation.thread_id
123133
|| observation.turn_id !== original.upstream_turn_id || observation.only_original_user_item !== true
124134
|| observation.codex_error_info !== "usageLimitExceeded" || observation.quota_available !== true
125135
|| typeof observation.quota_observed_at !== "number" || !Number.isFinite(observation.quota_observed_at)

‎tests/test_native_steward_reports.py‎

Lines changed: 73 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -507,8 +507,9 @@ def install_model(steward, tmp_path, sid, *, result_kind="validated_completion")
507507
@pytest.mark.parametrize("provider", ["file", "sqlite"])
508508
@pytest.mark.parametrize("local_session", [False, True])
509509
@pytest.mark.parametrize("recovery_succeeds", [False, True])
510+
@pytest.mark.parametrize("prior_context", [False, True], ids=["current_context", "prior_context"])
510511
def test_report_quota_failure_continues_once_after_native_no_effects_and_available_allowance(
511-
steward, tmp_path, monkeypatch, provider, local_session, recovery_succeeds):
512+
steward, tmp_path, monkeypatch, provider, local_session, recovery_succeeds, prior_context):
512513
import time
513514
from datetime import timezone
514515
from loopx.chat_agent import CodexChatAgentError
@@ -570,14 +571,28 @@ def exhausted(adapter, _prompt, event_sink):
570571
assert not reports.health(owner)["execution_failed"]
571572
assert frozen == (original_path.read_bytes(), journal_path.read_bytes())
572573
observations = []
573-
proof = {"thread_id": store.load_session(sid)["upstream_thread_id"],
574+
session = store.load_session(sid)
575+
refused_thread = session["upstream_thread_id"]
576+
if prior_context:
577+
# The native host resumes the requested thread, rather than the base
578+
# fixture's fixed id. Keep context identity checks enabled.
579+
fake = Path(runtime.codex_bin)
580+
fake.write_text(fake.read_text().replace('"durable-thread"',
581+
'request.get("params", {}).get("threadId", "durable-thread")'))
582+
store.update_session(sid, upstream_context_history=[*(session.get("upstream_context_history") or []),
583+
{"thread_id": refused_thread, "manager_context_version": session.get("manager_context_version")}],
584+
upstream_thread_id="native-context-after-quota-refusal")
585+
expected_threads = [store.load_session(sid)["upstream_thread_id"]]
586+
if prior_context:
587+
expected_threads.append(refused_thread)
588+
proof = {"thread_id": refused_thread,
574589
"turn_id": original["upstream_turn_id"], "only_original_user_item": True,
575590
"codex_error_info": "usageLimitExceeded", "quota_available": False,
576591
"quota_observed_at": time.time()}
577592

578593
def observe(**kwargs):
579594
observations.append(kwargs)
580-
return dict(proof)
595+
return dict(proof) if refused_thread in kwargs["thread_ids"] else None
581596

582597
monkeypatch.setattr(CodexAppServerAdapter, "failed_request_observation", staticmethod(observe))
583598
runtime._steward_monitor_next_check.clear()
@@ -590,7 +605,8 @@ def observe(**kwargs):
590605
old_adapter = runtime.adapters[sid]
591606
old_thread = store.load_session(sid)["upstream_thread_id"]
592607
continued = pump_steward_monitors(runtime)
593-
assert len(continued) == 1, "the original report must not remain stranded after proven quota recovery"
608+
assert len(continued) == 1, ("the original report must not remain stranded after proven quota recovery; "
609+
f"native contexts observed: {[row['thread_ids'] for row in observations]}")
594610
result = finish(runtime, continued[0])
595611
assert runtime.adapters[sid] is not old_adapter
596612
assert old_adapter.session.process.poll() is not None
@@ -605,7 +621,7 @@ def observe(**kwargs):
605621
assert reports.health(owner)["execution_failed"] is not recovery_succeeds
606622
assert frozen == (original_path.read_bytes(), journal_path.read_bytes())
607623
assert observations and all(x["turn_id"] == original["upstream_turn_id"] for x in observations)
608-
assert all(x["thread_ids"] == [proof["thread_id"]] for x in observations)
624+
assert all(x["thread_ids"] == expected_threads for x in observations)
609625
if not recovery_succeeds:
610626
assert not reports.health(owner)["publication_verified"]
611627
assert len(calls) == 2
@@ -634,6 +650,58 @@ def observe(**kwargs):
634650
assert frozen == (original_path.read_bytes(), journal_path.read_bytes())
635651

636652

653+
@pytest.mark.parametrize("provider", ["file", "sqlite"])
654+
@pytest.mark.parametrize("unsafe_proof", ["foreign_thread", "observed_effects"])
655+
def test_report_quota_context_history_does_not_admit_foreign_or_effectful_failure(
656+
steward, tmp_path, monkeypatch, provider, unsafe_proof):
657+
import time
658+
from loopx.chat_agent import CodexChatAgentError
659+
from loopx.capabilities.native_chat.codex_adapter import CodexAppServerAdapter
660+
from loopx.control_plane.turn_driver.journal_store import turn_journal_path
661+
662+
sid, actor, reports, _ = configured(steward, tmp_path, monkeypatch, provider)
663+
store, runtime, _, _, binding, capture, _ = steward
664+
calls = []
665+
666+
def exhausted(adapter, _prompt, event_sink):
667+
calls.append(adapter.upstream_thread_id)
668+
event_sink("turn.started", {"upstream_turn_id": "quota-refused-native-turn"})
669+
raise CodexChatAgentError("The provider allowance was exhausted.")
670+
671+
monkeypatch.setattr(CodexAppServerAdapter, "start_turn", exhausted)
672+
original = finish(runtime, pump_steward_monitors(runtime)[0])
673+
native = original["response"]["native_loopx"]
674+
assert native["status"] == "failed" and native["result_kind"] == "host_failure"
675+
session = store.load_session(sid)
676+
refused_thread = session["upstream_thread_id"]
677+
fake = Path(runtime.codex_bin)
678+
fake.write_text(fake.read_text().replace('"durable-thread"',
679+
'request.get("params", {}).get("threadId", "durable-thread")'))
680+
store.update_session(sid, upstream_context_history=[*(session.get("upstream_context_history") or []),
681+
{"thread_id": refused_thread, "manager_context_version": session.get("manager_context_version")}],
682+
upstream_thread_id="native-context-after-quota-refusal")
683+
journal = turn_journal_path(reports.root, goal_id=actor["goal_id"], turn_key=native["resume_turn_key"])
684+
turn_folder = store._turn_path(sid, original["turn_id"]).parent
685+
before = {path.name: path.read_bytes() for path in turn_folder.glob("*.json")}
686+
frozen, messages, model_calls = journal.read_bytes(), store.messages(sid), capture.read_bytes()
687+
observed = []
688+
689+
def observe(**kwargs):
690+
observed.append(kwargs)
691+
return {"thread_id": "unrecorded-foreign-thread" if unsafe_proof == "foreign_thread" else refused_thread,
692+
"turn_id": original["upstream_turn_id"], "only_original_user_item": unsafe_proof != "observed_effects",
693+
"codex_error_info": "usageLimitExceeded", "quota_available": True, "quota_observed_at": time.time()}
694+
695+
monkeypatch.setattr(CodexAppServerAdapter, "failed_request_observation", staticmethod(observe))
696+
runtime._steward_monitor_next_check.clear()
697+
assert pump_steward_monitors(runtime) == []
698+
assert len(calls) == 1 and observed
699+
assert {path.name: path.read_bytes() for path in turn_folder.glob("*.json")} == before
700+
assert (journal.read_bytes(), store.messages(sid), capture.read_bytes()) == (frozen, messages, model_calls)
701+
assert reports.health(binding["binding_id"])["execution_failed"]
702+
assert not reports.health(binding["binding_id"])["publication_verified"]
703+
704+
637705
@pytest.mark.parametrize("provider", ["file", "sqlite"])
638706
@pytest.mark.parametrize("change", ["unrelated_input", "read_counter", "queued_input", "binding_scope",
639707
"original_changed", "original_changed_after_identity"])

0 commit comments

Comments
 (0)