diff --git a/loopx/chat/ingress.py b/loopx/chat/ingress.py index 4d1540691d..89a3ae7645 100644 --- a/loopx/chat/ingress.py +++ b/loopx/chat/ingress.py @@ -13,6 +13,7 @@ from ..chat import require_matching_message_replay, require_matching_replay from ..file_lock import exclusive_file_lock from ..capabilities.native_chat.file_discovery import FileChatDiscovery +from ..control_plane.runtime.time import chronology_key if TYPE_CHECKING: from ..capabilities.native_chat.conversation_bindings import ChatConversationBindings @@ -275,9 +276,9 @@ def read(path): selected = set(queued_chat_turn_ids(rows, active_turn_id, include_reserved=include_reserved, capacity_at=capacity_at)) return sorted( [row for row in rows if row["turn_id"] in selected], - key=lambda item: ( - str(item.get("created_at") or ""), - str(item.get("turn_id") or ""), + key=lambda row: ( + chronology_key(row.get("created_at")), + str(row.get("turn_id") or ""), ), ) diff --git a/regression/ChatQueuedTurnOrder.lean b/regression/ChatQueuedTurnOrder.lean new file mode 100644 index 0000000000..c8b8f963eb --- /dev/null +++ b/regression/ChatQueuedTurnOrder.lean @@ -0,0 +1,100 @@ +import Std + +/- +Run with Lean 4.22.0: `lean -DwarningAsError=true regression/ChatQueuedTurnOrder.lean`. + +`selected` represents the Core queue selection for a specific read. +`eligible` represents the later checks under a fixed, uncontended claim. +`time` is the parsed UTC instant in microseconds. Raw timestamp and Turn ID +ranks represent Python string order. The HTTP and store regression covers +actual parsing, persistence, and claim transitions. +-/ + +namespace ChatQueuedTurnOrder + +structure Turn where + selected : Bool + eligible : Bool + time : Option Int + rawRank : Nat + idRank : Nat + +abbrev tieBeforeOrAt (a b : Turn) : Prop := + a.rawRank < b.rawRank ∨ (a.rawRank = b.rawRank ∧ a.idRank ≤ b.idRank) + +def beforeOrAt (a b : Turn) : Bool := + match a.time, b.time with + | some left, some right => decide (left < right ∨ (left = right ∧ tieBeforeOrAt a b)) + | none, some _ => true + | some _, none => false + | none, none => decide (tieBeforeOrAt a b) + +def readback (rows : List Turn) : List Turn := + (rows.filter Turn.selected).mergeSort beforeOrAt + +def candidates (rows : List Turn) : List Turn := + (readback rows).filter Turn.eligible + +def claim (rows : List Turn) : Option Turn := + (candidates rows).head? + +theorem readback_keeps_exactly_the_selected_turns (rows : List Turn) : + (readback rows).Perm (rows.filter Turn.selected) := + List.mergeSort_perm _ _ + +theorem readback_is_ordered (rows : List Turn) : + (readback rows).Pairwise (fun a b => beforeOrAt a b = true) := by + unfold readback + apply List.sorted_mergeSort + · rintro ⟨_, _, a, ar, ai⟩ ⟨_, _, b, br, bi⟩ ⟨_, _, c, cr, ci⟩ hab hbc + cases a <;> cases b <;> cases c <;> simp [beforeOrAt, tieBeforeOrAt] at * <;> omega + · rintro ⟨_, _, a, ar, ai⟩ ⟨_, _, b, br, bi⟩ + cases a <;> cases b <;> simp [beforeOrAt, tieBeforeOrAt, Bool.or_eq_true] <;> omega + +theorem candidate_membership (rows : List Turn) (turn : Turn) : + turn ∈ candidates rows ↔ turn ∈ rows ∧ turn.selected = true ∧ turn.eligible = true := by + rw [candidates, List.mem_filter, (readback_keeps_exactly_the_selected_turns rows).mem_iff, + List.mem_filter] + exact and_assoc + +theorem claim_selects_an_eligible_turn (rows : List Turn) (first : Turn) + (claimed : claim rows = some first) : + first ∈ rows ∧ first.selected = true ∧ first.eligible = true := by + apply (candidate_membership rows first).mp + cases found : candidates rows with + | nil => simp [claim, found] at claimed + | cons head tail => + have same : head = first := by simpa [claim, found] using claimed + simp [same] + +theorem claim_has_no_earlier_eligible_instant (rows : List Turn) (first later : Turn) + (claimed : claim rows = some first) + (present : later ∈ rows) (selected : later.selected = true) (eligible : later.eligible = true) + (firstTime laterTime : Int) + (firstParsed : first.time = some firstTime) (laterParsed : later.time = some laterTime) : + firstTime ≤ laterTime := by + have member := (candidate_membership rows later).mpr ⟨present, selected, eligible⟩ + have sorted : (candidates rows).Pairwise (fun a b => beforeOrAt a b = true) := + (readback_is_ordered rows).filter _ + cases found : candidates rows with + | nil => simp [claim, found] at claimed + | cons head tail => + have same : head = first := by simpa [claim, found] using claimed + rw [found, same] at member sorted + rcases List.mem_cons.mp member with equal | inTail + · have sameTime : firstTime = laterTime := by simpa [equal, firstParsed] using laterParsed + omega + · have ordered := (List.pairwise_cons.mp sorted).1 later inTail + simp only [beforeOrAt, firstParsed, laterParsed, decide_eq_true_eq] at ordered + omega + +theorem text_sort_can_claim_the_newer_turn_first : + "2026-02-03T10:00:00.000001Z" < "2026-02-03T10:00:00Z" ∧ + beforeOrAt ⟨true, true, some 0, 1, 0⟩ ⟨true, true, some 1, 0, 1⟩ = true := by decide + +#print axioms readback_keeps_exactly_the_selected_turns +#print axioms claim_selects_an_eligible_turn +#print axioms claim_has_no_earlier_eligible_instant +#print axioms text_sort_can_claim_the_newer_turn_first + +end ChatQueuedTurnOrder diff --git a/tests/presentation/test_chat_turn_queue.py b/tests/presentation/test_chat_turn_queue.py index f71a98180c..a06d799517 100644 --- a/tests/presentation/test_chat_turn_queue.py +++ b/tests/presentation/test_chat_turn_queue.py @@ -297,6 +297,48 @@ def test_queue_read_is_ordered_bounded_read_only_and_full_input_remains_readable assert request(f"/api/chat/sessions/{sid}/queue")[0] == 503 +def test_mixed_queue_timestamps_keep_readback_and_claim_in_utc_order(ordinary): # noqa: F811 + store, _runtime, contexts, request, capture, *_ = ordinary + project = contexts.resolve(contexts.available()[0]["project_ref"]) + sid = store.create_session( + goal_id=None, agent_id="codex", adapter_kind="codex_app_server", + upstream_thread_id="fixture", upstream_mode="chat", + channel_id=project["channel_id"], project_context=project["context"], + )["session_id"] + timestamps = { + "expired": "2000-01-01T00:00:00Z", + "earlier": "2026-02-03T10:00:00Z", + "later": "2026-02-03T10:00:00.000001Z", + "equal-offset": "2026-02-03T18:00:00+08:00", + } + turns = {} + for client_id, stamp in timestamps.items(): + turn, created = store.create_queued_turn( + sid, client_turn_id=client_id, message=client_id, origin="web", + ) + assert created + turns[client_id] = turn["turn_id"] + path = store._turn_path(sid, turn["turn_id"]) + path.write_text(json.dumps({**turn, "created_at": stamp}), encoding="utf-8") + store.update_turn(sid, turns["expired"], expires_at="2000-01-01T00:00:01Z") + + code, snapshot = request(f"/api/chat/sessions/{sid}/queue") + assert code == 200 and snapshot["active_turn_id"] is None + claimed = store.claim_next_queued_turn(sid, host_claim_id="fixture-claim") + assert claimed is not None + + assert ( + [(row["turn_id"], row["created_at"]) for row in snapshot["turns"]], + claimed["turn_id"], + ) == ( + [(turns[key], timestamps[key]) for key in ("expired", "earlier", "equal-offset", "later")], + turns["earlier"], + ) + assert store.load_session(sid)["active_turn_id"] == turns["earlier"] + assert store.load_turn(sid, turns["expired"])["status"] == "timed_out" + assert not capture.exists() + + def test_queued_steering_uses_original_input_once_and_replays_after_target_finished(ordinary): # noqa: F811 store, runtime, contexts, request, capture, *_ = ordinary sid, active, queued, original = held_queue(ordinary)