Skip to content

Wait for the idle batch flush instead of racing a fixed sleep - #10063

Merged
danielhanchen merged 1 commit into
mainfrom
fix-flaky-batch-flush
Aug 31, 2026
Merged

danielhanchen merged 1 commit into
mainfrom
fix-flaky-batch-flush

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

The Backend tests lane failed on test_event_batch_flushes_while_upstream_is_idle with assert [] == [two deltas], while the other 35,482 tests passed. This is a test timing bug, not a regression.

Why it fails

The test slept a flat 0.2s and then asserted the two chunks were durable. What it is waiting for is _EVENT_BATCH_SECONDS (0.1s) plus an asyncio.to_thread hop and a SQLite write in db.append_events.

I measured that end to end over twelve runs on a completely idle 192-core machine:

0.107 0.105 0.106 0.105 0.106 0.106 0.105 0.106 0.107 0.104 0.128 0.116
min=0.104  max=0.128  mean=0.108

So the best case already consumed more than half the budget, and one sample left only 1.56x headroom before it ever reached a shared runner. CPU contention alone does not push it over, which fits the failure being I/O rather than scheduling: the flush needs a free executor thread and the SQLite writer lock, and the lane runs the full suite.

Whose fault it is

Neither of the two commits that shaped this code.

The production behaviour is correct: with at least _EVENT_BATCH_MIN_SIZE pending and an idle upstream, the batch flushes after _EVENT_BATCH_SECONDS. The test was measuring it wrongly.

The change

Poll until the events land instead of sleeping a fixed span, in the same idiom test_subscribers_detach_then_replay_the_same_engine_run already uses a few lines above. The bound is the midpoint between _EVENT_BATCH_SECONDS and _EVENT_SINGLE_FLUSH_SECONDS, both imported from the module so it tracks the code rather than a copied literal.

That is deliberately not "just wait longer". A plain generous timeout would let a regression that drops these two events onto the 1.0s single-event timer pass silently. The midpoint keeps the test strictly below that path, so the discrimination survives while the margin goes from under 2x to roughly 5x.

Verification

Mutation tested, because a robustified test is only worth having if it still fails for the right reasons:

Result
unmodified passes
_EVENT_BATCH_MIN_SIZE 2 to 3, dropping the pair onto the 1.0s timer fails
idle flush branch deleted outright fails

Also test_chat_generation_supervisor.py 24/24, and the test 40/40 pinned to a single CPU shared with six busy loops.

I checked the rest of the file for the same pattern. This was the only sleep-then-assert gate; the other sleep(0.01) calls pace producer bodies and are not assertion timing.

test_event_batch_flushes_while_upstream_is_idle slept 0.2s and then asserted the
two chunks were durable. The flush it waits on costs _EVENT_BATCH_SECONDS plus a
thread hop and a SQLite write, which measures 0.104s to 0.128s over twelve runs
on a completely idle machine, so the assertion had under 2x headroom before it
ever reached a loaded runner. It lost that race on a Backend tests lane where the
other 35,482 tests passed.

Neither of the two commits that shaped this loop is at fault. #9187 wrote the
test with the margin it has, and the producer loop #9997 later touched only adds
work on admission markers, which this stream never emits.

So the production behaviour is right and the test was measuring it wrongly. It
now polls until the events land, in the same idiom the sibling replay test
already uses, bounded by the midpoint between the batch and single-event flush
intervals and reading both from the module so the bound tracks the code. That
raises the margin from under 2x to roughly 5x while staying strictly below the
single-event timer, so the test still fails if these two events ever fall onto
that slower path.

Confirmed by mutation: raising _EVENT_BATCH_MIN_SIZE to 3, which drops the pair
onto the 1.0s timer, and deleting the idle flush outright both still fail. The
file passes 24/24, and the test passes 40/40 pinned to one CPU shared with six
busy loops.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-08-31T09:07:55.060820Z b3162c0 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b3162c0c17

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +327 to +328
deadline = (_EVENT_BATCH_SECONDS + _EVENT_SINGLE_FLUSH_SECONDS) / 2
stored = await _await_chunk_payloads("run-1", len(chunks), deadline)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Start the deadline after the chunks reach the producer

When the default executor is busy, this deadline begins before _produce has completed its several startup asyncio.to_thread calls (get_worker_run, mark_running, another read, and touch_progress), so those unrelated operations can consume the entire 0.55-second budget before the mocked stream has even populated pending. This leaves the test susceptible to the same loaded-runner failure it is intended to remove; signal from body once the second chunk has been consumed and start the bounded flush wait from there.

Useful? React with 👍 / 👎.

"""
started = time.monotonic()
while True:
stored = [e["payload"] for e in runs_db.list_events(run_id) if e["type"] == "chunk"]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Move polling database reads off the event loop

On a contended SQLite database, each synchronous list_events call can wait for the connection's busy timeout while blocking the asyncio event loop. During that wait _produce cannot resume its own asyncio.wait timeout to submit the idle batch flush, so the polling intended to eliminate an I/O-contention race can itself make the deadline expire with no stored chunks. Run the reads in a thread and enforce the overall deadline asynchronously rather than performing repeated blocking database operations on the producer's loop.

Useful? React with 👍 / 👎.

@danielhanchen
danielhanchen merged commit 8fba17f into main Aug 31, 2026
30 of 34 checks passed
@danielhanchen
danielhanchen deleted the fix-flaky-batch-flush branch August 31, 2026 09:19
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.

1 participant