Skip to content

Commit 26ccef7

Browse files
authored
Merge pull request #7754 from lllluull/codex/context-read-diagnostics
fix(context): preserve typed errors in capture reads
2 parents 2136701 + 1206f5f commit 26ccef7

5 files changed

Lines changed: 145 additions & 4 deletions

File tree

‎docs/reference/required-work-context.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -862,6 +862,16 @@ not renumber arguments. Inspect the resolved prefix before that token in the
862862
same capture; malformed pointers need syntax repair first. Diagnostics never
863863
echo the pointer or task values, and no part of a rejected batch is delivered.
864864

865+
Reader failures preserve the runtime's `error_kind` and `diagnostic_code` so
866+
programs need not parse `reason`. Selector rejections use `request_rejected`
867+
with `context_selection_invalid_pointer`, `context_selection_invalid_index`
868+
or `context_selection_missing_pointer`. Repair the pointer syntax or inspect
869+
the known parent in the same capture, then retry the corrected batch. Other
870+
runtime failures retain their own classification; startup failures retain
871+
their diagnostic code. These failures do not require restoring a healthy
872+
capture. Missing or damaged capture files still fail closed through the
873+
original file/digest checks. Reading again never reruns admission.
874+
865875
The `context_capture_index_v1` view shares the digest-bound pagination contract.
866876
An expanded index includes its `list_depth`; `next_command` preserves the depth,
867877
selectors and both hashes. Changing depth rejects the prior view's continuation.
@@ -905,6 +915,13 @@ pointer 从原始摘要绑定的 capture 批量读取详情。提供已有 `--ca
905915
路径前缀;语法错误需先修正 pointer。错误信息不回显路径或任务正文,被拒绝的
906916
批次不会返回部分内容。
907917

918+
读取失败保留 runtime 的 `error_kind` 与 `diagnostic_code`,程序无需解析 `reason`。
919+
选择错误使用 `request_rejected`,原因码分别为 `context_selection_invalid_pointer`、
920+
`context_selection_invalid_index` 或 `context_selection_missing_pointer`。
921+
修正路径语法或在同一 capture 中检查已知父节点,再重试修正后的批次。其他 runtime
922+
故障保留自身分类;启动故障保留原诊断码。这些故障不要求恢复健康的 capture。
923+
文件缺失或损坏仍由原文件/摘要检查拒绝,重新读取不会重新准入。
924+
908925
`context_capture_index_v1` 沿用双摘要分页;展开的目录包含 `list_depth`,
909926
`next_command` 保留深度、路径和两个摘要。更改深度会拒绝旧视图的续读,目录 cursor
910927
也不能用作正文 cursor。遇到输出截断或缺页,用足够的输出预算恢复同一 capture

‎loopx/cli_commands/quota_capture.py‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,10 +197,20 @@ def read_context_capture(args: argparse.Namespace, *, presentation: dict[str, An
197197
except (OSError, ValueError, RecursionError, EffectRuntimeRemoteError, EffectRuntimeStartupError) as exc:
198198
# Recovery is presentation-only: keep failures separate from quota's
199199
# collection error path and retain the existing receipt/capture.
200-
return {"ok": False, "schema_version": "context_capture_page_v1",
200+
result = {"ok": False, "schema_version": "context_capture_page_v1",
201201
"reason": str(exc) if isinstance(exc, (ValueError, EffectRuntimeRemoteError, EffectRuntimeStartupError))
202202
else "original capture could not be read",
203203
"recovery": "Restore the original digest-bound capture; no guard, admission or spend was performed."}
204+
if isinstance(exc, (EffectRuntimeRemoteError, EffectRuntimeStartupError)):
205+
result["diagnostic_code"] = exc.diagnostic_code
206+
result["recovery"] = ("Resolve the reported runtime failure, then retry reading the same digest-bound capture; "
207+
"no guard, admission or spend was performed.")
208+
if isinstance(exc, EffectRuntimeRemoteError):
209+
result["error_kind"] = exc.error_kind
210+
if exc.error_kind == "request_rejected":
211+
result["recovery"] = ("Correct the rejected read request; for unknown fields use --list on a known parent. "
212+
"Keep the original capture and digest; no guard, admission or spend was performed.")
213+
return result
204214

205215

206216
def native_context_capture_view(projected: dict[str, Any], directory: Path, *,

‎loopx/control_plane/quota/context_selection.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,20 +22,23 @@ export function capturedContextSelection(request: JsonObject): JsonObject {
2222
const selections = pointers.map(pointer => {
2323
const argument = `--select argument ${argumentsByPointer.get(pointer)}`;
2424
if (pointer !== "" && !pointer.startsWith("/") || /~(?:[^01]|$)/.test(pointer))
25-
throw new EffectRuntimeRequestError(`context selection requires RFC 6901 pointers (${argument}; positions are 1-based)`);
25+
throw new EffectRuntimeRequestError(`context selection requires RFC 6901 pointers (${argument}; positions are 1-based)`,
26+
"context_selection_invalid_pointer");
2627
const tokens = pointer === "" ? [] : pointer.slice(1).split("/").map(token => token.replace(/~1/g, "/").replace(/~0/g, "~"));
2728
const path: (string | number)[] = [];
2829
let value: unknown = context;
2930
for (const token of tokens) {
3031
if (Array.isArray(value)) {
3132
if (!/^(0|[1-9][0-9]*)$/.test(token) || !Number.isSafeInteger(Number(token)) || Number(token) >= value.length)
32-
throw new EffectRuntimeRequestError(`context selection array index is missing or invalid (${argument}, token ${path.length + 1}; positions are 1-based)`);
33+
throw new EffectRuntimeRequestError(`context selection array index is missing or invalid (${argument}, token ${path.length + 1}; positions are 1-based)`,
34+
"context_selection_invalid_index");
3335
path.push(Number(token));
3436
value = value[Number(token)];
3537
} else if (value !== null && typeof value === "object" && Object.hasOwn(value, token)) {
3638
path.push(token);
3739
value = (value as JsonObject)[token];
38-
} else throw new EffectRuntimeRequestError(`context selection pointer does not exist (${argument}, token ${path.length + 1}; positions are 1-based)`);
40+
} else throw new EffectRuntimeRequestError(`context selection pointer does not exist (${argument}, token ${path.length + 1}; positions are 1-based)`,
41+
"context_selection_missing_pointer");
3942
}
4043
// Return the verified address, not a JS-number-coerced copy of the value.
4144
// The file adapter retains original JSON values and owns byte serialization.

‎tests/control_plane/test_context_capture_selection.py‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
from tests.control_plane.codex_checkpoint_fixture import NativeContextReader, last_context_page
1010
from loopx.cli_commands.quota_capture import read_context_capture
11+
from loopx.control_plane.effect_runtime import EffectRuntimeRemoteError, EffectRuntimeStartupError
1112
from loopx.control_plane.turn_driver.decision_capture import capture_page_range
1213
from test_quota_settlement_cli import _run_cli
1314

@@ -276,3 +277,92 @@ def test_cli_missing_batch_pointer_identifies_original_argument_without_source_l
276277
assert f"--select argument 3, token {token}" in result["reason"]
277278
assert pointer not in result["reason"] and "stop if unavailable" not in json.dumps(result)
278279
assert path.read_bytes() == raw and not registry.exists() and not runtime.exists()
280+
281+
282+
def test_cli_repairs_missing_selection_using_typed_error_and_same_capture(tmp_path):
283+
path, raw, original = fixture_capture(tmp_path)
284+
registry, runtime = tmp_path / "absent.json", tmp_path / "absent-runtime"
285+
command = ["quota", "context-read", "--capture-file", str(path),
286+
"--capture-sha256", hashlib.sha256(raw).hexdigest()]
287+
code, failure = _run_cli(registry, runtime, *command,
288+
"--select", "/large", "--select", "/rows/0/missing", cwd=tmp_path)
289+
assert code != 0 and failure["ok"] is False and "content" not in failure
290+
assert failure["error_kind"] == "request_rejected"
291+
assert failure["diagnostic_code"] == "context_selection_missing_pointer"
292+
assert "--list" in failure["recovery"] and "Restore" not in failure["recovery"]
293+
# Branch on the typed cause, not wording in reason; discover and retry
294+
# against the original capture without another guard or admission.
295+
code, index = _run_cli(registry, runtime, *command, "--select", "/rows/0", "--list", cwd=tmp_path)
296+
assert code == 0 and index["ok"] and index["eof"], index
297+
fields = json.loads(index["content"])["selections"][0]["fields"]
298+
pointer = next(field["pointer"] for field in fields if field["pointer"] == "/rows/0/tail")
299+
code, selected = _run_cli(registry, runtime, *command, "--select", pointer, cwd=tmp_path)
300+
assert code == 0 and selected["ok"] and selected["eof"], selected
301+
assert json.loads(selected["content"])["selections"] == [
302+
{"pointer": pointer, "value": original["rows"][0]["tail"]}]
303+
assert capture_page_range(selected, raw=raw, digest=selected["sha256"]) is None
304+
assert path.read_bytes() == raw and not registry.exists() and not runtime.exists()
305+
306+
307+
@pytest.mark.parametrize("kind,code", [
308+
("request_rejected", "request_too_large"),
309+
("io_transient", "io_busy"),
310+
("io_permanent", "io_permission_denied"),
311+
("internal_failure", "unexpected_handler_error"),
312+
])
313+
def test_reader_preserves_runtime_diagnostics_without_parsing_reason(tmp_path, monkeypatch, kind, code):
314+
from loopx.control_plane.quota import turn_envelope
315+
316+
path, raw, _ = fixture_capture(tmp_path)
317+
318+
def fail(*_args, **_kwargs):
319+
raise EffectRuntimeRemoteError("same opaque reason", error_kind=kind, diagnostic_code=code)
320+
321+
monkeypatch.setattr(turn_envelope, "_turn_envelope_result", fail)
322+
result = read_context_capture(args(path, raw))
323+
assert result["ok"] is False and "content" not in result and "next_command" not in result
324+
assert result["error_kind"] == kind and result["diagnostic_code"] == code
325+
assert result["reason"] == "same opaque reason"
326+
assert "Restore" not in result["recovery"]
327+
assert ("--list" in result["recovery"]) is (kind == "request_rejected")
328+
assert path.read_bytes() == raw
329+
330+
331+
def test_runtime_startup_failure_does_not_request_capture_restoration(tmp_path, monkeypatch):
332+
from loopx.control_plane.quota import turn_envelope
333+
334+
path, raw, _ = fixture_capture(tmp_path)
335+
336+
def fail(*_args, **_kwargs):
337+
raise EffectRuntimeStartupError("runtime unavailable", diagnostic_code="runtime_startup_timeout")
338+
339+
monkeypatch.setattr(turn_envelope, "_turn_envelope_result", fail)
340+
result = read_context_capture(args(path, raw))
341+
assert result["ok"] is False and "content" not in result
342+
assert result["diagnostic_code"] == "runtime_startup_timeout"
343+
assert "runtime" in result["recovery"] and "Restore" not in result["recovery"]
344+
assert path.read_bytes() == raw
345+
346+
347+
@pytest.mark.parametrize("damage", ["missing", "digest", "json"])
348+
def test_capture_failure_cannot_be_repaired_as_a_selector_error(tmp_path, monkeypatch, damage):
349+
from loopx.control_plane.quota import turn_envelope
350+
351+
path, raw, _ = fixture_capture(tmp_path)
352+
request = args(path, raw)
353+
if damage == "missing":
354+
path.unlink()
355+
elif damage == "digest":
356+
path.write_bytes(b"{}")
357+
else:
358+
path.write_bytes(b"{broken")
359+
request.capture_sha256 = hashlib.sha256(path.read_bytes()).hexdigest()
360+
361+
def unexpected(*_args, **_kwargs):
362+
pytest.fail("invalid captures must not reach selection")
363+
364+
monkeypatch.setattr(turn_envelope, "_turn_envelope_result", unexpected)
365+
result = read_context_capture(request)
366+
assert result["ok"] is False and "content" not in result and "next_command" not in result
367+
assert "diagnostic_code" not in result and "error_kind" not in result
368+
assert "Restore the original digest-bound capture" in result["recovery"]

‎tests/control_plane_ts/context_selection.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import assert from "node:assert/strict";
22
import {test} from "node:test";
33
import {evaluateTurnEnvelope} from "../../loopx/control_plane/quota/turn_envelope.ts";
4+
import {effectRuntimeErrorPayload} from "../../loopx/control_plane/effect_runtime_errors.ts";
45

56
const select = (context: object, pointers: unknown) => evaluateTurnEnvelope({operation: "context_select", context, select: pointers});
67

@@ -70,3 +71,23 @@ test("selection failures identify original argument and token without echoing co
7071
}
7172
assert.throws(() => select(context, ["/z", "secret-".repeat(1000)]), /--select argument 2/);
7273
});
74+
75+
test("selection failures retain machine-readable causes at the runtime boundary", () => {
76+
const context = {rows: [{stop: "private-value"}]};
77+
for (const [pointer, code] of [
78+
["rows", "context_selection_invalid_pointer"],
79+
["/~2", "context_selection_invalid_pointer"],
80+
["/rows/01", "context_selection_invalid_index"],
81+
["/rows/9", "context_selection_invalid_index"],
82+
["/rows/0/missing", "context_selection_missing_pointer"],
83+
["/toString", "context_selection_missing_pointer"],
84+
]) {
85+
assert.throws(() => select(context, ["/rows", pointer]), (error: unknown) => {
86+
const failure = effectRuntimeErrorPayload(error);
87+
assert.equal(failure.kind, "request_rejected");
88+
assert.equal(failure.code, code);
89+
assert.ok(!failure.message.includes(pointer) && !failure.message.includes("private-value"));
90+
return true;
91+
});
92+
}
93+
});

0 commit comments

Comments
 (0)