Skip to content

The agent that grows with you

fix(cron): order execution, delivery and incident history by instant, not by text

alt-glitch318f6ac63f1a
diff --git a/cron/delivery_queue.py b/cron/delivery_queue.py
index 4569b1b726a..32848c2c0c4 100644
--- a/cron/delivery_queue.py
+++ b/cron/delivery_queue.py
@@ -57,7 +57,8 @@ def _prune_terminal_unlocked(conn: sqlite3.Connection) -> None:
(execution_id, terminal_status, finished_at)
SELECT execution_id, status, finished_at FROM deliveries
WHERE status IN ('delivered','failed','unknown','suppressed')
- ORDER BY finished_at, created_at, execution_id
+ ORDER BY julianday(finished_at), finished_at,
+ julianday(created_at), created_at, execution_id
LIMIT ?""",
(excess,),
)
@@ -65,7 +66,8 @@ def _prune_terminal_unlocked(conn: sqlite3.Connection) -> None:
"""DELETE FROM deliveries WHERE execution_id IN (
SELECT execution_id FROM deliveries
WHERE status IN ('delivered','failed','unknown','suppressed')
- ORDER BY finished_at, created_at, execution_id
+ ORDER BY julianday(finished_at), finished_at,
+ julianday(created_at), created_at, execution_id
LIMIT ?
)""",
(excess,),
@@ -228,9 +230,10 @@ def claim_next() -> Optional[dict]:
pid = os.getpid()
started = _process_start_time(pid)
with _transaction() as conn:
+ # created_at carries a DST-varying offset: order by instant, not text.
row = conn.execute(
"SELECT execution_id FROM deliveries WHERE status='pending' "
- "ORDER BY created_at, execution_id LIMIT 1"
+ "ORDER BY julianday(created_at), created_at, execution_id LIMIT 1"
).fetchone()
if row is None:
return None
diff --git a/cron/executions.py b/cron/executions.py
index 2f53c3b7e1c..bac8fef9acc 100644
--- a/cron/executions.py
+++ b/cron/executions.py
@@ -175,7 +175,8 @@ def _prune_unlocked(conn: sqlite3.Connection) -> None:
"""DELETE FROM executions WHERE id IN (
SELECT id FROM executions
WHERE status IN ('completed','failed','unknown')
- ORDER BY finished_at DESC, claimed_at DESC, id DESC LIMIT -1 OFFSET ?
+ ORDER BY julianday(finished_at) DESC, finished_at DESC,
+ julianday(claimed_at) DESC, claimed_at DESC, id DESC LIMIT -1 OFFSET ?
)""",
(max(0, int(MAX_TERMINAL_EXECUTIONS)),),
)
@@ -393,14 +394,17 @@ def list_executions(
clauses.append("job_id=?")
params.append(str(job_id))
if before_claimed_at is not None:
- clauses.append("claimed_at < ?")
- params.append(str(before_claimed_at))
+ # Same (instant, text) key as the ORDER BY, so a page never skips or repeats a row.
+ clauses.append("(julianday(claimed_at), claimed_at) < (julianday(?), ?)")
+ params.extend([str(before_claimed_at)] * 2)
where = " WHERE " + " AND ".join(clauses) if clauses else ""
params.append(max(1, min(int(limit), 500)))
+ # Stamps carry the local offset, which changes at DST and on a timezone change, so text order
+ # is not time order. julianday() compares instants (ms); the text breaks same-ms ties.
with _transaction() as conn:
rows = conn.execute(
"SELECT * FROM executions" + where
- + " ORDER BY claimed_at DESC, id DESC LIMIT ?",
+ + " ORDER BY julianday(claimed_at) DESC, claimed_at DESC, id DESC LIMIT ?",
params,
).fetchall()
return [dict(row) for row in rows]
@@ -422,18 +426,23 @@ def latest_execution(job_id: str) -> Optional[Dict[str, Any]]:
def latest_executions(job_ids: List[str]) -> Dict[str, Dict[str, Any]]:
- """Load latest execution for many jobs in one indexed query."""
+ """Load latest execution for many jobs in one query."""
clean = [str(job_id) for job_id in dict.fromkeys(job_ids) if job_id]
if not clean:
return {}
placeholders = ",".join("?" for _ in clean)
+ # One windowed sort: a per-row correlated ORDER BY julianday() cannot use the index and
+ # grows quadratically with history (~90 ms at 1000 rows).
with _transaction() as conn:
rows = conn.execute(
- f"""SELECT e.* FROM executions e
- WHERE e.job_id IN ({placeholders})
- AND e.id=(SELECT e2.id FROM executions e2
- WHERE e2.job_id=e.job_id
- ORDER BY e2.claimed_at DESC, e2.id DESC LIMIT 1)""",
+ f"""SELECT e.* FROM executions e WHERE e.id IN (
+ SELECT id FROM (
+ SELECT id, ROW_NUMBER() OVER (
+ PARTITION BY job_id
+ ORDER BY julianday(claimed_at) DESC, claimed_at DESC, id DESC
+ ) AS rn
+ FROM executions WHERE job_id IN ({placeholders}))
+ WHERE rn=1)""",
clean,
).fetchall()
return {row["job_id"]: dict(row) for row in rows}
diff --git a/cron/incidents.py b/cron/incidents.py
index 22a107da5ce..693e7b7550d 100644
--- a/cron/incidents.py
+++ b/cron/incidents.py
@@ -262,8 +262,11 @@ def list_incidents(state: Optional[str] = None) -> List[Dict[str, Any]]:
return []
where, params = _state_filter(state)
with _transaction() as conn:
+ # last_seen_at carries a DST-varying offset: order by instant, not text.
rows = conn.execute(
- "SELECT * FROM cron_incidents" + where + " ORDER BY last_seen_at DESC, id DESC", params
+ "SELECT * FROM cron_incidents" + where
+ + " ORDER BY julianday(last_seen_at) DESC, last_seen_at DESC, id DESC",
+ params,
).fetchall()
return [dict(row) for row in rows]
diff --git a/tests/cron/test_cron_incidents.py b/tests/cron/test_cron_incidents.py
index a1fb0669573..433d9aa4ab7 100644
--- a/tests/cron/test_cron_incidents.py
+++ b/tests/cron/test_cron_incidents.py
@@ -94,6 +94,25 @@ def test_new_failure_creates_incident_and_is_new(monkeypatch, tmp_path):
assert inc.count_incidents() == 1
+def test_incidents_list_newest_instant_first_across_dst_fall_back(monkeypatch, tmp_path):
+ """01:10-05:00 is 20 minutes after 01:50-04:00 but sorts first as text."""
+ from datetime import datetime
+ from zoneinfo import ZoneInfo
+
+ inc = _point_db(monkeypatch, tmp_path)
+ new_york = ZoneInfo("America/New_York")
+ monkeypatch.setattr(
+ inc, "_hermes_now", lambda: datetime(2026, 11, 1, 1, 50, tzinfo=new_york, fold=0)
+ )
+ earlier, _ = inc.upsert_incident("job-1", "first failure")
+ monkeypatch.setattr(
+ inc, "_hermes_now", lambda: datetime(2026, 11, 1, 1, 10, tzinfo=new_york, fold=1)
+ )
+ later, _ = inc.upsert_incident("job-2", "second failure")
+
+ assert [row["id"] for row in inc.list_incidents()] == [later, earlier]
+
+
def test_same_signature_dedups_same_incident(monkeypatch, tmp_path):
inc = _point_db(monkeypatch, tmp_path)
diff --git a/tests/cron/test_delivery_queue.py b/tests/cron/test_delivery_queue.py
index b4c56edfafa..d5858b672d4 100644
--- a/tests/cron/test_delivery_queue.py
+++ b/tests/cron/test_delivery_queue.py
@@ -24,6 +24,30 @@ def test_pending_delivery_is_claimed_and_sent_once(tmp_path, monkeypatch):
assert status["content"] == ""
+def test_pending_deliveries_are_claimed_in_instant_order_across_dst_fall_back(
+ tmp_path, monkeypatch
+):
+ """01:10-05:00 is 20 minutes after 01:50-04:00 but sorts first as text."""
+ from datetime import datetime
+ from zoneinfo import ZoneInfo
+
+ import cron.delivery_queue as queue
+
+ monkeypatch.setattr(queue, "DELIVERY_DB", tmp_path / "deliveries.db")
+ new_york = ZoneInfo("America/New_York")
+ monkeypatch.setattr(
+ queue, "_hermes_now", lambda: datetime(2026, 11, 1, 1, 50, tzinfo=new_york, fold=0)
+ )
+ queue.enqueue("exec-z-earlier", {"id": "job-1"}, "first")
+ monkeypatch.setattr(
+ queue, "_hermes_now", lambda: datetime(2026, 11, 1, 1, 10, tzinfo=new_york, fold=1)
+ )
+ queue.enqueue("exec-a-later", {"id": "job-2"}, "second")
+
+ assert queue.claim_next()["execution_id"] == "exec-z-earlier"
+ assert queue.claim_next()["execution_id"] == "exec-a-later"
+
+
def test_terminal_delivery_retention_is_bounded(tmp_path, monkeypatch):
import cron.delivery_queue as queue
diff --git a/tests/cron/test_execution_ledger.py b/tests/cron/test_execution_ledger.py
index b55857b2e68..fb8ffbf8d1b 100644
--- a/tests/cron/test_execution_ledger.py
+++ b/tests/cron/test_execution_ledger.py
@@ -490,3 +490,27 @@ def test_job_listing_exposes_latest_execution(monkeypatch, tmp_path):
listed = jobs.list_jobs(include_disabled=True)
assert listed[0]["latest_execution"]["id"] == record["id"]
assert listed[0]["latest_execution"]["status"] == "running"
+
+
+def test_history_orders_by_instant_across_dst_fall_back(monkeypatch, tmp_path):
+ """01:10-05:00 is 20 minutes after 01:50-04:00 but sorts first as text."""
+ from datetime import datetime
+ from zoneinfo import ZoneInfo
+
+ executions = _point_ledger(monkeypatch, tmp_path)
+ new_york = ZoneInfo("America/New_York")
+ first_pass = datetime(2026, 11, 1, 1, 50, tzinfo=new_york, fold=0)
+ second_pass = datetime(2026, 11, 1, 1, 10, tzinfo=new_york, fold=1)
+ monkeypatch.setattr(executions, "_hermes_now", lambda: first_pass)
+ earlier = executions.create_execution("dst-job", source="builtin")
+ monkeypatch.setattr(executions, "_hermes_now", lambda: second_pass)
+ later = executions.create_execution("dst-job", source="builtin")
+ assert later["claimed_at"] < earlier["claimed_at"]
+
+ assert executions.latest_execution("dst-job")["id"] == later["id"]
+ assert executions.latest_executions(["dst-job"])["dst-job"]["id"] == later["id"]
+ assert [r["id"] for r in executions.list_executions(job_id="dst-job")] == [
+ later["id"], earlier["id"],
+ ]
+ page = executions.list_executions(job_id="dst-job", before_claimed_at=later["claimed_at"])
+ assert [r["id"] for r in page] == [earlier["id"]]