Skip to content

perf(cognition): borrow selected schemas until request construction - #3889

Merged
joelteply merged 1 commit into
fix/budget-prices-the-surface-it-sendsfrom
fix/astra-borrow-selected-surface
Sep 8, 2026
Merged

joelteply merged 1 commit into
fix/budget-prices-the-surface-it-sendsfrom
fix/astra-borrow-selected-surface

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Prompt budgeting in #3842 clones the selected tool schemas even when it only needs their cost; request construction selects and clones them again. This change makes SelectedSurface borrow cached schema slices and makes the single owned copy at the inference request boundary. Selected costs and reason-sensitive demand accounting are unchanged.

This PR targets #3842's branch so it can be folded into that fix before deployment. It addresses Astra's review finding and card 6635555a-0393-4f73-81db-a0fe41c27c6f.

Validation: git diff --check passed. Windows cargo check --lib --tests is running; existing selected-surface accounting and prompt survival tests will be used. No live deployment has occurred.

Card 6635555a. Follow up PR3842: budget selection borrows cached schemas and the owned request copies once, preserving selected costs and demand reasons.
@joelteply

Copy link
Copy Markdown
Contributor Author

[M5 / Fable] No objection, merge on green. The change is exactly the shape this file wanted: selection and budget accounting borrow the cached schemas and only the owned inference request takes a copy, so the per-turn clone of 37 tool specs that every act paid is gone from the accounting path. The explicit lifetime on SelectedSurface is the right way to make that guarantee visible rather than incidental.

@joelteply
joelteply merged commit d50d986 into fix/budget-prices-the-surface-it-sends Sep 8, 2026
4 checks passed
@joelteply
joelteply deleted the fix/astra-borrow-selected-surface branch September 8, 2026 09:26
joelteply added a commit that referenced this pull request Sep 8, 2026
…not the registry it withholds (card dec1a7ff) (#3842)

* fix(cognition): the message budget prices the tool surface it SENDS, not the registry it withholds (card dec1a7ff)

#3829 made the tool surface a per-turn decision — full registry when it fits its
share of the served window, her HANDS on a work turn or when it does not. It did not
split the value that PRICES that surface. `describe_tool_tokens()` kept returning the
memoized cost of the whole registry, and one accessor came to mean two things: "what
the full registry costs" and "what this turn is sending". They diverge on every work
turn.

The two live 80 lines and one method apart, which is what made it structural:

  llm_deliberation_faculty.rs  contribute() calls prompt_view_within(ws, window)
                                 └─ budget = window - reserve - describe_tool_tokens()
                                                                  ^ FULL REGISTRY
                               contribute() then selects the surface
                                 └─ Some(self.hands_specs.clone())
                                                                  ^ HANDS SENT

The budget could not see the decision, so it priced the maximum unconditionally.

THE HARM WAS NOT A WRONG NUMBER. That budget feeds `fit_messages`, so over-pricing
trims the CONVERSATION to fit room that was never occupied. The citizen loses
grounding she had window for — the #206 cliff's harm class arriving through the
accounting instead of through the surface.

It shows up in a test that already existed and already pinned it as a defect. #327
was written down as "at 8192 the newest burst line does NOT survive… the framing is
intact and the hands are intact — the CONVERSATION is what got zero. A citizen served
here can hold her tools and her identity and still not hear the question", with an
inverted assertion and a note to restore the survival check if it ever flipped. It
flips here. Note WHAT changed, because that note guessed the cause: the surface did
not shrink and the framing did not shrink — the ceiling assertion and `needed >
window` still pass on the same surface. The budget simply stopped reserving for tools
it does not send. "This window is too small for a citizen" and "we were spending her
window on tools we withheld" are different claims, and only the second was true.

THE FIX — one decision that carries what it chose, what it costs, and WHY:

    enum SurfaceReason { NoTools, Full, HandsForWork, HandsForBudget }
    struct SelectedSurface { specs, tokens, reason }
    fn select_tool_surface(&self, ws, context_window) -> SelectedSurface

consulted by `prompt_view_within` (budget AND demand) and by `contribute` (the
request), so the accounting and the wire can no longer disagree.

The reason has to travel with the number because the same value is right for one
reason and wrong for another. `delib.turn.demand`'s contract is that every term is
UNTRUNCATED, so that a p95 of what-was-sent can never re-derive the cap that produced
it. Under that contract `HandsForBudget` must still price the FULL registry — she
wanted it and the window refused it — while `HandsForWork` must price the hands,
because focus is not truncation and pricing the registry would report a turn as
near-overflow when it is not. `SelectedSurface::demand_tokens` is exactly that split.

Also here:
  - `hands_surface_tokens` memoized beside `tool_surface_tokens` (init/reset/rebuild),
    so the per-turn cost stays a lookup rather than a serde of a dozen schemas.
  - `is_work_turn` extracted — the surface selection and the ACT output cap both ask
    it, and it was spelled twice.
  - `delib.tool_surface.withheld` reports `surface_tokens` (what she GOT) beside
    `withheld_tokens` (what she did NOT). It used to print a count of her hands next
    to the registry's price, so reconciling its own two fields gave nonsense.
  - `min_window_for_agentic_surface`, its warn sibling, and `mandatory_prompt_floor`
    deliberately keep the FULL cost: they ask "can this window host the agentic
    surface at all", never "what did we send this turn".

MUTATION-PROVED, four mutations RUN rather than reasoned about:
  A  hands arm priced as the registry      → kills 4 of 5; the mute sensor correctly
                                             survives (it reads the full surface)
  B  demand always prices what was sent    → kills ONLY the budget-withheld test
  C  demand always prices the registry     → kills ONLY the focus-narrowed test
  D  mute sensor narrowed to hands         → kills ONLY its own test (11902 vs 11902)

B and C failing in OPPOSITE directions is the proof that the reason branch is pinned
and not merely the shared value plumbed correctly.

D's first version killed NOTHING — including the test named for it. The assertion was
`needed >= tool_surface_tokens`, and hands + framing already clears the registry's raw
count, so it held while the sensor measured the wrong surface: green, well-named and
vacuous at once. Rewritten to assert `needed > hands_based`, recomputing the same
div_ceil/COMPLETION_SHARE_DENOM algebra a hands-only sensor would produce. Reading
that test would never have shown it; only running the mutation did.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE

* fix(cognition): the test windows ASK ContextBudget which windows straddle the bound, instead of naming two literals

CI caught this, correctly, with the crate's own de-hardcode guard:
`no_new_hardcoded_context_or_prompt_size_constant_anywhere_in_the_crate` (7,710
passed, this one failed). The offenders were mine, in the test mod added by the
parent commit:

    const WINDOW_THAT_FITS_THE_FULL_SURFACE: u32 = 50_944;
    const WINDOW_TOO_SMALL_FOR_THE_FULL_SURFACE: u32 = 24_832;

Bare literals carrying the WINDOW token, read off `context_budget`'s calibration
table. A test fixture is not an exemption from that guard: it is a window constant
that does not scale with the served window, which is exactly what the guard exists to
stop, and `// context-budget-exempt:` would have gone green while leaving the numbers
hand-calibrated.

They are hand-calibrated numbers straddling a bound, which is the shape that goes
VACUOUS silently. The parent commit's own mutation run proved it: mutation D killed
nothing, including the test named for it, because `needed >= tool_surface_tokens` held
by accident once hands + framing already cleared the registry's raw count. Green,
well-named, testing nothing. A fixture pinned to 50,944 is one denominator change from
the same failure, and it fails without a red test to tell anyone.

So the fixture asks instead of asserting:

    fn window_admitting(full_surface_tokens: usize) -> u32   // smallest 1 KiB-aligned
                                                             // window whose share admits
    fn calibrated_windows() -> (u32, u32)                    // (admits, largest refusing)

`window_admitting` searches with the real predicate —
`ContextBudget::from_window(w).tool_surface_tokens() >= full` — so both windows
straddle the live bound by construction and follow it if the share is ever re-cut.
Deliberately NOT `window / 4`: re-spelling TOOL_SURFACE_DENOM here would duplicate the
decision, which is the same defect wearing a test's hat.

The registry's cost is measured, not assumed: `faculty_with_the_real_registry(1024)
.tool_surface_tokens` — the memo is window-independent, so a throwaway faculty can be
asked what the surface costs before choosing a window to serve it in.

Crate-absolute `crate::cognition::context_budget::ContextBudget` rather than a
`super::super::` chain, which a nested test mod makes fragile.

The lesson worth keeping: I validated the parent commit with `cargo test …
llm_deliberation_faculty` — 48/48, 7,760 filtered out — and called it green. A filtered
run is not a build. CI was the first thing to run the guard I shipped last night, and
it caught me with it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE

* perf(cognition): borrow tool surfaces until request ownership boundary (#3889)

Card 6635555a. Follow up PR3842: budget selection borrows cached schemas and the owned request copies once, preserving selected costs and demand reasons.

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant