Skip to content

runtime: keep a tee of a tee's read path under the shared skew budget - #111

Merged
ryuzdev merged 3 commits into
mainfrom
cello/tee-chain-flake
Nov 21, 2026
Merged

ryuzdev merged 3 commits into
mainfrom
cello/tee-chain-flake

Conversation

@ryuzdev

@ryuzdev ryuzdev commented Nov 21, 2026

Copy link
Copy Markdown
Member

What flaked

crates/cello/tests/d1_concurrency_conformance.rs::attribution_request_tee_chain_shares_one_skew_budget
(attr-r2tee-chain) failed once in a full cargo test -p cello run and would
not reproduce on an idle machine. It is not a timing flake: under CPU load it
fails about 55 times in 100 on main, and 8 of 8 runs of the whole
d1_concurrency_conformance binary failed while the machine was loaded.

Failing output before this change:

assertion `left == right` failed:
  {"forwarded":0,"lagging1":{"ok":true,"size":25165824},"lagging2":{"ok":true,"size":0},"ok":true}

Root cause

The fixture streams 24 MiB through request.body.tee() and then tees one copy
again, so one request owns two host tees: ids 1 (body), 2,3 (first tee),
4,5 (tee of 2). All of them draw on one TeeSkewBudget, which failed "the
most-lagging branch" by buffered bytes alone, with HashMap iteration order
breaking ties.

Two defects compounded:

  1. The victim could be a copy a consumer was draining. In a chain the same
    bytes are charged at every stage, so the inner tee's source is often the
    largest holder outright. Traced standings at a failing send:

    used=33499344 "2:13481829zr 4:8751312zr 5:11266203zu"
    

    Branch 2, the inner tee's source, was the strict max, so the budget
    failed it. On a tie (2 and an unread copy hold identical bytes until the
    inner pump runs) HashMap order decided, so the run was also
    nondeterministic.

  2. Failing a mid-read copy truncated the chain silently. For a branch with
    a pull in flight, fail_tee_branch removed it as Cancelled, which a
    consumer reads as a clean end. The inner tee's pump saw
    Terminated(Cancelled) and broke without erroring its own branches, so
    both ended as EOF: the subrequest body carried zero bytes and the handler
    answered ok: true, or a copy's arrayBuffer() resolved short.

Fix

crates/cello/http_streams.rs:

  • Victim choice (choose_tee_victim, copy_is_undrained,
    HttpStreamService::pick_tee_victim): fail a copy nobody has drained — one
    with no byte taken and no pull in flight — choosing among those that give
    back the overrun on their own. A copy a consumer is draining is failed only
    when no undrained copy frees enough, because dropping live bytes is still
    better than buffering past the cap without bound. Remaining ties break by
    stream id, so the choice never depends on HashMap order. The counters and
    the registry's pull state are read as two snapshots (the budget's lock is
    never held across another lock) and the cap is rechecked before anyone is
    failed.
  • A failed mid-read copy reports it. A leased branch is removed with the
    new HttpStreamTerminationReason::Skewed, which maps to
    HTTP_TEE_SKEW_MESSAGE, so an in-flight read rejects with the documented
    error instead of ending the body.
  • A tee pump never closes its branches as if they finished. When its
    source terminates for a reason that is not a clean end (Finished or
    Cancelled), each live branch receives that error after the bytes it
    already holds.

The test asserts the contract, not one scheduling outcome

Two copies of a chain are indistinguishable until a consumer takes the first
byte from one of them: an unread copy and the copy a subrequest is streaming
both sit registered, undrained and unleased, and can hold identical bytes
(traced: 4:11100054z-A 5:11100054z-A). Which of them the shared budget ends
is a scheduling outcome, so "the read branch always completes" is not
something the implementation can promise. The fixture now reports the
subrequest's outcome instead of assuming it, and the test pins what is
guaranteed:

  • every copy the budget spared arrived whole (24 MiB),
  • at least one copy — or the subrequest reading one — reports the skew cap,
  • nothing comes up short.

That still catches the bug: before this change the read branch reported 0
bytes (or a short count) while every copy said ok, so the whole-copy
assertion fails. tee_skew_victim_tests adds seven deterministic unit tests
for the victim rule and for the Skewed error.

Docs: docs/reference/cloudflare-compat.md, docs/changelog.md.

Rates

This fixture, 32 CPU hogs, the single test in a loop:

build runs failures
main (b1e3efe) 100 55
branch (fix, before the test was aligned) 200 0 in the designed shape, 1 loud chain failure
branch (final) see the run recorded on the PR

- Fail the copy nobody drained: one with no byte taken and no pull in
  flight, chosen among those that give back the overrun on their own.
  Buffered bytes alone picked the inner tee's source in a chain -- the
  same bytes are charged at every stage -- and HashMap order broke the
  tie between copies holding identical bytes, so the victim was
  scheduling-dependent.
- Report a failed mid-read copy: a leased branch is removed with the new
  HttpStreamTerminationReason::Skewed, which maps to HTTP_TEE_SKEW_MESSAGE,
  so a pull in flight rejects instead of ending the body.
- Never close a tee's branches as if they finished: when the pump's source
  terminates for a reason that is not a clean end, each live branch gets
  that error after the bytes it already holds.
- Fixture and conformance test: the subrequest's outcome is data now. A
  copy a subrequest streams is indistinguishable from an unread copy
  until its first pull, so which copy the shared budget ends is a
  scheduling outcome; the test pins survivors whole, at least one copy
  reporting the skew cap, and no copy coming up short.
- Unit tests pin the victim rule and the Skewed error. Under CPU load the
  single test failed 55/100 on main; 0/150 and 0/60 after, and the whole
  d1_concurrency_conformance binary 10/10.
- Docs: docs/reference/cloudflare-compat.md and the changelog (#111).
@coderabbitai

coderabbitai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 21 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ac8195cc-b6b4-4387-a29c-c28d1ad416a6
Commits

Reviewing files that changed from the base of the PR and between b1e3efe and ec78415.

Files selected for processing: 7

  • crates/cello/http_streams.rs
  • crates/cello/js.rs
  • crates/cello/js/harness.js
  • crates/cello/tests/d1_concurrency_conformance.rs
  • crates/cello/tests/fixtures/d1-concurrency/worker.js
  • docs/changelog.md
  • docs/reference/cloudflare-compat.md
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

- fan_out_http_tee_item returns the terminating reason and publishes it to both branches before the pump breaks, so a skew kill or sweep that commits between producing an item and sending it can no longer end both branches as a clean EOF.
- fail_tee_branch returns whether it acted; the skew loop skips budget ids whose registry entry a lease already removed and ends the sending branch when nothing killable remains, closing the victim-missing spin.
- Forward a request body stream failure's root cause, so a fetch streaming a failed copy reports the skew error instead of a generic 'error sending request'.
- The chain conformance test now requires the forwarded copy's error to name the skew cap; docs and comments state that a teed or subrequest-streamed copy is spared only after its first byte.

Fixes #111
@ryuzdev

ryuzdev commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Security review record. An independent reviewer, SecTeeVictim, who wrote none of this, reviewed it in three rounds; final verdict OK at ec784154.

  • Round 1, FIX:
    • Medium: silent truncation was still reachable on the SourceTerminated short-circuit;
    • Medium: the victim-MISSING spin;
    • Medium: the test counted any forwarded failure as a skew kill;
    • Low: docs overpromised.
  • Round 2, FIX, all Low:
    • two pumps killing the same victim made the second fail its own live branch;
    • the container-port heuristic lost the timeout case;
    • stale comments.
    • Under the review cap the integrator fixed these himself.
  • Round 3: delta only; OK. The re-pick loop can't spin, both bounds hold, and memory stays under the cap.

Flake rate: on main, 55/100 single-test failures and 8/8 failures of the full d1 binary under load. On this branch, 0/210 plus 0/60 after round 3; the d1 binary passed 10/10.

@ryuzdev
ryuzdev merged commit 2047a68 into main Nov 21, 2026
9 checks passed
ryuzdev added a commit that referenced this pull request Nov 21, 2026
- Fail the copy nobody drained: one with no byte taken and no pull in
  flight, chosen among those that give back the overrun on their own.
  Buffered bytes alone picked the inner tee's source in a chain -- the
  same bytes are charged at every stage -- and HashMap order broke the
  tie between copies holding identical bytes, so the victim was
  scheduling-dependent.
- Report a failed mid-read copy: a leased branch is removed with the new
  HttpStreamTerminationReason::Skewed, which maps to HTTP_TEE_SKEW_MESSAGE,
  so a pull in flight rejects instead of ending the body.
- Never close a tee's branches as if they finished: when the pump's source
  terminates for a reason that is not a clean end, each live branch gets
  that error after the bytes it already holds.
- Fixture and conformance test: the subrequest's outcome is data now. A
  copy a subrequest streams is indistinguishable from an unread copy
  until its first pull, so which copy the shared budget ends is a
  scheduling outcome; the test pins survivors whole, at least one copy
  reporting the skew cap, and no copy coming up short.
- Unit tests pin the victim rule and the Skewed error. Under CPU load the
  single test failed 55/100 on main; 0/150 and 0/60 after, and the whole
  d1_concurrency_conformance binary 10/10.
- Docs: docs/reference/cloudflare-compat.md and the changelog (#111).
ryuzdev added a commit that referenced this pull request Nov 21, 2026
- fan_out_http_tee_item returns the terminating reason and publishes it to both branches before the pump breaks, so a skew kill or sweep that commits between producing an item and sending it can no longer end both branches as a clean EOF.
- fail_tee_branch returns whether it acted; the skew loop skips budget ids whose registry entry a lease already removed and ends the sending branch when nothing killable remains, closing the victim-missing spin.
- Forward a request body stream failure's root cause, so a fetch streaming a failed copy reports the skew error instead of a generic 'error sending request'.
- The chain conformance test now requires the forwarded copy's error to name the skew cap; docs and comments state that a teed or subrequest-streamed copy is spared only after its first byte.

Fixes #111
@ryuzdev
ryuzdev deleted the cello/tee-chain-flake branch November 21, 2026 14:59
ryuzdev added a commit that referenced this pull request Nov 22, 2026
Long stream timelines now run in virtual time, so a five-minute SSE, a
60-second idle body, the 30-second waitUntil budget and a stalled
TransformStream producer cost milliseconds of CI instead of minutes,
reproducibly.

- One clock: `asyncrt::mono_now` returns `tokio::time::Instant::now()`, and
  the domain's start instant (stamped inside its own runtime) plus
  `InFlight::{started, background_since}` and the event-start stamps read
  it. Every other wait in the runtime is already a Tokio timer, so a test
  that pauses the clock moves every deadline together. Unpaused, it reads
  the same monotonic clock `std` does: no production change.
- `crates/cello/tests/virtual_clock_conformance.rs` drives the real
  `runtime::drive` against a real Worker on a `start_paused` current-thread
  runtime and reads the response body the way the shell does:
  * a two-minute-plus SSE survives five virtual minutes with all 30 events
    (fails on the pre-#103 waitUntil registration: the body is cut after the
    30 s budget);
  * a silent body ends at its 60 s idle deadline and not one second earlier
    (fails without the clock seam: the sweeper re-arms forever);
  * answered `waitUntil` work is cut at the background budget, not before
    it and not at the 300 s handler budget;
  * a `TransformStream` producer parks while its consumer does not read and
    resumes when it does (#105);
  * a proptest over seeded chunk schedules and drain orders: a tee of a tee
    delivers byte-identical data on every branch (#111), with the failing
    seed and minimal input printed, plus a fixed test for the one recorded
    schedule because seeds are random.
  Each scenario asserts its own wall time stays under a second, and every
  driven request is awaited to retire instead of detached so one scenario's
  isolate cannot leak into the next.
- Dev-only `tokio` `test-util` enables the paused clock; `proptest` (already
  a workspace dependency) is now used. Failures persist beside the crate.
- CONTRIBUTING "Testing locally" documents the pattern, the deadlines that
  must read the seam, and the ones deliberately left on `std`.
ryuzdev added a commit that referenced this pull request Nov 22, 2026
Long stream timelines now run in virtual time, so a five-minute SSE, a
60-second idle body, the 30-second waitUntil budget and a stalled
TransformStream producer cost milliseconds of CI instead of minutes,
reproducibly.

- One clock: `asyncrt::mono_now` returns `tokio::time::Instant::now()`, and
  the domain's start instant (stamped inside its own runtime) plus
  `InFlight::{started, background_since}` and the event-start stamps read
  it. Every other wait in the runtime is already a Tokio timer, so a test
  that pauses the clock moves every deadline together. Unpaused, it reads
  the same monotonic clock `std` does: no production change.
- `crates/cello/tests/virtual_clock_conformance.rs` drives the real
  `runtime::drive` against a real Worker on a `start_paused` current-thread
  runtime and reads the response body the way the shell does:
  * a two-minute-plus SSE survives five virtual minutes with all 30 events
    (fails on the pre-#103 waitUntil registration: the body is cut after the
    30 s budget);
  * a silent body ends at its 60 s idle deadline and not one second earlier
    (fails without the clock seam: the sweeper re-arms forever);
  * answered `waitUntil` work is cut at the background budget, not before
    it and not at the 300 s handler budget;
  * a `TransformStream` producer parks while its consumer does not read and
    resumes when it does (#105);
  * a proptest over seeded chunk schedules and drain orders: a tee of a tee
    delivers byte-identical data on every branch (#111), with the failing
    seed and minimal input printed, plus a fixed test for the one recorded
    schedule because seeds are random.
  Each scenario asserts its own wall time stays under a second, and every
  driven request is awaited to retire instead of detached so one scenario's
  isolate cannot leak into the next.
- Dev-only `tokio` `test-util` enables the paused clock; `proptest` (already
  a workspace dependency) is now used. Failures persist beside the crate.
- CONTRIBUTING "Testing locally" documents the pattern, the deadlines that
  must read the seam, and the ones deliberately left on `std`.
@ryuzdev ryuzdev mentioned this pull request Nov 22, 2026
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