← Back to Pull requests

fix(cron): find unified-runtime cron runs by their scheduler admission #139273

Merged
unsupportedpastels merged 16 files (923 lines) on Oct 15, 2026 20:33 UTC
View on GitHub
unsupportedpastels unsupportedpastels commented on Oct 15, 2026 16:35 UTC
Author

<img src="https://v3b.fal.media/files/b/0aae8017/tU0ZVQ8chitWDT6hXuwkr_qqsazS8L.png" alt="Cron run history" width="480">

What does this PR do?

Lane 3 of package 4 (#139162) from the unified-gateway tracker #134889.

CRON-1: unified-runtime cron runs appear in run history and open (#138812)

Agent cron runs on the unified runtime get gateway-minted local- session ids. Run history only looked for the legacy cron_<job>_<YYYYmmdd_HHMMSS> ids, so Desktop couldn't list or open those runs.

  • Lookup by admission. The local- ids stay, because exact-once retry rebuilds them from the admission id. Run history now finds a job's runs through the admission the scheduler already writes for every fire, cron:<job>:<execution>. A new partial covering index, idx_session_admissions_cron_request, is in SCHEMA_SQL. Legacy runs are still found by their id.

  • Readers only read. The history and detail routes open SessionDB read-only. The gateway stays the only writer, and the queue contract is unchanged (#106742).

  • Session detail and Desktop. Session detail reports a run's job and execution. Desktop recognises cron sessions by their source rather than their id shape. Reconciliation pairs a session with its ledger attempt by execution id, so a neighbouring fire that failed before creating a session keeps its own row.

  • Execution ids containing : are refused for new admissions only. An admission made before this change keeps its exact submit/recover retry. Run history files it under its job using the stored policy record, not by splitting on the last :.

  • Output documents. An output document never records its execution, so the attempts its timestamp could match are only candidates, paired with sessions by time. The filename keeps whole seconds, so an attempt's claim time is floored to its second before matching.

  • Legacy prefix collisions. A legacy id must end in exactly YYYYmmdd_HHMMSS, so job daily no longer lists job daily_digest's runs (refs #92133).
  • Credit

  • This salvages #138968 by @dokterdok whole.

  • It credits draft #138821 by @KoNit-K, which #138968 built on. Its query was replaced, because decoding every local session's policy on each request scanned all local sessions (#138968 measured about 1.5 s at 40k sessions).

  • Both authors have Co-authored-by trailers.
  • Related Issue

    Fixes #138812

    Refs #134889 (CRON-1) · Refs #139162 · Refs #92133

    Type of Change

  • 🐛 Bug fix (non-breaking change that fixes an issue)
  • Changes Made

  • gateway/session_cron.py: the : guard applies to new admissions only; exact retry of existing identities is kept

  • hermes_state_keys.py, hermes_state_common.py, hermes_state_portability.py: admission-keyed run lookup, the partial index, policy-based job association for ambiguous ids, and the strict legacy suffix

  • hermes_cli/web_routers/cron.py, hermes_cli/web_routers/sessions.py: execution-aware reconciliation, candidate-only document matching, and execution identity in session detail

  • apps/desktop/src/app/cron/open-cron-run.ts (+ test), apps/desktop/src/app/cron/index.tsx, apps/desktop/src/app/chat/sidebar/cron-jobs-section.tsx, apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts: cron sessions recognised by source

  • Tests: tests/hermes_state/test_cron_run_sessions.py and tests/hermes_cli/test_cron_run_history_sessions.py are new; tests/hermes_state/test_hermes_state.py is extended
  • How to Test

    1. scripts/run_tests.sh tests/hermes_state/test_cron_run_sessions.py tests/hermes_cli/test_cron_run_history_sessions.py tests/hermes_state/test_hermes_state.py
    2. Without the fix, the run-history tests fail: the local- run is missing and only the legacy row is returned. Without the review fixes, 4 tests fail: a pre-upgrade fire:1 admission is refused on retry, and a same-second output document is pinned on the earlier execution (2 variants).
    3. Results:
    - 166 Python test files that touch cron run history, session_cron or admissions: 1121 passed, 0 failed, 6 skipped.
    - scripts/check: ok.
    - Desktop vitest for the cron, sidebar and prompt-action files: 779 passed, and tsc --noEmit is clean. This ran before the review fixes, which changed no Desktop files.

    An independent review pass (gpt-6-astra) returned needs changes with two findings: colon-bearing ids admitted before the upgrade lost their exact retry, and a document's guessed execution was treated as certain. Both are fixed above, each with a test that failed first.

    Known gaps

  • A cron run that compresses into a follow-on session is still listed by its first session only. That was already true on main.

  • An existing state.db gets the new index on its next writable open, which the gateway does. Until then lookups are correct but unindexed.

  • Not run through live Electron navigation.
  • Checklist

    Code

  • I've read the Contributing Guide

  • My commit messages follow Conventional Commits

  • I searched for existing PRs to make sure this isn't a duplicate (#138968 and #138821 are salvaged here with credit)

  • My PR contains only changes related to this fix/feature

  • I've run pytest tests/ -q and all tests pass. Not ticked: the full suite wasn't run. The 166 related files pass, as listed above.

  • I've added tests for my changes

  • I've tested on my platform: Linux
  • Documentation & Housekeeping

  • I've updated relevant documentation (README, docs/, docstrings) — or N/A

  • I've updated cli-config.yaml.example if I added/changed config keys — or N/A

  • I've updated CONTRIBUTING.md or AGENTS.md if I changed architecture or workflows — or N/A

  • I've considered cross-platform impact (Windows, macOS) — or N/A

  • I've updated tool descriptions/schemas if I changed tool behavior — or N/A
  • Update after review (head db1b816a)

  • Output docs are paired with ledger attempts only after sessions are known. Each attempt gets exactly one row: its session, else its output doc, else its ledger row. An overlapping attempt (for example a manual run claimed before another run's doc is written) no longer shows the wrong row or hides a failed run.

  • The partial index's WHERE is built from CRON_PRINCIPAL_ID, the substr offsets come from the prefix length, and a prefix_range() helper replaces three copies of the half-open bound.

  • The two new test files share fixtures in tests/fakes/cron_owner.py.

  • Still open, not a regression: a restored local- cron tab isn't write-gated before any list loads its row.

  • Tests: 166 related Python files, 1124 passed, 0 failed, 6 skipped. Both cron files also pass under TZ=America/New_York. Desktop cron vitest: 69 passed. scripts/check ok.
  • Diff: 923 lines (+778 / -145) across 16 files Reviewer: unsupportedpastels Review duration: 238m
    All Vouch review confidence checks passed
    Residual risk 0.20 = Change Risk (0.86) × (1 − Review Confidence (0.77)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.86 · 923 lines diff across 16 files
    0.86
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.74 · 1 substantive comment(s)
    0.74
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    77%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Self Review self_review
    0.140
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    4 items
    kshitijk4poor kshitijk4poor commented on Oct 15, 2026 18:58 UTC
    Reviewer

    Reviewed at 2c5e7ac7. The 10 new tests fail on current main and pass on this head. test_unified_run_is_one_owned_session_row_and_detail_agrees passes at this head. The 8 test_hermes_state.py vacuum and maintenance failures I see locally fail on clean main too.

    Verified correct:

  • SQL: a probe checked the offsets, ids containing :, _, % and [], and the policy-based split for ambiguous ids.

  • Query plan: EXPLAIN QUERY PLAN shows a range seek on idx_session_admissions_cron_request; the OR is applied as a filter after the seek. list_cron_job_runs(limit=20) took about 1ms on a 200-run job with 20k interactive sessions.

  • Legacy ids: the stricter GLOB hides no real runs. The scheduler has always written cron_<job>_YYYYmmdd_HHMMSS.

  • Index creation: the index is created only on writable opens; _open_read_only does no DDL.

  • The : guard: it can't refuse a real scheduler id, which is always uuid4().hex.

  • Desktop: cronRunWriteGateApplies covers everything the old submit.ts condition did.
  • Warning: the same-second case is only partly fixed. If another attempt B is claimed before or in the same second as run A's doc (a manual hermes cron run overlapping a tick), B becomes candidates[0]. If B never created a session:

  • A's doc renders as an extra cron_output row with B's status;

  • B's own fallback row stays hidden through represented.
  • On main the same case just drops B, so this isn't strictly a regression, but represented is still decided before reconciliation. No test covers it.

    Nits

  • hermes_state_common.py: the partial index hard-codes WHERE principal_id = 'cron-owner', while the queries inline CRON_PRINCIPAL_ID. If the two ever drift apart, the planner silently stops using the index. Build it from the constant or assert they're equal.

  • _reconcile_cron_runs relies on _execution_candidates and _execution_id passed inside row dicts, and treats a missing key differently from an empty tuple. Returning docs and orphan ledger rows separately from _list_cron_output_runs would remove both and most of the docstring.

  • _CRON_ADMISSION_SQL hard-codes substr(request_id, 6) and length(:request_lo) - 5. Deriving them from len(_CRON_REQUEST_PREFIX) would be easier to verify.

  • The half-open bound prefix[:-1] + chr(ord(prefix[-1]) + 1) now exists three times. A prefix_range() helper in hermes_state_keys would cover all three.

  • The two new test files define near-identical owner fixtures and fire helpers. test_a_same_second_output_doc... also re-imports hermes_time and timedelta, which are already imported at module top.

  • Known gap, not a regression: a restored local-* cron tab still isn't write-gated before any list loads its row.
  • yoniebans yoniebans commented on Oct 15, 2026 19:31 UTC
    Reviewer

    Reviewed at 2c5e7ac72e, on top of @kshitijk4poor's review above; what it verifies is not repeated here. One addition on the Desktop side: with the old open-cron-run.ts under the new tests, the three #138812 gate cases fail, and all pass on this head.

    @whyyagswhy's report that test_unified_run_is_one_owned_session_row_and_detail_agrees fails at 70af70a52b has no reply yet. I couldn't reproduce it at that commit: it passed in repeated runs and under UTC, America/Los_Angeles and Asia/Kolkata, and so did the tip of #138968. Asking which environment showed the second row would settle whether there is a real path to it.

    Not from this PR: agent/transports/codex.py still derives a job's prompt-cache scope from the legacy cron_<job>_<timestamp> id, so unified-runtime fires of one job no longer share a scope. That predates this change and fits a follow-up.

    unsupportedpastels unsupportedpastels commented on Oct 15, 2026 19:35 UTC
    Reviewer

    @kshitijk4poor thanks, fixed in db1b816a.

  • Overlapping attempt: I took your restructure. _list_cron_output_runs now returns docs and ledger attempts separately, and _reconcile_cron_runs decides each doc's writer only after sessions are known. An attempt that finished before the doc's second loses; then an attempt whose own session spans the doc beats one with no session; then the newest claim wins. Each attempt gets one row: its session, else its doc, else its ledger row. The _execution_candidates and _execution_id keys are gone. test_an_overlapping_attempt_claimed_before_a_runs_doc_keeps_its_own_row (with B finishing before and after A's doc) failed before: A's doc showed as an extra FAILED row, and B's own row was hidden.

  • Index constant: the partial index's WHERE is built from CRON_PRINCIPAL_ID.

  • substr offsets: derived from len(CRON_REQUEST_PREFIX), which is now public.

  • Half-open bound: a prefix_range() helper in hermes_state_keys, used in all three places.

  • Test duplication: cron_owner() and admit_fire() are shared in tests/fakes/cron_owner.py, and the duplicate imports are gone.

  • *Restored local- tab before any list loads:** not addressed here, as you noted.
  • @whyyagswhy, the failure you reported in test_unified_run_is_one_owned_session_row_and_detail_agrees only happened outside TZ=UTC. 2c5e7ac7 pins the zone in the fixture, and both cron test files pass under TZ=America/New_York.

    Tests: 166 related files, 1124 passed, 0 failed, 6 skipped. Desktop cron vitest: 69 passed. scripts/check ok.

    Assignees
    unsupportedpastels unsupportedpastels
    Labels
    risk: low confidence: 77.1% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 85.5% (HIGH) · Higher = larger blast radius
    85.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 77.1% · Lower = rushed or shallow review
    77.1%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 19.6% · Safe to merge
    19.6%