Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions loopx/chat/ingress.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -709,5 +710,7 @@ def loopx_ingress(self, session_id: str) -> list[dict[str, Any]]:
from ..chat_store import _read_json

rows = [_read_json(path) for path in (self._session_dir(session_id) / "ingress").glob("*.json")]
return sorted((row for row in rows if row.get("mode") in {"loopx_queue", "loopx_inbox"}),
key=lambda row: (row.get("created_at", ""), row.get("client_ingress_id", "")))
return sorted(
(row for row in rows if row.get("mode") in {"loopx_queue", "loopx_inbox"}),
key=lambda row: (chronology_key(row.get("created_at")), row.get("client_ingress_id", "")),
)
78 changes: 78 additions & 0 deletions regression/ChatIngressReceiptOrder.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import Std

/-
Run with Lean 4.22.0: `lean -DwarningAsError=true regression/ChatIngressReceiptOrder.lean`.

The model of `loopx_ingress` starts after timestamp parsing. Parsed instants
are UTC microseconds. Natural ranks represent the Python string order of raw
timestamps and ingress IDs. The file-backed Chat regression exercises the
actual timestamp parser and the queue drain with a local provider substitute.
-/

namespace ChatIngressReceiptOrder

inductive Mode where
| queue | inbox | other

structure Receipt where
mode : Mode
time : Option Int
rawRank : Nat
idRank : Nat

def retained (row : Receipt) : Bool :=
match row.mode with
| .queue | .inbox => true
| .other => false

abbrev tieBeforeOrAt (a b : Receipt) : Prop :=
a.rawRank < b.rawRank ∨ (a.rawRank = b.rawRank ∧ a.idRank ≤ b.idRank)

def beforeOrAt (a b : Receipt) : 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 Receipt) : List Receipt :=
(rows.filter retained).mergeSort beforeOrAt

theorem keeps_exactly_the_retained_receipts (rows : List Receipt) :
(readback rows).Perm (rows.filter retained) :=
List.mergeSort_perm _ _

theorem readback_is_ordered (rows : List Receipt) :
(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 parsed_receipts_are_chronological (rows : List Receipt) :
(readback rows).Pairwise (fun a b =>
∀ first second, a.time = some first → b.time = some second → first ≤ second) := by
apply (readback_is_ordered rows).imp
intro a b ordered first second aTime bTime
simp only [beforeOrAt, aTime, bTime, decide_eq_true_eq] at ordered
omega

theorem equal_instants_keep_the_previous_tie_rule (instant : Int)
(a b : Receipt) (atTime : a.time = some instant) (btTime : b.time = some instant) :
beforeOrAt a b = true ↔ tieBeforeOrAt a b := by
simp [beforeOrAt, tieBeforeOrAt, atTime, btTime]

theorem text_sort_can_reverse_chronology :
"2026-02-03T10:00:00.000001Z" < "2026-02-03T10:00:00Z" ∧
beforeOrAt ⟨.queue, some 0, 1, 0⟩ ⟨.queue, some 1, 0, 1⟩ = true := by decide

#print axioms keeps_exactly_the_retained_receipts
#print axioms readback_is_ordered
#print axioms parsed_receipts_are_chronological
#print axioms equal_instants_keep_the_previous_tie_rule
#print axioms text_sort_can_reverse_chronology

end ChatIngressReceiptOrder
38 changes: 38 additions & 0 deletions tests/test_chat_loopx_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import pytest

import loopx.chat_store as chat_store
from loopx.chat_loopx_mode import TOOL
from loopx.chat_runtime import ChatRuntimeController
from loopx.chat_store import ChatSessionStore
Expand Down Expand Up @@ -316,6 +317,43 @@ def rejected(**_):
assert len(service.store.loopx_ingress(sid)) == 2


def test_retained_ingress_is_read_and_drained_in_utc_order(mode, monkeypatch):
service, sid, _, _, _ = mode
receipts = [
("earlier-z", "2026-02-03T10:00:00Z", "loopx_queue"),
("later", "2026-02-03T10:00:00.000001Z", "loopx_queue"),
("equal-offset", "2026-02-03T18:00:00+08:00", "loopx_queue"),
("earlier-a", "2026-02-03T10:00:00Z", "loopx_queue"),
("inbox", "2026-02-03T10:00:00.000002Z", "loopx_inbox"),
("live", "2026-02-03T10:00:00.000003Z", "live_steering"),
]
for ingress_id, created_at, ingress_mode in receipts:
monkeypatch.setattr(chat_store, "utc_now", lambda stamp=created_at: stamp)
service.store.create_ingress_receipt(
sid, client_ingress_id=ingress_id, mode=ingress_mode, message=ingress_id
)

queue_order = ["earlier-a", "earlier-z", "equal-offset", "later"]
assert [row["client_ingress_id"] for row in service.snapshot(sid)["ingress"]] == [
*queue_order, "inbox"
]

delivered_batches = []

def capture_steer(message, *, expected_turn_id):
delivered_batches.append((expected_turn_id, json.loads(message.split("\n", 1)[1])))

adapter = SimpleNamespace(session=SimpleNamespace(steer=capture_steer))
service.deliver_queue(sid, adapter, "fixture-turn")
service.deliver_queue(sid, adapter, "next-fixture-turn")

assert delivered_batches == [("fixture-turn", queue_order)]
assert {row["client_ingress_id"]: row["status"] for row in service.store.loopx_ingress(sid)} == {
**dict.fromkeys(queue_order, "delivered"),
"inbox": "pending",
}


def test_uncertain_queue_is_not_replayed(mode):
service, sid, _, settings, _ = mode
apply(mode, "start", settings=settings)
Expand Down
Loading