Repository navigation
Converge Turn session reuse on its typed policy #9144
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
cocolord
wants to merge
1
commit into
main
Choose a base branch
from
codex/mechanism-session-binding-20261120
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+269
−65
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| /** Conversation reuse policy for normal planning and original-Turn recovery. | ||
| * Persistence and Python's historical scalar codec remain at the host IO edge. | ||
| */ | ||
| import {requireJsonObject, requireStringLiteral, type JsonObject} from "../runtime_decode.ts"; | ||
| import {TURN_ROUTES} from "./turn_contract_generated.ts"; | ||
|
|
||
| const SESSION_SCHEMA = "loopx_turn_session_binding_v0"; | ||
| const CONTEXT_SCHEMA = "loopx_iteration_context_policy_v0"; | ||
|
|
||
| type ContextPolicy = { | ||
| schema_version: typeof CONTEXT_SCHEMA; | ||
| mode: "fresh" | "resume"; | ||
| scope: "iteration"; | ||
| binding_scope?: "agent"; | ||
| }; | ||
| type SessionDecision = | ||
| | {action: "none"; binding_status: "not_applicable"; context_policy: ContextPolicy} | ||
| | {action: "start_new"; binding_status?: "existing_binding_ignored" | "not_found"; context_policy: ContextPolicy} | ||
| | {action: "resume"; binding_status: "compatible"; context_policy: ContextPolicy} | ||
| | {action: "reject"; binding_status: "missing_turn_lineage" | "unsupported_schema" | "identity_mismatch"}; | ||
| type SessionPlan = {schema_version: typeof SESSION_SCHEMA} & SessionDecision; | ||
|
|
||
| export function turnSessionPlan(request: JsonObject): {session: SessionPlan; error: string | null} { | ||
| const scope = requireStringLiteral(request.session_scope, ["todo", "agent"], "session scope"); | ||
| const mode = requireStringLiteral(request.iteration_context_policy, ["fresh", "resume"], "iteration context policy"); | ||
| const route = requireStringLiteral(request.route, TURN_ROUTES, "Turn route"); | ||
| const lineage = requireJsonObject(request.lineage, "Turn lineage"); | ||
| // Lineage and binding identity are encoded by the production caller, | ||
| // including historical Python str/or values. Never trim that identity. | ||
| const fields = scope === "todo" && !(lineage.request_binding_id && mode === "fresh") | ||
| ? ["goal_id", "agent_id", "todo_id"] : ["goal_id", "agent_id"]; | ||
| const context: ContextPolicy = {schema_version: CONTEXT_SCHEMA, mode, scope: "iteration", | ||
| ...(scope === "agent" ? {binding_scope: scope} : {})}; | ||
| const result = (plan: SessionDecision, error: string | null = null): {session: SessionPlan; error: string | null} => | ||
| ({session: {schema_version: SESSION_SCHEMA, ...plan}, error}); | ||
| if (route !== "ready_for_host" && route !== "repair_required" && route !== "replan_required") { | ||
| return result({action: "none", binding_status: "not_applicable", context_policy: context}); | ||
| } | ||
| if ([...fields, "action_hash"].some(field => !lineage[field]) || | ||
| !(lineage.todo_id || lineage.replan_obligation_id || lineage.request_binding_id)) { | ||
| return result({action: "reject", binding_status: "missing_turn_lineage"}, | ||
| "host-bound routes require goal, agent, todo, and action-hash lineage"); | ||
| } | ||
| const binding = requireJsonObject(request.session_binding, "session binding"); | ||
| const hasBinding = Object.keys(binding).length > 0; | ||
| if (mode === "fresh") { | ||
| return result({action: "start_new", binding_status: hasBinding ? "existing_binding_ignored" : "not_found", | ||
| context_policy: context}); | ||
| } | ||
| if (!hasBinding) return result({action: "start_new", context_policy: context}); | ||
| if (binding.schema_version !== SESSION_SCHEMA) { | ||
| return result({action: "reject", binding_status: "unsupported_schema"}, | ||
| "unsupported LoopX Turn session binding schema"); | ||
| } | ||
| const identity = requireJsonObject(request.binding_identity_text, "encoded session identity"); | ||
| if (fields.some(field => identity[field] !== lineage[field])) { | ||
| return result({action: "reject", binding_status: "identity_mismatch"}, | ||
| "session binding does not match the current " + fields.join(", ")); | ||
| } | ||
| return result({action: "resume", binding_status: "compatible", context_policy: context}); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| """Conversation reuse does not change Turn identity or recovery authority.""" | ||
|
|
||
| from copy import deepcopy | ||
|
|
||
| import pytest | ||
|
|
||
| from loopx.control_plane.turn_driver.driver import ( | ||
| FailedTurnSessionRecoveryError, | ||
| build_loopx_turn_plan, | ||
| reconcile_failed_turn_session_request, | ||
| ) | ||
| from tests.test_loopx_turn_driver import _envelope | ||
|
|
||
|
|
||
| def _plan(envelope, **options): | ||
| return build_loopx_turn_plan(envelope, host="codex-cli", | ||
| execution_mode="isolated-headless", turn_instance_id="session-policy", **options) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize(("value", "encoded"), [ | ||
| (True, "True"), (1.0, "1.0"), (0.000001, "1e-06"), | ||
| (1152921504606846977, "1152921504606846977"), | ||
| ([True, "task"], "[True, 'task']"), | ||
| ({"name": "task", "active": True}, "{'name': 'task', 'active': True}"), | ||
| ("任务-\"quoted\"", "任务-\"quoted\""), | ||
| ]) | ||
| def test_historical_binding_codec_survives_plan_and_failed_recovery(value, encoded): | ||
| envelope = _envelope() | ||
| envelope["action"]["selected_todo"]["todo_id"] = encoded | ||
| binding = {"schema_version": "loopx_turn_session_binding_v0", | ||
| "goal_id": "fixture-goal", "agent_id": "codex-fixture", "todo_id": value} | ||
| before = deepcopy((envelope, binding)) | ||
| plan = _plan(envelope, session_scope="todo", session_binding=binding) | ||
| assert plan["ok"] and plan["session"]["action"] == "resume" | ||
| request = {"turn_envelope": envelope, "session": plan["session"], "original": "retained"} | ||
| assert reconcile_failed_turn_session_request(request, session_binding=binding) == request | ||
| assert (envelope, binding) == before | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("binding", [None, {}, {"schema_version": "future"}, | ||
| {"schema_version": "loopx_turn_session_binding_v0", "goal_id": "other"}]) | ||
| @pytest.mark.parametrize("scope", ["todo", "agent"]) | ||
| def test_fresh_ignores_old_binding_after_lineage_validation(binding, scope): | ||
| plan = _plan(_envelope(), session_scope=scope, session_binding=binding, | ||
| iteration_context_policy="fresh") | ||
| assert plan["ok"] and plan["session"] == { | ||
| "schema_version": "loopx_turn_session_binding_v0", "action": "start_new", | ||
| "binding_status": "existing_binding_ignored" if binding else "not_found", | ||
| "context_policy": {"schema_version": "loopx_iteration_context_policy_v0", | ||
| "mode": "fresh", "scope": "iteration", | ||
| **({"binding_scope": "agent"} if scope == "agent" else {})}, | ||
| } | ||
| invalid = _envelope() | ||
| invalid["agent_id"] = "" | ||
| with pytest.raises(ValueError, match="identity.agent_id must be a non-empty string"): | ||
| _plan(invalid, session_scope=scope, session_binding=binding, | ||
| iteration_context_policy="fresh") | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("binding", [None, {}, {"schema_version": "future"}]) | ||
| @pytest.mark.parametrize("scope", ["todo", "agent"]) | ||
| def test_wait_does_not_inspect_a_session(binding, scope): | ||
| envelope = _envelope(should_run=False, quiet_noop_allowed=True) | ||
| plan = _plan(envelope, session_scope=scope, session_binding=binding) | ||
| assert plan["ok"] and plan["session"] == { | ||
| "schema_version": "loopx_turn_session_binding_v0", "action": "none", | ||
| "binding_status": "not_applicable", | ||
| "context_policy": {"schema_version": "loopx_iteration_context_policy_v0", | ||
| "mode": "resume", "scope": "iteration", | ||
| **({"binding_scope": "agent"} if scope == "agent" else {})}, | ||
| } | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("value", [None, False, 0, 0.0, "", [], {}]) | ||
| def test_false_binding_identity_is_rejected_without_a_fresh_fallback(value): | ||
| envelope = _envelope() | ||
| binding = {"schema_version": "loopx_turn_session_binding_v0", | ||
| "goal_id": "fixture-goal", "agent_id": "codex-fixture", "todo_id": value} | ||
| plan = _plan(envelope, session_scope="todo", session_binding=binding) | ||
| assert not plan["ok"] and plan["session"]["binding_status"] == "identity_mismatch" | ||
| assert plan["error"] == "session binding does not match the current goal_id, agent_id, todo_id" | ||
| request = {"turn_envelope": envelope, "session": {"action": "start_new"}} | ||
| with pytest.raises(FailedTurnSessionRecoveryError) as caught: | ||
| reconcile_failed_turn_session_request(request, session_binding=binding) | ||
| assert caught.value.reason == "session_binding_identity_mismatch" | ||
| assert str(caught.value) == "failed-Turn recovery " + plan["error"] | ||
|
|
||
|
|
||
| def test_agent_scope_reuses_conversation_without_changing_original_turn_identity(): | ||
| envelope = _envelope() | ||
| binding = {"schema_version": "loopx_turn_session_binding_v0", | ||
| "goal_id": "fixture-goal", "agent_id": "codex-fixture", "todo_id": "previous-task"} | ||
| fresh = _plan(envelope, session_scope="agent") | ||
| resumed = _plan(envelope, session_scope="agent", session_binding=binding) | ||
| assert resumed["ok"] and resumed["session"]["action"] == "resume" | ||
| assert resumed["transaction"]["settlement_plan"]["identity"] == fresh["transaction"]["settlement_plan"]["identity"] | ||
| request = {"turn_envelope": envelope, "session": fresh["session"], | ||
| "transaction": fresh["transaction"]} | ||
| recovered = reconcile_failed_turn_session_request(request, session_binding=binding) | ||
| assert recovered["session"]["binding_status"] == "failed_turn_recovery" | ||
| assert recovered["transaction"] == fresh["transaction"] | ||
| assert request["session"]["action"] == "start_new" |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[P2] 保留新增 RPC 失败时的结构化恢复判定。原失败 journal 和已存会话均可读时,只让此请求丢失响应,两种 provider 的公开 inspect 都从含 retry_failed_phase 的 exit 0 变成无 recovery_decision 的 exit 1。这里的异常越过了 failed-Turn session check 的转换,所以只读操作被报成可能已提交。请让这个错误经过原恢复检查,验证不启动 Host、不写回或扣额,恢复后仍沿原身份结算一次。