Skip to content

Add arena rating snapshot job - #149

Merged
seribaymadina merged 2 commits into
mainfrom
arena/05-rating-snapshot-job
Jun 19, 2026
Merged

Add arena rating snapshot job#149
seribaymadina merged 2 commits into
mainfrom
arena/05-rating-snapshot-job

Conversation

@seribaymadina

@seribaymadina seribaymadina commented Jun 19, 2026

Copy link
Copy Markdown
Contributor

Adds the rating snapshot job (layer 7): refit Davidson-BT ratings from all votes and persist one leaderboard board.

  • coval-bench arena snapshot reads every vote, runs the rating engine, and writes one board.

  • The whole board is written in a single transaction with one computed_at, so a reader never sees a partial board.

  • A non-blocking advisory lock keeps two runs from computing at once. --force bypasses it; a crashed run self-heals when its connection drops.

  • Status comes from the engine's CI-half-width classifier. Models with no votes are never written.

  • Writes the all domain board only. Per-domain boards, retention/pruning, and trigger cadence are follow-ups.

  • Read-API files are untouched: math stays in arena/rating.py, SQL in db/arena_store.py, the job is glue.

Summary by CodeRabbit

  • New Features
    • Added a new arena snapshot command to compute and persist leaderboard snapshots with configurable parameters including rating metric, bootstrap resampling rounds, and random seed.
    • Command supports a --force flag to bypass snapshot locks when needed.

Greptile Summary

This PR adds the arena snapshot CLI command (layer 7 of the rating pipeline) that reads all votes, fits the Davidson-BT leaderboard via compute_ratings, and atomically persists one board to arena.leaderboard_snapshots. The previously-flagged gaps — uncaught ConvergenceError and individual-execute inserts in a loop — are both resolved in this diff.

  • run_snapshot in snapshot.py orchestrates the job: battles and votes are fetched, converted to BattleOutcome objects, and fed to compute_ratings; the resulting rows are bulk-inserted with executemany inside a single transaction so computed_at is identical for every row in a board.
  • A non-blocking pg_try_advisory_lock prevents concurrent recomputes; --force bypasses the lock; ConvergenceError is caught and serialised as structured JSON before a non-zero exit.
  • list_battles gains an optional limit=None path needed by the refit job, and LeaderboardSnapshot / SnapshotStatus are added to models.py.

Confidence Score: 5/5

Safe to merge — the orchestration logic, advisory lock lifecycle, and atomic board insert are all correct, and the previously-raised gaps are resolved in this diff.

The lock is correctly held on a dedicated connection for the job's full duration and always released in a finally block, executemany inside conn.transaction() guarantees all rows share a single computed_at, ConvergenceError is caught and serialised before exit, and the five integration tests exercise all branching paths including force-override and domain scoping.

No files require special attention.

Important Files Changed

Filename Overview
runner/src/coval_bench/arena/snapshot.py New orchestration module: fetches battles+votes, builds BattleOutcome list, calls compute_ratings, writes board via insert_snapshot_board. Advisory-lock branching is clean; empty-vote case is correctly handled by returning an empty RatingResult without writing anything.
runner/src/coval_bench/db/arena_store.py Adds insert_snapshot_board (executemany in a single transaction), snapshot_lock (session-level pg_try_advisory_lock with proper acquire/release/commit), and refactors list_battles to accept limit=None. SQL is parameterised; lock connection lifetime is correctly scoped to the job.
runner/src/coval_bench/main.py Adds arena group and snapshot sub-command. ConvergenceError is caught and serialised as structured JSON before sys.exit(1); skipped and success paths also emit valid JSON — exit contract is consistent across all code paths.
runner/src/coval_bench/db/models.py Adds SnapshotStatus StrEnum and LeaderboardSnapshot Pydantic model matching the arena.leaderboard_snapshots schema; computed_at is left None so the DB default assigns a single transaction timestamp.
runner/tests/unit/test_arena_snapshot.py Integration tests using pytest-postgresql cover: board persistence, no-votes no-write, lock-skip, force-override, and domain-scoped snapshot. Good coverage of the advisory lock paths and atomic timestamp assertion.

Sequence Diagram

%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
    participant CLI as CLI (arena snapshot)
    participant S as run_snapshot
    participant Store as ArenaStore
    participant DB as PostgreSQL
    participant Eng as compute_ratings

    CLI->>S: run_snapshot(store, metric, domain, force, ...)
    alt "force=False"
        S->>Store: snapshot_lock()
        Store->>DB: pg_try_advisory_lock(arena_snapshot)
        DB-->>Store: acquired (true/false)
        alt not acquired
            S-->>CLI: None - JSON skipped true
        end
    end
    S->>S: _refit_and_persist(...)
    S->>Store: "list_battles(domain, limit=None)"
    Store->>DB: SELECT FROM arena.battles
    DB-->>Store: battles[]
    S->>Store: list_votes()
    Store->>DB: SELECT FROM arena.votes
    DB-->>Store: votes[]
    S->>Eng: compute_ratings(outcomes, bootstrap_rounds, seed)
    Eng-->>S: RatingResult or ConvergenceError
    S->>Store: insert_snapshot_board(rows)
    Store->>DB: BEGIN / executemany INSERT / COMMIT
    DB-->>Store: ok
    S-->>CLI: RatingResult
    CLI->>CLI: JSON event metric models
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
    participant CLI as CLI (arena snapshot)
    participant S as run_snapshot
    participant Store as ArenaStore
    participant DB as PostgreSQL
    participant Eng as compute_ratings

    CLI->>S: run_snapshot(store, metric, domain, force, ...)
    alt "force=False"
        S->>Store: snapshot_lock()
        Store->>DB: pg_try_advisory_lock(arena_snapshot)
        DB-->>Store: acquired (true/false)
        alt not acquired
            S-->>CLI: None - JSON skipped true
        end
    end
    S->>S: _refit_and_persist(...)
    S->>Store: "list_battles(domain, limit=None)"
    Store->>DB: SELECT FROM arena.battles
    DB-->>Store: battles[]
    S->>Store: list_votes()
    Store->>DB: SELECT FROM arena.votes
    DB-->>Store: votes[]
    S->>Eng: compute_ratings(outcomes, bootstrap_rounds, seed)
    Eng-->>S: RatingResult or ConvergenceError
    S->>Store: insert_snapshot_board(rows)
    Store->>DB: BEGIN / executemany INSERT / COMMIT
    DB-->>Store: ok
    S-->>CLI: RatingResult
    CLI->>CLI: JSON event metric models
Loading

Reviews (3): Last reviewed commit: "Address snapshot job review feedback" | Re-trigger Greptile

@vercel

vercel Bot commented Jun 19, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
benchmarks Ready Ready Preview, Comment Jun 19, 2026 10:57pm

Request Review

@coderabbitai

coderabbitai Bot commented Jun 19, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a complete arena leaderboard rating snapshot pipeline: new LeaderboardSnapshot and SnapshotStatus DB models, three new ArenaStore methods (insert_snapshot_board, snapshot_lock, refactored list_battles), an orchestration module (arena/snapshot.py) with lock-aware run_snapshot, a arena snapshot CLI command, and integration tests against an ephemeral PostgreSQL instance.

Changes

Arena Leaderboard Snapshot Workflow

Layer / File(s) Summary
LeaderboardSnapshot and SnapshotStatus DB models
runner/src/coval_bench/db/models.py
Adds SnapshotStatus StrEnum with PRELIMINARY/USABLE/ESTABLISHED tiers and LeaderboardSnapshot Pydantic model covering board identifiers, rating/CI fields, vote aggregates, and status; exports both in __all__.
ArenaStore persistence: list_battles refactor, insert_snapshot_board, snapshot_lock
runner/src/coval_bench/db/arena_store.py
Adds advisory-lock SQL constants and async imports; refactors list_battles with conditional domain filter and optional LIMIT; adds insert_snapshot_board for transactional batch INSERTs returning row count; adds snapshot_lock async context manager for non-blocking PostgreSQL advisory lock acquisition and guaranteed release.
Snapshot orchestration: _refit_and_persist and run_snapshot
runner/src/coval_bench/arena/snapshot.py
Adds _refit_and_persist (loads battles/votes, maps to BattleOutcome identifiers, calls compute_ratings, builds and persists LeaderboardSnapshot rows) and public run_snapshot entrypoint that coordinates advisory lock acquisition or bypasses it with force=True.
arena snapshot CLI command
runner/src/coval_bench/__main__.py
Adds arena Click command group and arena_snapshot subcommand wiring metric/bootstrap-rounds/seed/force options to run_snapshot via a lifespan-managed DB pool; emits a JSON event to stdout indicating skipped or model count.
Integration tests: snapshot, no-votes, lock, and force paths
runner/tests/unit/test_arena_snapshot.py
Adds test module with ephemeral PostgreSQL fixtures (pytest-postgresql + Alembic migrations), table-reset/count helpers, async pool factory, and battle/vote seeding; covers happy-path snapshot content assertions, no-votes empty result, held-lock returns None, and force=True bypasses held lock and persists rows.

Sequence Diagram(s)

sequenceDiagram
  participant CLI as arena snapshot CLI
  participant run_snapshot
  participant snapshot_lock as ArenaStore.snapshot_lock
  participant _refit_and_persist
  participant ArenaStore
  participant compute_ratings

  CLI->>run_snapshot: run_snapshot(store, metric, domain, rounds, seed, force)

  alt force=False
    run_snapshot->>snapshot_lock: async with store.snapshot_lock()
    snapshot_lock-->>run_snapshot: acquired=True/False
    alt lock not acquired
      run_snapshot-->>CLI: None (skipped)
    end
  end

  run_snapshot->>_refit_and_persist: _refit_and_persist(store, ...)
  _refit_and_persist->>ArenaStore: list_battles(domain, limit=None)
  ArenaStore-->>_refit_and_persist: battles[]
  _refit_and_persist->>ArenaStore: list_votes()
  ArenaStore-->>_refit_and_persist: votes[]
  _refit_and_persist->>compute_ratings: BattleOutcome[], bootstrap_rounds, seed
  compute_ratings-->>_refit_and_persist: RatingResult
  _refit_and_persist->>ArenaStore: insert_snapshot_board(LeaderboardSnapshot rows)
  ArenaStore-->>_refit_and_persist: inserted_count
  _refit_and_persist-->>run_snapshot: RatingResult
  run_snapshot-->>CLI: RatingResult (models count printed as JSON)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • coval-ai/benchmarks#119: Creates the Alembic migration for the arena schema and the battles, votes, and leaderboard_snapshots tables that insert_snapshot_board and snapshot_lock write to.
  • coval-ai/benchmarks#138: Established the ArenaStore foundation that this PR extends with insert_snapshot_board, snapshot_lock, and the refactored list_battles.
  • coval-ai/benchmarks#139: Introduced compute_ratings() (Davidson-BT engine) that _refit_and_persist calls to produce the rating/CI values written into LeaderboardSnapshot rows.

Suggested reviewers

  • callumreid
  • coval-cale

Poem

🐇 Hop hop, the leaderboard grows,
Battles tallied, the rating shows.
A snapshot locked, then released with care,
Bootstrap rounds whistle through the air.
JSON printed: "models: two!"
The rabbit's work is finally through! 🏆

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 17.39% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Add arena rating snapshot job' directly and clearly summarizes the main change: adding a new arena rating snapshot job CLI command and its implementation.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch arena/05-rating-snapshot-job

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Refit Davidson-BT ratings from all votes and persist one leaderboard board
via coval-bench arena snapshot. The board is written in a single transaction
so readers never see a partial board, and a non-blocking advisory lock keeps
two runs from computing at once (--force bypasses it).
Comment thread runner/src/coval_bench/__main__.py Outdated
Comment thread runner/src/coval_bench/db/arena_store.py Outdated
@seribaymadina
seribaymadina force-pushed the arena/05-rating-snapshot-job branch from 91cbf36 to 7f66e99 Compare June 19, 2026 22:39

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@runner/src/coval_bench/arena/snapshot.py`:
- Around line 30-31: The store.list_battles() and store.list_votes() calls on
lines 30-31 load all data regardless of the domain parameter provided to
run_snapshot(), but the caller-provided domain is persisted on line 51, causing
a mismatch between the loaded data and the domain label. Pass the domain
parameter to both store.list_battles() and store.list_votes() calls to filter
the loaded data by the specified domain, ensuring the persisted domain label
accurately reflects the data that was actually loaded.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 96b337ba-a029-4ddc-8f77-07f4831d2381

📥 Commits

Reviewing files that changed from the base of the PR and between cf2b746 and 91cbf36.

📒 Files selected for processing (5)
  • runner/src/coval_bench/__main__.py
  • runner/src/coval_bench/arena/snapshot.py
  • runner/src/coval_bench/db/arena_store.py
  • runner/src/coval_bench/db/models.py
  • runner/tests/unit/test_arena_snapshot.py

Comment thread runner/src/coval_bench/arena/snapshot.py Outdated
Filter battles by domain so the persisted board label matches the data
that was rated. Catch ConvergenceError in the CLI and emit an error JSON
line plus a non-zero exit instead of a raw traceback. Insert the board
with executemany.

@coval-cale coval-cale left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hell ya dude

@seribaymadina
seribaymadina added this pull request to the merge queue Jun 19, 2026
Merged via the queue into main with commit fa4efe5 Jun 19, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants