← Back to Pull requests

runtime: optional bounded admission #109

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Oct 07, 2026 12:14 UTC
Author

Required human contributor answers

1. What outcome are you trying to achieve?

Today the runtime only queues: SerialScheduler is a semaphore of one that waits and never refuses, so the only bound on a hundred requests is the caller's patience. The outcome is that "refuse when there is no room" exists as a reviewed, available capability — while nothing is wired to it, so today's deployments are unchanged.

2. What is the highest-leverage variable for that outcome?

Scope discipline: this stays optional and unwired.

A wider version of this work is what #35 was, and it was asked to stay a scope draft. What makes the narrow step mergeable is keeping the unit of change small, per the reviewer's guidance: "optional bounded admission in the existing runtime, with capacity units explicit; the full worker lifecycle can remain separate" (#35 comment).

3. How will this work move that variable rather than create busywork?

The diff is purely additive: a new module beside SerialScheduler rather than a replacement, nothing constructs it outside its tests, and no worker or frontend file is touched. It cannot regress existing behaviour, and it removes "write your own capacity counter" — a counter whose edges review has already found three times — from every worker that later wants a bound. Readiness, worker-thread ownership and drain on shutdown are deliberately left to the step that wires this up.

4. Who is the customer or user, and what do they actually need?

Two of them: the next worker author who wires admission into dispatch, and the maintainer who reads queue state.

- The worker author needs to opt in with a cost of their choosing (tokens, bytes, or just 1), and needs the capacity held for the whole of the work rather than released when the requesting task stops waiting. That is why Permit is owned and can move into spawn_blocking.
- The maintainer needs queue state published through the existing Report { depth, capacity, rejected } shape, which is already what /health carries.

After answering the four questions: is a PR needed at all to achieve this outcome?

Human decision and rationale (or explicit source reference): Yes. Source: the reviewer's guidance on #35, which named this exact narrow step as the way to start. The alternative is every worker writing its own counter, and this counter's edges — release accounting, clamping, lock poisoning — are what review found three times across this PR's history.

Provenance: these answers are grounded in the contributor's own record (issue #14's roadmap, the #35 scope thread, and this PR's review history) and were reviewed and confirmed by the contributor before being recorded here.

For a bug fix: link actual observed failure evidence.

Evidence: Not applicable — this is not a bug fix. It adds a new optional type and nothing on main constructs it, so there is no observed failure to reproduce. The edges review found while the change was under review are covered by the tests listed under Test Result.

Rebased onto main; #34 has merged, so the stack has collapsed. The diff is only this change's own four files: src/runtime/src/admission.rs, tests/runtime/admission.rs, one line in src/runtime/src/lib.rs, and the [[test]] registration in src/runtime/Cargo.toml — git diff --stat main is 4 files.

Purpose

The first step review pointed at on #35: optional bounded admission in the existing runtime, with capacity units explicit, and the worker lifecycle left out.

SerialScheduler admits one unit at a time and never refuses — a hundred requests queue behind each other and the only bound is the caller's patience. That stays the default. This is what a worker opts into when it wants a bound instead, next to the scheduler rather than in place of it.

Units are the caller's, and they are explicit

Admission counts two things: how many requests are outstanding, and what each one costs.

let admission = BoundedAdmission::new(3, Some(100));   // 3 requests, or 100 units
let permit = admission.try_admit(60)?;                  // this request costs 60

A request costs one; the cost is whatever the caller passes. A prefill worker can admit by token count, a worker with large payloads by bytes, a worker that wants neither by 1. Nothing here guesses which of those a model means — which is why the cost is a parameter rather than a documented convention, and why the type does not pick a unit for anyone.

The permit is the reservation

Capacity is held until the permit drops, so "outstanding" means accepted and not yet finished with rather than "accepted". A worker that hands work to a thread and forgets to release would be bounded forever, so release cannot be something a caller has to remember.

The permit is deliberately neither Clone nor Copy: two permits for one admission would release capacity twice, which is exactly the failure this type exists to prevent. Releasing more than was held panics rather than saturating, so a double release is visible instead of quietly drifting the counter.

Two cases a plain depth < capacity check gets wrong:

  • A request costing more than the whole unit ceiling is refused, rather than admitted and overrunning it.

  • A zero bound panics at construction. It would admit nothing at all, which is a configuration mistake; failing where it is written beats every request being turned away with no explanation.
  • The fit check and the reserve use the same saturating arithmetic, so a unit cost near usize::MAX cannot pass one and overflow the other.

    report() returns Report { depth, capacity, rejected } — the same shape #34 publishes from /health, so a worker that opts in gets queue state on the health route without new plumbing. rejected here counts refusals from try_admit only; #34's Report documents a second term, work accepted and then dropped because its caller had gone, which an admission bound cannot observe.

    Not in this PR

    Per the same guidance: worker-thread ownership, readiness transitions, drain on shutdown, and any change to SerialScheduler or to the native workers. This changes no existing behaviour — nothing is bounded until something asks for a bound, and no worker asks today.

    Test Plan

    cargo fmt --all --check
    cargo clippy --workspace --locked --all-targets -- -D warnings
    cargo test --workspace --locked
    

    tests/runtime/admission.rs, under the repository tests/ tree per CONTRIBUTING with an explicit [[test]] path:

  • a request bound refuses once full, counts the refusal, and admits again once a slot frees

  • capacity is held until the permit drops — the property that makes the bound mean anything

  • a unit bound admits by cost rather than by count, including that a large request's units come back when it finishes

  • one request costing more than the ceiling is refused rather than overrunning it, and one costing exactly the ceiling is admitted

  • the request count is reported as capacity

  • a zero request bound and a zero unit bound each panic at construction

  • clones share one bound, so a queue and its handlers cannot disagree about how much room is left
  • Test Result

    System1-Omni Version / Commit: rebased onto main 3d4ed19; head 017a71b.

    Run both locally and in CI on this head. Locally (macOS arm64, Rust 1.99.0): cargo fmt --all --check clean, cargo clippy --workspace --locked --all-targets --features omni-laya/serve -- -D warnings clean, cargo test --workspace --locked --features omni-laya/serve 190 passed, 0 failed, 28 ignored, cargo build --workspace --release --locked --features omni-laya/serve passes. In CI on 017a71b: rust, build, benchmarks and cuda-contract all success.

    The admission suite is also run in release mode (cargo test -p omni-runtime --test admission --release), because one of its regressions is an arithmetic overflow: the same sequence fails differently in each profile, so both are exercised.

    The workspace count moved from 107 (at 19c4d80) to 190 mostly because main advanced a long way while this was stacked, not because this change adds tests beyond its own: this PR contributes the 15 in tests/runtime/admission.rs.

    No new dependency, and Cargo.lock is unchanged. src/runtime/Cargo.toml gains only the [[test]] target that points at the new test file, which is how this repository registers tests.

    Rebased onto main 3d4ed19

    The stack has collapsed: #34 is merged, so this branch no longer carries #34's commits. merge-base(main, head) is main itself, and the diff here is only the four files this change owns (+555/-0). The reviewer's "rebase twice" note is therefore complete, and the rejected/413 changes it referenced are on main now rather than arriving with a rebase.

    Changes since the review of 19c4d80

  • try_admit now computes the sum once with saturating_add and uses it for both the fit check and the reserve. Previously the check saturated while the reserve added directly, so the two could disagree for a unit cost near usize::MAX. This is the reviewer's src/runtime/src/admission.rs:97 finding.

  • The rejected doc above now states the term this type can count. The finding it answers (src/runtime/src/engine.rs:41-43) is in a file this PR does not touch, so the doc change itself lives on #34 at 095d831; what this PR does is count exactly that term — BoundedAdmission increments rejected only in the refusal branch of try_admit, and never for work it accepted. At this head the rejected field's wording in Report is still the broader one, because the narrowed version arrives with the rebase.

  • Not addressed: the src/frontend/src/engine.rs:128 413-vs-malformed-body finding and the serve()/shutdown/Unavailable test gaps. Both are in #34's files rather than this change, and #34 is frozen at a reviewed head; they are follow-ups once the stack lands.
  • Demo / evidence

    N/A — no runtime behavior applies to this change. Nothing constructs a BoundedAdmission outside its tests, so there is no measurable workload, latency, throughput or memory result for this diff: the library is added and unwired, existing deployments are unchanged, and there is no model, hardware or precision configuration to record. The evidence for this change is the test suite in the Test Plan, and the commands and outcomes are in Test Result above. A serving-level measurement becomes meaningful only once a worker opts in, which is a later step.

    Self-review

  • I have reviewed the full diff and addressed the issues I found.

  • I have checked that the change follows the project's architecture and stays focused on the stated purpose.

  • I have run the checks appropriate to this change and reported commands, results, and anything I could not verify above.

  • I have checked that the PR description, documentation, and any accuracy or performance claims match the implementation and available evidence.
  • Two review findings fixed in the second commit

    A permit can now be moved into the work it was granted for. It held a &BoundedAdmission, so it could not go into the runtime's own blocking executor — Executor::run in src/runtime/src/lib.rs does spawn_blocking(move || ...) and needs 'static work, and a borrowed permit does not compile there. BoundedAdmission now wraps a shared inner, Permit owns a share of that inner, and try_admit takes &self and hands back something that outlives the handle that issued it.

    The counter can no longer be driven negative. The permit stored the units its caller asked for and released that, while the counter had been advanced by a clamped value; where the two differed, a later release underflowed and panicked. The permit now stores the units it actually reserved. The clamping went with it: a request costing more than the ceiling is refused outright, so a reservation is never larger than the budget it was admitted under, and the held total cannot reach usize::MAX by accumulation.

    Coverage added for the gaps the review named: concurrent admit/release over 32 threads for 100 rounds asserting the live count never passes the bound and all reservations come back, recovery after a panic while the counters are locked, a permit moved into another thread and released there, and the ceiling cases that used to unbalance the counter.

    Still out of scope, deliberately: worker-thread ownership, readiness transitions, and drain on shutdown. There is no admission-plus-transport integration test because nothing wires admission to a worker yet; that arrives with the step that does the wiring.

    A third review finding, fixed in the latest commit

    With no unit budget configured, the shared unit total was still being charged. try_admit's None branch added the caller's cost to a total that has no ceiling and that nothing reads in that configuration, which bought nothing and could overflow. BoundedAdmission::new(2, None) admitting usize::MAX and then 1 overflowed in a debug build; in a release build it wrapped to zero, and the next release panicked inside Drop, which is a non-unwinding panic that aborts the process.

    The total is now advanced only when a unit budget exists, and release subtracts only then, so the bounded path and its exact-once behaviour are unchanged. The reservation keeps two numbers: the caller's cost, which Permit::units() still reports unchanged, and what the total was advanced by. a_request_only_bound_does_not_accumulate_units covers the sequence in both drop orders and asserts the depth returns to zero; it fails on the previous head in both profiles and passes here.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: Levius-Fubuki Review duration: 78845m
    All Vouch review confidence checks passed
    Residual risk 0.33 = Change Risk (0.59) × (1 − Review Confidence (0.45)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.59 · 650 lines diff across 8 files
    0.59
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    44%
    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.388
    Shallow Review Depth shallow_review_depth
    0.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #109"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 44.7% 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: 59% (MEDIUM) · Higher = larger blast radius
    59%
    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: 44.7% · Lower = rushed or shallow review
    44.7%
    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: 32.6% · Safe to merge
    32.6%