Skip to content

fix(store): prevent TOCTOU race on event seq numbering (#98) - #110

Merged
knight22-21 merged 1 commit into
knight22-21:mainfrom
chiragjangiir:fix/append-event-toctou-race
Oct 22, 2026
Merged

knight22-21 merged 1 commit into
knight22-21:mainfrom
chiragjangiir:fix/append-event-toctou-race

Conversation

@chiragjangiir

Copy link
Copy Markdown
Contributor

Closes #98

Root Cause

In devagent/session/store.py, append_event() read the next sequence number via SELECT COALESCE(MAX(seq), -1) + 1 and then inserted the new event. In concurrent environments (such as parallel multi-worker agent sessions), two concurrent workers could read the same MAX(seq) simultaneously before either inserted a row. Because SQLite autocommits statements individually when no explicit transaction is begun on read, both workers generated identical seq values, causing collisions in event ordering.

Changes

  1. Added conn.execute("BEGIN IMMEDIATE") before reading MAX(seq) in append_event(), guaranteeing exclusive write-transaction access across the read-calculate-insert cycle.
  2. Added timeout=30.0 to _conn() so concurrent threads wait for lock release rather than prematurely raising sqlite3.OperationalError.
  3. Added tests/test_event_seq_concurrency.py asserting that 24 concurrent threads writing to the same session simultaneously produce strictly unique, unbroken, monotonic sequence numbers (0 to 23).

Verification

  • Tested with pytest:
    python -m pytest tests/test_event_seq_concurrency.py tests/test_phase8.py tests/test_phase36.py
    All 35 tests passed cleanly.
  • Checked with ruff:
    ruff check devagent/session/store.py tests/test_event_seq_concurrency.py
    Zero lint errors.

@knight22-21
knight22-21 merged commit 34da0bd into knight22-21:main Oct 22, 2026
5 checks passed
@knight22-21

Copy link
Copy Markdown
Owner

Thanks for the fix, @chiragjangiir! Resolving event sequence numbers directly within the append transaction prevents duplicate sequence numbers under concurrent event logging.

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.

append_event() has a TOCTOU race on seq numbering; concurrent workers can generate duplicate sequence numbers

2 participants