diff --git a/loopx/chat_store.py b/loopx/chat_store.py index c3c42ac5d8..84bf665b75 100644 --- a/loopx/chat_store.py +++ b/loopx/chat_store.py @@ -42,6 +42,7 @@ _opaque_id, _read_json, ) +from .control_plane.runtime.time import chronology_key from .file_lock import exclusive_file_lock, try_exclusive_file_lock, write_json_atomic @@ -76,6 +77,12 @@ def _instant(value: Any) -> datetime | None: return None +def _session_recency_key(session: dict[str, object]) -> tuple[int, datetime, str]: + valid, timestamp, raw = chronology_key(session.get("updated_at")) + # Session discovery order remains the tie break for equal instants. + return valid, timestamp, "" if valid else raw + + def _upstream_id(value: Any) -> str: token = str(value or "").strip() if not token or len(token) > 1024 or any(ord(character) < 32 for character in token): @@ -682,7 +689,7 @@ def latest_session( agent_id=agent_id, channel_id=channel_id, ) - return max(candidates, key=lambda item: str(item.get("updated_at") or ""), default=None) + return max(candidates, key=_session_recency_key, default=None) def resumable_session_candidates( self, @@ -738,7 +745,7 @@ def list_sessions(self, *, goal_id: str | None = None, agent_id: str | None = No channel_id: str | None = None) -> list[dict[str, Any]]: metadata = self.iter_session_metadata(goal_id=goal_id, agent_id=agent_id, channel_id=channel_id) rows = (self.public_session(payload) for _, payload in metadata) - return sorted(rows, key=lambda item: str(item.get("updated_at") or ""), reverse=True) + return sorted(rows, key=_session_recency_key, reverse=True) def iter_session_metadata(self, *, goal_id: str | None = None, agent_id: str | None = None, channel_id: str | None = None) -> Iterator[tuple[Path, dict[str, Any]]]: diff --git a/loopx/control_plane/goals/chat_session_lifecycle.ts b/loopx/control_plane/goals/chat_session_lifecycle.ts index 8d3bbea924..e8c995f0ed 100644 --- a/loopx/control_plane/goals/chat_session_lifecycle.ts +++ b/loopx/control_plane/goals/chat_session_lifecycle.ts @@ -1,6 +1,7 @@ import type { JsonObject } from "../effect_program.ts"; import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts"; import { assertNever, jsonObject } from "../runtime_decode.ts"; +import { parseTodoTimestampMicros } from "../runtime_timestamp.ts"; import { parseExactGoalRef, type ExactGoalRef, @@ -211,10 +212,18 @@ function decideSelection( candidate.kind === "exact" && goalRefsEqual(candidate.goalRef, currentGoalRef) ) - .sort((left, right) => - right.updatedAt.localeCompare(left.updatedAt) - || right.sessionId.localeCompare(left.sessionId) - )[0]; + .map((session) => ({ session, instant: parseTodoTimestampMicros(session.updatedAt.trim()) })) + .sort((left, right) => { + if (left.instant !== right.instant) { + if (left.instant === null) return 1; + if (right.instant === null) return -1; + return left.instant < right.instant ? 1 : -1; + } + const byUnknownTime = left.instant === null + ? right.session.updatedAt.localeCompare(left.session.updatedAt) + : 0; + return byUnknownTime || right.session.sessionId.localeCompare(left.session.sessionId); + })[0]?.session; return current ? { kind: "reuse", diff --git a/regression/ChatSessionRecency.lean b/regression/ChatSessionRecency.lean new file mode 100644 index 0000000000..66d49e9763 --- /dev/null +++ b/regression/ChatSessionRecency.lean @@ -0,0 +1,87 @@ +import Std + +/- +Run with Lean 4.22.0 using +`lean -DwarningAsError=true regression/ChatSessionRecency.lean`. + +The model combines the existing Goal, Agent, channel and resumability +filters with the optional exact Goal-instance filter. Parsed update times +are UTC microseconds. The tie rank abstracts source order for the Python +store and Session ID order for the TypeScript selector. Unreadable times +keep their relative lexical order after dated Sessions. The regressions +exercise the actual timestamp parsers and both selection paths. +-/ + +namespace ChatSessionRecency + +structure Scope where + goal : Nat + agent : Nat + channel : Nat + deriving DecidableEq + +structure Session where + scope : Scope + instanceId : Nat + resumable : Bool + time : Option Int + rawRank : Nat + tieRank : Nat + +def eligible (scope : Scope) (instanceId : Option Nat) (session : Session) : Bool := + decide (session.scope = scope ∧ session.resumable = true ∧ + (instanceId = none ∨ instanceId = some session.instanceId)) + +def newerOrTied (a b : Session) : Bool := + match a.time, b.time with + | some left, some right => decide (right < left ∨ (left = right ∧ b.tieRank ≤ a.tieRank)) + | some _, none => true + | none, some _ => false + | none, none => + decide (b.rawRank < a.rawRank ∨ (a.rawRank = b.rawRank ∧ b.tieRank ≤ a.tieRank)) + +def latest (scope : Scope) (instanceId : Option Nat) (sessions : List Session) : Option Session := + ((sessions.filter (eligible scope instanceId)).mergeSort newerOrTied).head? + +private theorem recency_sorted (sessions : List Session) : + (sessions.mergeSort newerOrTied).Pairwise (fun a b => newerOrTied a b = true) := by + apply List.sorted_mergeSort + · rintro ⟨s, i, x, a, ar, atie⟩ ⟨t, j, y, b, br, btie⟩ ⟨u, k, z, c, cr, ctie⟩ hab hbc + cases a <;> cases b <;> cases c <;> simp [newerOrTied] at * <;> omega + · rintro ⟨s, i, x, a, ar, atie⟩ ⟨t, j, y, b, br, btie⟩ + cases a <;> cases b <;> simp [newerOrTied, Bool.or_eq_true] <;> omega + +theorem latest_is_resumable_and_within_scope (scope : Scope) (instanceId : Option Nat) + (sessions : List Session) (selected : Session) (found : latest scope instanceId sessions = some selected) : + selected ∈ sessions ∧ selected.scope = scope ∧ selected.resumable = true ∧ + (instanceId = none ∨ instanceId = some selected.instanceId) := by + obtain ⟨tail, head⟩ := List.head?_eq_some_iff.mp found + have member : selected ∈ (sessions.filter (eligible scope instanceId)).mergeSort newerOrTied := by + simp [head] + obtain ⟨stored, accepted⟩ := List.mem_filter.mp (List.mem_mergeSort.mp member) + exact ⟨stored, by simpa [eligible] using accepted⟩ + +theorem latest_precedes_all_eligible (scope : Scope) (instanceId : Option Nat) + (sessions : List Session) (selected : Session) (found : latest scope instanceId sessions = some selected) + (other : Session) (stored : other ∈ sessions) (accepted : eligible scope instanceId other = true) : + newerOrTied selected other = true := by + obtain ⟨tail, head⟩ := List.head?_eq_some_iff.mp found + have ordered := recency_sorted (sessions.filter (eligible scope instanceId)) + rw [head, List.pairwise_cons] at ordered + have member : other ∈ (sessions.filter (eligible scope instanceId)).mergeSort newerOrTied := + List.mem_mergeSort.mpr (List.mem_filter.mpr ⟨stored, accepted⟩) + rw [head, List.mem_cons] at member + rcases member with rfl | tailMember + · cases time : other.time <;> simp [newerOrTied, time] + · exact ordered.1 other tailMember + +theorem old_text_order_can_choose_the_earlier_session : + "2026-02-03T10:00:00Z" > "2026-02-03T10:00:00.000001Z" ∧ + newerOrTied ⟨⟨0, 0, 0⟩, 0, true, some 1, 0, 0⟩ + ⟨⟨0, 0, 0⟩, 0, true, some 0, 1, 1⟩ = true := by decide + +#print axioms latest_is_resumable_and_within_scope +#print axioms latest_precedes_all_eligible +#print axioms old_text_order_can_choose_the_earlier_session + +end ChatSessionRecency diff --git a/tests/control_plane_ts/chat_session_lifecycle.test.ts b/tests/control_plane_ts/chat_session_lifecycle.test.ts index b4635aab75..67ecd21577 100644 --- a/tests/control_plane_ts/chat_session_lifecycle.test.ts +++ b/tests/control_plane_ts/chat_session_lifecycle.test.ts @@ -68,6 +68,55 @@ test("selection creates a new exact session when only stale state exists", () => ); }); +test("selection compares exact instants within the current Goal instance", () => { + assert.deepEqual( + decideChatSessionLifecycle({ + operation: "select", + profile_id: "source_session_v1", + current_goal_ref: goalB, + candidates: [ + session("stale", goalA, "2026-09-26T04:00:00Z"), + session("offset", goalB, "2026-09-26T09:00:00+08:00"), + session("whole", goalB, "2026-09-26T01:00:00Z"), + session("fraction", goalB, "2026-09-26T01:00:00.000001Z"), + ], + }), + { kind: "reuse", session_id: "fraction", goal_ref: goalB }, + ); +}); + +test("selection keeps the Session ID tie break for equivalent encodings", () => { + assert.deepEqual( + decideChatSessionLifecycle({ + operation: "select", + profile_id: "source_session_v1", + current_goal_ref: goalB, + candidates: [ + session("session-a", goalB, "2026-09-26T09:00:00+08:00"), + session("session-z", goalB, "2026-09-26T01:00:00Z"), + ], + }), + { kind: "reuse", session_id: "session-z", goal_ref: goalB }, + ); +}); + +test("selection retains the legacy order when update times are unreadable", () => { + const legacyTimes = [ + session("opaque-a", goalB, "legacy-a"), + session("opaque-b", goalB, "legacy-b"), + ]; + const request = { + operation: "select", + profile_id: "source_session_v1", + current_goal_ref: goalB, + }; + assert.deepEqual(decideChatSessionLifecycle({ ...request, candidates: legacyTimes }), + { kind: "reuse", session_id: "opaque-b", goal_ref: goalB }); + assert.deepEqual(decideChatSessionLifecycle({ + ...request, candidates: [...legacyTimes, session("dated", goalB)], + }), { kind: "reuse", session_id: "dated", goal_ref: goalB }); +}); + test("new work requires the session GoalRef to be current", () => { const base = { profile_id: "source_session_v1", diff --git a/tests/test_chat_codex_home.py b/tests/test_chat_codex_home.py index d5262b3b67..4599fdd577 100644 --- a/tests/test_chat_codex_home.py +++ b/tests/test_chat_codex_home.py @@ -42,6 +42,72 @@ def legacy(runtime): ) +@pytest.mark.parametrize( + "older_stamp", + ["2026-02-03T10:00:00Z", "2026-02-03T18:00:00+08:00"], + ids=["whole-second", "utc-offset"], +) +def test_chat_lists_and_resumes_sessions_by_scoped_update_time(tmp_path, monkeypatch, older_stamp): + from urllib.parse import urlencode + + from loopx.chat_server import ChatHTTPServer, ChatRequestHandler + + runtime = controller(tmp_path, monkeypatch) + store = runtime.store + scope = {"goal_id": "fixture", "agent_id": "codex", "channel_id": "goal.fixture"} + + def add(session_id, stamp, **scope_override): + with monkeypatch.context() as clock: + clock.setattr("loopx.chat_store.utc_now", lambda: stamp) + return store.create_session( + **{**scope, **scope_override}, session_id=session_id, + upstream_thread_id="fixture-thread", adapter_kind="codex_app_server", + upstream_mode="chat", + ) + + older = add("session-older", older_stamp) + tied = add("session-tied", "2026-02-03T10:00:00+00:00") + later = add("session-later", "2026-02-03T10:00:00.000001Z") + closed = add("session-closed", "2026-02-03T13:00:00Z") + with monkeypatch.context() as clock: + clock.setattr("loopx.chat_store.utc_now", lambda: "2026-02-03T13:00:00Z") + store.update_session(closed["session_id"], status="closed") + add("other-goal", "2026-02-03T23:00:00Z", goal_id="other") + add("other-agent", "2026-02-03T23:00:00Z", agent_id="other") + add("other-channel", "2026-02-03T23:00:00Z", channel_id="task.other") + tied_ids = {older["session_id"], tied["session_id"]} + tie_order = [ + row["session_id"] for row in store.session_candidates(**scope) + if row["session_id"] in tied_ids + ] + + server = ChatHTTPServer(("127.0.0.1", 0), ChatRequestHandler) + server.chat_store, server.verbose = store, False + worker = threading.Thread(target=server.serve_forever, daemon=True) + worker.start() + connection = http.client.HTTPConnection("127.0.0.1", server.server_port, timeout=10) + try: + connection.request("GET", "/api/chat/sessions?" + urlencode(scope)) + response = connection.getresponse() + payload = json.loads(response.read()) + selected, resumed = runtime.open_session( + goal_id=scope["goal_id"], agent_id=scope["agent_id"], + work_dir=tmp_path, objective="Synthetic resume", mode="resume_latest", + ) + assert response.status == 200, payload + assert [row["session_id"] for row in payload["sessions"]] == [ + closed["session_id"], later["session_id"], *tie_order, + ] + assert resumed and selected["session_id"] == later["session_id"] + assert len(store.list_sessions()) == 7 + finally: + connection.close() + server.shutdown() + server.server_close() + worker.join() + runtime.close() + + def test_model_discovery_uses_the_same_home_as_runtime_not_ambient_provider(tmp_path, monkeypatch): runtime = controller(tmp_path, monkeypatch) bound = tmp_path / "bound"