diff --git a/core/continuum-cognition/fixtures/reply-output-tokens-m5-2026-10-26.json b/core/continuum-cognition/fixtures/reply-output-tokens-m5-2026-10-26.json new file mode 100644 index 0000000000..e21c61592f --- /dev/null +++ b/core/continuum-cognition/fixtures/reply-output-tokens-m5-2026-10-26.json @@ -0,0 +1 @@ +{"source":"M5 (Apple M5 Pro) prompt captures, completed generations that landed (finish != length), 24 h to 2026-10-26, usage.outputTokens (reasoning included), in capture order per mind","minds":{"Aiko":[98,119,196,576,170,1136,126,313,814,164,385,822,271,486,756,186,75,75,81,149,184,110,301,427,410,92,102,164,97,453,99,95,119,326,107,205,1095,98,99,98,223,76,78,203,84,204,679,188,493,104,105,299,612,549,369,306,99,347,180,355,248,110,159,235,337,69,118,83,170,646,60,272,110,298,609,208,347,148,458,102,621,232,224,94,397,123,296,293,81,1095,300,121,604,150,871,191,246,239,289,813,117,113,594,226,102,400,281,142,174,317,244,386,840,568,380,436,662,270,580,78,299,226,430,264,154,433,101,101,99,123,124,390,121,80,106,412,109,68,225,158,451,182,1184,323,469,141,176,476,182,1063,303,100,316,122,1102,322,166,614,165,77,105,92,92,103,244,271,81,486,531,99,125,74,410,1120,52,238,298,129,408,601,383,336,580,560,291,222,514,74,175,116,259,116,118,83,225,343,119,218,137,540,204,284,75,434,239,160,357,122,105,137,162,82,1133,187,807,250,391,194,340,689,351,75,1337,75,1118,742,120,1120,1212,673,88,432,1045,51,343,1159,566,83,124,121,1030,259,1055,51,425,1094,72,1098,1057,910,140,113,961,235,200,610,528,1097,482,92,230,665,504,111,1426,116,357,40],"Atlas":[129,255,251,267,295,126,761,231,128,134,231,420,97,346,271,830,1202,250,976,172,232,141,190,471,216,460,179,184,243,138,328,391,334,225,192,168,164,122,288,277,186,742,207,626,233,165,233,175,166,190,201,221,164,228,464,185,196,166,232,127,796,184,172,195,82,134,186,342,194,242,180,337,175,284,168,165,209,220,305,176,188,150,181,191,270,194,225,249,302,563,425,735,233,275,191,242,633,222,185,82,1040,172,166,228,138,543,112,380,168,58,264,210,392,150,384,114,538,167,522,618,615,334,176,223,392,233,264,239,375,243,358,216,841,171,201,328,883,135,165,830,332,371,458,270,482,155,1164,168,183,273,182,625,132,273,543,450,83,817,243,344,1153,527,98,389,67,133,648,100,522,621,934,252,517,172,987,77,600,168,134,828,500,383,135,573,496,494,55,646,161,1093,376,202,149,87,529,589,767,176,523,208,1076,243,518,369,1147,541,504,594,183,758,127,330,700,98,725,1234,191,330,694,489,283,353,365,554,181,776,866,383,60,97,706,63,222,318,73,310,854,351,1092,297,475,339,479,145,421,550,225,463,846,129,713,115,384,421,141,1436,385,362,565,158,951,212,195,197,243,352,151,285,285,329,370,144,723,1049,121,193,977,140,336,220,181,290,306,332,248,175,120,979,145,839,206,684,227,1135,201,174,493,333,197,108,102,171,50,173,43,150,166,140,107,212,150,141,160,294,251,204,213,498,462,278,276,77,98,356,120,205,247,188,184,196,255,288,770,79,370,1228,425,625,738,933,907,433,112,1070],"Benchy":[276,228,107,193,113,250,237,119,104,744,435,595,595,151,318,171,388,322,100,798,294,166,463,531,335,219,361,379,525,280,309,1112,541,78,637,666,806,439,222,303,473,730,316,715,160,422,716,98,458,335,387,461,197,477,235,257,451,264,76,788,323,663,65,462,269,293,89,85,428,83,222,345,219,261,146,414,1526,74,68,148,375,100,248,432,772,429,71,576,552,61,752,141,59,185,174,258,234,131,145,193,391,118,180,129,122,932,163,249,1055,224,479,679,410,628,158,303,488,247,650,173,129,1073,390,351,517,1172,760,98,685,213,498,78,541,89,416,152,802,792,356,191,125,84,433,211,439,100,207,516,252,141,160,140,239,276,61,661,151,547,252,353,684,1069,369,706,268,159,391,660,342,684,336,255,365,748,654,191,592,1114,80,907,96,477,1065],"Cyrus":[169,138,363,207,115,120,356,118,104,372,154,799,391,683,616,483,461,179,86,651,248,435,304,371,116,405,154,811],"Demetri":[110,116,247,205,91,216,75,277,211,163,139,407,98,334,188,336,268,194,282,509,154,66,381,196,92,766],"Esme":[590,620,206,238,90,227,413,569,154,390,110,104,111,382,165,1020,971,703,282,174,172,233],"Freya":[496,221,117,257,151,128,997,359,238,297,1177,739,1074,966,1087,104,364,1077,382,137,92,689,245,83,201,194],"Idris":[1291,107,525,283,370,479,757,286,215,198,351,435,337,173,285,584,328,227,751,332,280,286,251,416,141],"Joaquin":[418,356,190,1126,157,378,226,433,984,90,497,198,143,229,374,413,102,170,320,356,287,275,110,60,298],"Kira":[299,76,118,1071,81,1208,1026,316,111,97,1078,1120,69,61,305,151,125,122,81,142,221,169,348,1071,1075,123,746,151,904,96,556,106,517,1278,53],"Lorcan":[62,275,183,124,225,327,273,377,382,486,410,324,534],"Mara":[188,397,489,580,170,222,215,280,297,62,57,57,175,338],"Mathis":[285,447,358,187,376,240,179,594,415,248,418,234,741,156,79,142,147,530,404,151,132],"Rania":[178,211,596,547,475,315,284,997,595,149],"Solomon":[398,378,587,456,750,210,389,625,239,1127,769,250,472]}} \ No newline at end of file diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/types.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/types.rs index 118a48d5ef..8e9f5433e4 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/types.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/types.rs @@ -363,10 +363,12 @@ pub struct DeliberationPromptView { pub input_identity: [u8; 32], /// Cached pre-calibration cost, including selected schemas and framing. pub estimated_prompt_tokens: usize, - /// The reply's allowance this plan granted (its flex grant plus what no other claim - /// took, under its runaway bound) — charged against the window here, and carried - /// verbatim as the wire request's `max_tokens`. + /// The room this plan leaves for the reply: its flex grant, sized by her measured + /// reply tail (`ReplyTail::reserve`). Charged against the window here; the floor of + /// the request's `max_tokens`, never its ceiling ([`Self::reply_allowance`]). pub completion_reserve: u32, + /// The turn's runaway bound: a loop guard on the request, reserved by no claim. + pub reply_bound: u32, pub capacity_error: Option, /// The assembled prompt broke the one budget (`prompt/budget.rs`): the act fails and /// this prompt is never sent. @@ -400,4 +402,19 @@ impl DeliberationPromptView { .collect::>() .join("\n") } + + /// The request's `max_tokens`: the window's PHYSICAL room after this prompt, under the + /// runaway bound, never below the reserve. The reserve sizes her view; it never cuts + /// her reply: a reply longer than her measured tail writes into whatever the window + /// still has (mid-epoch, the room her view has not grown into yet), and joins the + /// tail. One token stays free: local admission requires prompt + reply < window. + pub fn reply_allowance(&self, window: u32, calibration: PromptCalibration) -> u32 { + let prompt = calibration.charge(self.estimated_prompt_tokens).min(u32::MAX as usize) as u32; + window + .saturating_sub(prompt) + .saturating_sub(1) + .min(self.reply_bound) + .max(self.completion_reserve) + .max(1) + } } diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/view.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/view.rs index 86e3b5c905..481d581ac7 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/view.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/prompt/view.rs @@ -101,6 +101,7 @@ impl LlmDeliberationFaculty { let (reply, reply_runaway) = reply_claim( self.turn_kind(ws), self.working_set.as_ref().and_then(|reg| reg.need_of(self.persona_id)), + self.working_set.as_ref().and_then(|reg| reg.reply_reserve_of(self.persona_id)), pending_peak, Self::holds_live_work(ws), ws.directed_at_self(), @@ -314,13 +315,13 @@ impl LlmDeliberationFaculty { // The reply never takes from required content: its floor is what the window leaves // after framing, tools and the required input. Its UNCLIPPED floor is her need. let reply_need = reply.floor_tokens; - // An act's reply wants its whole runaway bound, at its priority above her context's: - // what no claim took used to top it up to that bound, and her view, a claim on the - // whole window, leaves nothing untaken. Aris's act was cut at the output limit with - // 5,316 granted and 0 unallocated (the M5, 2026-10-22 00:14Z), a whole turn lost. - if matches!(self.turn_kind(ws), TurnKind::Act) { - reply.max_tokens = reply.max_tokens.max(reply_runaway); - } + // The reply claims her measured RESERVE (`reply_claim`), never the runaway bound: + // reserving 12,288 for replies measured at p99 1,202 left her view and history a + // median 30.3k of a 58,880 window (the M5, 2026-10-26, 30 `delib.window.flex` rows; + // framing 13,463 there already includes the tool schemas). A reply past the reserve is not cut by it (Aris's act + // cut at 5,316 granted, 2026-10-22, was the reserve bounding the request): the + // request carries the window's physical room after the prompt + // (`DeliberationPromptView::reply_allowance`). reply.floor_tokens = reply_need.min(context_window.saturating_sub(fixed_cost.saturating_add(required_cost))); reply.min_tokens = reply.floor_tokens; let fixed_claim = |id: &str, tokens: u32| crate::cognition::rag_budget::RagSourceBudget { @@ -372,12 +373,10 @@ impl LlmDeliberationFaculty { })); let plan = crate::cognition::rag_budget::flex_allocate(context_window, &claims); let budget_floor = crate::cognition::rag_budget::turn_need(&claims).saturating_sub(claims.iter().find(|c| c.source_id == FLEX_REPLY).map_or(0, |c| c.floor_tokens)).saturating_add(reply_need); - // Whatever no claim took is hers to write with, up to the runaway bound. + // The room the view leaves for the reply is the reply's grant. What no claim took + // is her view's to grow into; the reply may still write into it (`reply_allowance`). let reply_grant = plan.granted(FLEX_REPLY); - let completion_reserve = reply_grant - .saturating_add(plan.unallocated) - .min(reply_runaway) - .max(1) as usize; + let completion_reserve = reply_grant.max(1) as usize; continuum_base::probe!( class = "delib.window.flex", persona = %self.persona_name, @@ -392,11 +391,12 @@ impl LlmDeliberationFaculty { reply_granted = reply_grant, unallocated = plan.unallocated, reply_runaway, - allowance = completion_reserve, + reserve = completion_reserve, escalation = plan.escalation_needed, "the served window's one allocation — framing, required input, grounding, \ - history and the reply by priority; the allowance is the reply's grant plus \ - what no claim took, under its runaway bound" + history and the reply by priority; the reserve is the reply's grant (her \ + measured tail), what no claim took is her view's, and the runaway bound only \ + guards the request" ); // Grounding is optional: when its floor did not fit, it holds no room the // required input then has to do without. @@ -413,10 +413,9 @@ impl LlmDeliberationFaculty { .filter(|a| claims.iter().skip(5).any(|c| c.source_id == a.source_id)) .map(|a| a.allocated_tokens) .sum(); - // What no claim took goes to the reply up to its runaway bound; only the rest is room - // her view may grow into by appends (`fit_view`), and the fit's budget holds that same - // room, or it would drop what the epoch was allowed to keep. - let view_room = plan.unallocated.saturating_sub(reply_runaway.saturating_sub(reply_grant)); + // What no claim took is room her view may grow into by appends (`fit_view`), and the + // fit's budget holds that same room, or it would drop what the epoch was allowed to keep. + let view_room = plan.unallocated; let msg_budget = window_msg_budget.min(required_tokens.saturating_add(calibration.prompt_budget( plan.granted(FLEX_HISTORY).saturating_add(view_granted).saturating_add(view_room) as usize, ))); @@ -690,6 +689,7 @@ impl LlmDeliberationFaculty { input_identity, estimated_prompt_tokens, completion_reserve: completion_reserve as u32, + reply_bound: reply_runaway, capacity_error, budget_fault, protocol_error, diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/reply_claim.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/reply_claim.rs index b9068c176a..03f096f660 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/reply_claim.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/reply_claim.rs @@ -19,9 +19,12 @@ const PASS_RUNAWAY_MULTIPLE: u32 = 2; /// ([`LlmDeliberationFaculty::COMPLETION_FLOOR_TOKENS`]); an ACT floors at her measured /// answer channel (the tool call itself). The caller caps it so required input always /// fits — the reply never takes from required content. -/// - max: what she is expected to write — her measured need, or the reply-sized cold -/// prior when unmeasured; at least twice a pending cut's peak (the cut write gets its -/// room back on the retry). Never past the runaway bound. +/// - max: her REPLY RESERVE — the max of her last measured outputs × 5/4 +/// ([`crate::cognition::working_set::ReplyTail`]), or the reply-sized cold prior when +/// unmeasured; at least twice a pending cut's peak (the cut write gets its room back on +/// the retry). Never past the runaway bound. The reserve sizes the room her view leaves; +/// it never bounds the reply: the request carries the window's physical room after the +/// prompt (`DeliberationPromptView::reply_allowance`). /// - priority: an ambient pass 4, a directed pass 6, an act 8, an act on live held work /// or after a pending cut 10 — the weight the reply grows by against history (5) and /// grounding (6). @@ -34,10 +37,12 @@ const PASS_RUNAWAY_MULTIPLE: u32 = 2; /// priority, so priority is what decides. /// /// The runaway bound: [`LlmDeliberationFaculty::ACT_OUTPUT_CAP`] for an act; for a pass, -/// twice her measured turn, never below the act's cap. +/// twice her measured turn, never below the act's cap. A loop guard on the request only: +/// no claim reserves it. pub fn reply_claim( kind: TurnKind, need: Option, + reserve: Option, pending_peak: u32, live_work: bool, directed: bool, @@ -52,8 +57,8 @@ pub fn reply_claim( _ => LlmDeliberationFaculty::COMPLETION_FLOOR_TOKENS, } .min(runaway); - let wanted = need - .map_or(LlmDeliberationFaculty::COMPLETION_COLD_PRIOR_TOKENS, |n| n.total()) // map_or: unmeasured = a REPLY-sized prior, never a window fraction + let wanted = reserve + .unwrap_or(LlmDeliberationFaculty::COMPLETION_COLD_PRIOR_TOKENS) // unwrap_or: unmeasured = a REPLY-sized prior, never a window fraction .max(pending_peak.saturating_mul(2)) .max(floor) .min(runaway); diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/binding_and_history.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/binding_and_history.rs index 481bdb2d78..bc513ceea1 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/binding_and_history.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/binding_and_history.rs @@ -398,7 +398,7 @@ fn catalog_fits_the_minimum_serving_window() { let framing = estimate_guard_tokens(&collapsed); // The reply's floor — what the window always holds for it — derived from the // claim itself, never re-spelled. Above it the reply grows by priority. - let reserve = reply_claim(TurnKind::Pass, None, 0, false, false).0.floor_tokens as usize; + let reserve = reply_claim(TurnKind::Pass, None, None, 0, false, false).0.floor_tokens as usize; assert!( framing + reserve < window as usize, "framing+menu ({framing}) + reserve ({reserve}) must leave burst room in {window}" diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/reply_reserve.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/reply_reserve.rs index 1c1bb5d0af..12e2760152 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/reply_reserve.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/reply_reserve.rs @@ -37,9 +37,10 @@ fn prompt_plus_completion_cap_never_exceeds_the_served_window() { // Same atomic snapshot the production `contribute` path uses — the model // binding carries the served window the request is bounded to. let binding = faculty.binding.load_full(); + let allowance = view.reply_allowance(window, PromptCalibration::default()); let request = faculty.build_request_within( &binding, - view.completion_reserve, + allowance, view.messages.clone(), None, view.system.clone(), @@ -51,10 +52,8 @@ fn prompt_plus_completion_cap_never_exceeds_the_served_window() { let cap = request .max_tokens .expect("deliberation must bound generation to the reserved room"); - assert_eq!( - cap, view.completion_reserve, - "the generation cap IS the reserved room — one source of truth" - ); + assert_eq!(cap, allowance, "the generation cap IS the reply's physical room — one source of truth"); + assert!(cap >= view.completion_reserve, "never below the room the plan reserved"); // The closed invariant: prompt-at-ceiling + the generation cap fits n_ctx. let prompt_tokens = estimate_guard_tokens(&view.system) + estimate_guard_tokens(&view.user_text()); assert!( @@ -161,7 +160,7 @@ fn measured_emissions_size_the_reserve_and_capped_turns_grow_it_back() { .with_context_window(window) .with_working_set(reg.clone()); let wanted = |who: Uuid, pending: u32| { - reply_claim(TurnKind::Pass, reg.need_of(who), pending, false, false).0.max_tokens + reply_claim(TurnKind::Pass, reg.need_of(who), reg.reply_reserve_of(who), pending, false, false).0.max_tokens }; let cold = wanted(persona, 0); @@ -266,6 +265,46 @@ fn measured_reserve_recovers_past_a_censored_large_reply() { } } +// what this catches: an act reserving its runaway bound. On the M5 (2026-10-26) every +// act reserved 12,288 of a 58,880 window for replies measured at p99 1,202 and max +// 1,526, leaving her view and history a median 30.3k of it. The reserve is her +// measured tail (max × 5/4); the request still carries the window's physical room, so a +// reply past the tail is never cut by it. +#[test] +fn an_act_reserves_her_measured_tail_and_may_write_past_it() { + use crate::cognition::working_set::{EmissionStop, WorkingSetRegistry}; + let window = 58_880u32; + let persona = Uuid::new_v4(); + let reg = WorkingSetRegistry::new(); + for (tick, output) in [252u32, 792, 1_202, 300].into_iter().enumerate() { + reg.record_emission_in_memory(persona, output, output / 2, EmissionStop::Landed, tick as u64); + } + assert_eq!(reg.reply_reserve_of(persona), Some(1_503), "max 1,202 × 5/4"); + let faculty = LlmDeliberationFaculty::new( + persona, + "Aiko", + "You are Aiko.", + Arc::new(HeuristicInferenceAdapter::new()), + ) + .with_context_window(window) + .with_tools(vec![read_tool()]) + .with_working_set(reg); + let ws = writing_workspace(crate::identity::ActivityRoom::mint(), 40, true); + assert_eq!(faculty.turn_kind(&ws), TurnKind::Act); + let view = faculty.prompt_view_within(&ws, window); + assert!(view.capacity_error.is_none(), "{:?}", view.capacity_error); + assert!(view.budget_fault.is_none(), "{:?}", view.budget_fault); + assert!( + (LlmDeliberationFaculty::COMPLETION_FLOOR_TOKENS..=1_503).contains(&view.completion_reserve), + "the act reserves her tail, never the runaway bound: {}", + view.completion_reserve + ); + let allowance = view.reply_allowance(window, PromptCalibration::default()); + assert!(allowance > view.completion_reserve, "a reply past her tail writes into the window's room"); + assert!(allowance <= LlmDeliberationFaculty::ACT_OUTPUT_CAP, "the runaway bound still guards"); + assert!(view.estimated_prompt_tokens + (allowance as usize) < window as usize, "inside the window"); +} + // what this catches: KV-prefix cache locality — session-stable standing framing // (roster/doctrine/map) must serialize BEFORE volatile grounding (recall) even // when the volatile bid scores HIGHER salience, so the stable sections sit in the diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/turn_window.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/turn_window.rs index 89e00aa1e9..ea1ac6367f 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/turn_window.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/prompt_shaping/turn_window.rs @@ -721,7 +721,7 @@ fn a_held_work_card_survives_budget_pressure_that_drops_everything_else() { // (`persona.act.think_only reasoning_len=2730`, `2112`): no answer, no act. And // (2026-10-18 02:10Z) Benchy's first write cut mid-call against a reserve of twice // her read-only peak. Pinned on the pure claim: an unmeasured reply wants a -// reply-sized prior, never a constant floor; a measured need is wanted whole; an +// reply-sized prior, never a constant floor; her measured reply tail is wanted whole; an // act floors at her answer channel; a pending cut doubles back; priority follows // the turn (ambient 4, directed 6, act 8, act on live work or after a cut 10); the // runaway bounds hold; the time/need terms are reported, never the bound; and the @@ -739,28 +739,32 @@ fn the_reply_claim_holds_the_reasoning_channel_under_its_runaway_bound() { (c.floor_tokens, c.max_tokens, c.priority, r) }; // Unmeasured: a reply-sized prior, never 768 or any constant floor. - assert_eq!(shape(reply_claim(TurnKind::Pass, None, 0, false, false)), (floor, prior, 4, cap)); - assert_eq!(shape(reply_claim(TurnKind::Pass, None, 0, false, true)), (floor, prior, 6, cap)); - assert_eq!(shape(reply_claim(TurnKind::Act, None, 0, false, false)), (floor, prior, 8, cap)); - assert_eq!(shape(reply_claim(TurnKind::Act, None, 0, true, false)).2, 10, "live held work"); - assert_eq!(shape(reply_claim(TurnKind::Act, None, 1, false, false)).2, 10, "a pending cut"); + assert_eq!(shape(reply_claim(TurnKind::Pass, None, None, 0, false, false)), (floor, prior, 4, cap)); + assert_eq!(shape(reply_claim(TurnKind::Pass, None, None, 0, false, true)), (floor, prior, 6, cap)); + assert_eq!(shape(reply_claim(TurnKind::Act, None, None, 0, false, false)), (floor, prior, 8, cap)); + assert_eq!(shape(reply_claim(TurnKind::Act, None, None, 0, true, false)).2, 10, "live held work"); + assert_eq!(shape(reply_claim(TurnKind::Act, None, None, 1, false, false)).2, 10, "a pending cut"); // The M5's shape: a mind that thinks ~900 tokens before a 300-token answer. let need = OutputNeed { reasoning: 900, answer: 300, turns: 5 }; - let (_, wanted, _, runaway) = shape(reply_claim(TurnKind::Pass, Some(need), 0, false, false)); - assert_eq!(wanted, 1_200, "her measured think + answer, whole"); + let (_, wanted, _, runaway) = shape(reply_claim(TurnKind::Pass, Some(need), Some(need.total()), 0, false, false)); + assert_eq!(wanted, 1_200, "her measured reply tail, whole"); + // The RESERVE decides what the reply claims, never the need or the runaway bound: the + // M5's residents wrote at most 1,526 (2026-10-26), and the act once claimed 12,288. + let act = shape(reply_claim(TurnKind::Act, Some(need), Some(1_908), 0, false, false)); + assert_eq!((act.1, act.3), (1_908, cap), "an act claims her tail; the cap only guards"); assert_eq!(runaway, cap, "a small need still gets the act's cap as its bound"); // Kimi (the 5090, 2026-10-06): an act floors at her answer channel and wants // her whole turn; a pass is bounded at twice her p90 turn. let kimi = OutputNeed { reasoning: 6_100, answer: 4_077, turns: 32 }; - assert_eq!(shape(reply_claim(TurnKind::Act, Some(kimi), 0, false, false)), (4_077, 10_177, 8, cap)); - assert_eq!(shape(reply_claim(TurnKind::Pass, Some(kimi), 0, false, false)).3, 20_354); + assert_eq!(shape(reply_claim(TurnKind::Act, Some(kimi), Some(kimi.total()), 0, false, false)), (4_077, 10_177, 8, cap)); + assert_eq!(shape(reply_claim(TurnKind::Pass, Some(kimi), Some(kimi.total()), 0, false, false)).3, 20_354); // A pending cut doubles back (cf9e's 3,587 → 7,174), under the runaway bound. - assert_eq!(shape(reply_claim(TurnKind::Pass, Some(need), 3_587, false, false)).1, 7_174); - assert_eq!(shape(reply_claim(TurnKind::Act, Some(kimi), 7_174, false, false)).1, cap); - assert_eq!(shape(reply_claim(TurnKind::Pass, Some(kimi), 7_174, false, false)).1, 14_348); + assert_eq!(shape(reply_claim(TurnKind::Pass, Some(need), Some(need.total()), 3_587, false, false)).1, 7_174); + assert_eq!(shape(reply_claim(TurnKind::Act, Some(kimi), Some(kimi.total()), 7_174, false, false)).1, cap); + assert_eq!(shape(reply_claim(TurnKind::Pass, Some(kimi), Some(kimi.total()), 7_174, false, false)).1, 14_348); // A runaway need never claims past the bound, floor included. let huge = OutputNeed { reasoning: 30_000, answer: 20_000, turns: 9 }; - assert_eq!(shape(reply_claim(TurnKind::Act, Some(huge), 0, false, false)), (cap, cap, 8, cap)); + assert_eq!(shape(reply_claim(TurnKind::Act, Some(huge), Some(huge.total()), 0, false, false)), (cap, cap, 8, cap)); // The terms beside the allowance: reported, never the bound. let a = output_allowance(TurnKind::Pass, Some(12.0), None, 6_932); assert_eq!((a.allowance, a.time_term, a.need_term), (6_932, Some(720), None)); @@ -802,14 +806,15 @@ fn the_reply_claim_holds_the_reasoning_channel_under_its_runaway_bound() { crate::cognition::working_set::EmissionStop::CutMidAnswer); } -// what this catches: the request carries the view's allowance VERBATIM — the -// prompt plan's flex grant — on an act and on a pass alike. An unmeasured mind on -// a roomy window gets what no other claim took, up to the runaway bound: the -// reserve that left 30k of an idle window unused while her reply was cut (the -// two-step yield) cannot come back, and the act bound still holds (losing it -// reproduces the 5,316-token act, 157 s on the lane). +// what this catches: the request carries the reply's PHYSICAL room — the window +// after the prompt, under the runaway bound — on an act and on a pass alike, while +// the plan RESERVES only the reply's claim. An unmeasured mind reserves the reply-sized +// prior, never the runaway bound (12,288 of 58,880 on the M5, 2026-10-26, against +// replies of max 1,526), and her reply is still not cut at the reserve: what no claim +// took is room she may write into (Aris's act cut at a 5,316 grant, 2026-10-22, was +// the reserve bounding the request). #[tokio::test] -async fn an_unmeasured_turn_carries_its_grant_under_the_runaway_bound() { +async fn an_unmeasured_turn_reserves_a_reply_and_may_write_into_the_window() { let window = 32_768u32; let persona = Uuid::new_v4(); let adapter: Arc = Arc::new(HeuristicInferenceAdapter::new()); @@ -824,9 +829,11 @@ async fn an_unmeasured_turn_carries_its_grant_under_the_runaway_bound() { let view = faculty.prompt_view(&ws); assert_eq!( view.completion_reserve, - LlmDeliberationFaculty::ACT_OUTPUT_CAP, - "an idle window's slack is hers to write with, up to the runaway bound" + LlmDeliberationFaculty::COMPLETION_COLD_PRIOR_TOKENS, + "an unmeasured reply reserves what a reply costs, never the runaway bound" ); + let allowance = view.reply_allowance(window, PromptCalibration::default()); + assert_eq!(allowance, LlmDeliberationFaculty::ACT_OUTPUT_CAP, "an idle window's room, up to the runaway bound"); let binding = faculty.binding.load_full(); for (kind, purpose) in [ (TurnKind::Act, "cognition/act"), @@ -834,7 +841,7 @@ async fn an_unmeasured_turn_carries_its_grant_under_the_runaway_bound() { ] { let request = faculty.build_request_within( &binding, - view.completion_reserve, + allowance, view.messages.clone(), None, view.system.clone(), @@ -842,7 +849,7 @@ async fn an_unmeasured_turn_carries_its_grant_under_the_runaway_bound() { Some(ws.room_id), kind, ); - assert_eq!(request.max_tokens, Some(view.completion_reserve), "{purpose}: the grant, verbatim"); + assert_eq!(request.max_tokens, Some(allowance), "{purpose}: the allowance, verbatim"); assert_eq!(request.purpose.as_deref(), Some(purpose)); } } diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/capacity_and_wire.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/capacity_and_wire.rs index 5a66c9f7ec..a7fb02f270 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/capacity_and_wire.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/capacity_and_wire.rs @@ -204,11 +204,14 @@ async fn prompt_preserves_stimulus_and_large_action_on_the_wire() { .as_ref() .unwrap() .contains("Held activity context")); + // The wire carries the window's physical room after the prompt (`reply_allowance`), + // never below the reserve the plan left: a reply past her measured tail is not cut. assert_eq!( request.max_tokens, - Some(view.completion_reserve), - "the wire carries the plan's grant verbatim" + Some(view.reply_allowance(window, PromptCalibration::default())), + "the wire carries the reply's physical room" ); + assert!(request.max_tokens.unwrap() >= view.completion_reserve); let schema_tokens = crate::cognition::tool_surface::tool_surface_tokens_of(request.tools.as_ref().unwrap()); assert_eq!( @@ -548,3 +551,37 @@ fn an_over_budget_prompt_is_a_budget_fault_never_a_clipped_prompt() { assert!(fault.contains("prompt budget violated"), "{fault}"); assert!(view.messages.first().is_some_and(|m| m.content_text().contains("turn_0 ")), "nothing was cut to comply"); } + +// what this catches: her view cut to pay for a reply she has not written. The request +// carries the window's physical room after an ESTIMATED prompt; when the engine counts +// the prompt a little larger, only the room past the reserve overflowed. The faculty +// re-sizes the reply from the measured count and sends the same view, whole, once, +// instead of refitting (dropping history) for the overshoot. +#[tokio::test] +async fn an_overshooting_reply_room_is_requoted_never_paid_for_with_her_view() { + let window = 32_768u32; + let adapter = Arc::new(ScriptedAdapter::new(vec![make_response(FinishReason::Stop, "PASS", None)])); + let mut attempt = 0; + *adapter.on_request.lock().unwrap() = Some(Box::new(move |request| { + if attempt > 0 { + return None; + } + attempt += 1; + // The engine counted 200 more prompt tokens than the request left room for. + Some(crate::ai::inference_error::InferenceError::ContextExceeded { + requested: window - request.max_tokens.expect("bounded") + 200, + available: window, + }) + })); + let faculty = LlmDeliberationFaculty::new(Uuid::new_v4(), "Ivar", "You are Ivar.", adapter.clone()) + .with_context_window(window); + let ws = history_with_stimulus("LATEST: did the deploy fix land?"); + let outcome = faculty.contribute(&ws).await.expect("a verdict or named fault"); + assert!(outcome.fault.is_none(), "{:?}", outcome.fault); + let seen = adapter.seen.lock().unwrap(); + assert_eq!(seen.len(), 2, "one re-quote, then the turn"); + let texts = |r: &TextGenerationRequest| r.messages.iter().map(|m| m.content_text().to_string()).collect::>(); + assert_eq!(texts(&seen[0]), texts(&seen[1]), "her view is sent whole again, nothing dropped"); + let first = seen[0].max_tokens.expect("bounded"); + assert_eq!(seen[1].max_tokens, Some(first - 201), "the measured physical room, one token free"); +} diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/window_feedback.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/window_feedback.rs index f0f9bd921d..8e757ebbcf 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/window_feedback.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/tests/verdicts/window_feedback.rs @@ -66,7 +66,7 @@ async fn live_window_reductions_bound_actual_requests_and_persist() { request.tools.as_ref().expect("native tools retained"), ); assert_eq!(schemas, faculty.select_tool_surface(&ws).tokens); - assert_eq!(request.max_tokens, Some(expected_view.completion_reserve)); + assert_eq!(request.max_tokens, Some(expected_view.reply_allowance(expected, PromptCalibration::default()))); let cost = LlmDeliberationFaculty::framing_cost( request.system_prompt.as_deref().expect("system framing"), ) + LlmDeliberationFaculty::messages_cost(&request.messages) @@ -149,7 +149,7 @@ async fn live_window_observation_cannot_overwrite_a_newer_binding() { assert_eq!(seen[0].model.as_deref(), Some("original-model")); assert_eq!( seen[0].max_tokens, - Some(faculty.prompt_view_within(&ws, 16_384).completion_reserve) + Some(faculty.prompt_view_within(&ws, 16_384).reply_allowance(16_384, PromptCalibration::default())) ); } let verdict = faculty.contribute(&ws).await.expect("next verdict"); @@ -165,7 +165,7 @@ async fn live_window_observation_cannot_overwrite_a_newer_binding() { Some( faculty .prompt_view_within(&ws, next_window) - .completion_reserve + .reply_allowance(next_window, PromptCalibration::default()) ) ); } @@ -206,7 +206,7 @@ async fn provider_context_feedback_refits_and_captures_each_attempt() { if residual { let changed_wm = wm.clone(); let mut attempt = 0; - *adapter.on_request.lock().unwrap() = Some(Box::new(move |request| { + *adapter.on_request.lock().unwrap() = Some(Box::new(move |_request| { let excess = match attempt { 0 => 337, 1 => 43, @@ -216,8 +216,10 @@ async fn provider_context_feedback_refits_and_captures_each_attempt() { changed_wm.record_receipt("arrived_after_frozen_quote"); } attempt += 1; + // The PROMPT overflows the window by `excess` past the reply's floor, so + // this is a refit, never a re-quote of the reply's physical room. Some(InferenceError::ContextExceeded { - requested: window - request.max_tokens.expect("actual reserved output") + excess, + requested: window - LlmDeliberationFaculty::COMPLETION_FLOOR_TOKENS + excess, available: window, }) })); @@ -305,7 +307,8 @@ async fn provider_context_feedback_refits_and_captures_each_attempt() { let ask = pair[1].messages.iter().position(|m| m.content_text().contains(stimulus)).unwrap(); assert!(ground[0] < ask); assert_eq!(pair[0].system_prompt, pair[1].system_prompt); - assert_eq!(pair[0].max_tokens, pair[1].max_tokens); + // The reply's room is re-derived from each refit's measured prompt. + assert!(pair[1].max_tokens.expect("bounded") >= LlmDeliberationFaculty::COMPLETION_FLOOR_TOKENS); assert_eq!(serde_json::to_value(&pair[0].tools).unwrap(), serde_json::to_value(&pair[1].tools).unwrap()); assert!(LlmDeliberationFaculty::messages_cost(&pair[1].messages) < LlmDeliberationFaculty::messages_cost(&pair[0].messages)); @@ -362,8 +365,10 @@ async fn provider_context_feedback_refits_and_captures_each_attempt() { r.tools.as_deref().expect("selected tools"), ) }; - let measured_first = if residual { window - first.max_tokens.unwrap() + 337 } else { 29_722 }; - let observed = PromptCalibration::observed(cost(first), measured_first, None) + // The final request's room was sized by the LAST refusal's measured density. + let penultimate = &seen[seen.len() - 2]; + let measured = if residual { window - LlmDeliberationFaculty::COMPLETION_FLOOR_TOKENS + 43 } else { 29_722 }; + let observed = PromptCalibration::observed(cost(penultimate), measured, None) .expect("positive actual request observation"); assert!( observed.charge(cost(second)) diff --git a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs index c6985640af..42f817f40f 100644 --- a/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs +++ b/core/continuum-cognition/src/cognition/llm_deliberation_faculty/verdict/contribute.rs @@ -126,6 +126,9 @@ impl LlmDeliberationFaculty { let mut gen_await_ms = 0u64; // The allowance the request actually carried (set where it is built, read at the seam). let mut sent_allowance: Option = None; + // The measured prompt the reply's room was last re-quoted at (below): a re-quote + // needs a strictly larger count, so it is bounded by the window. + let mut reply_room_requoted: Option = None; // Correct only frozen admitted input, consuming a finite optional unit on // every retry. Exact measured progress is required too. No accepted cognition // is replayed, and no working-memory or RAG source is re-read or refilled. @@ -235,7 +238,7 @@ impl LlmDeliberationFaculty { let request = self.build_request_within( &binding, - view.completion_reserve, + view.reply_allowance(fit_window, calibration), view.messages.clone(), tools, view.system.clone(), @@ -261,7 +264,7 @@ impl LlmDeliberationFaculty { // The allowance belongs to THIS view, refreshed on every refit: the template // is built once, and a template's `max_tokens` from an earlier plan would // bound the reply to a window the prompt no longer leaves. - request.max_tokens = Some(view.completion_reserve.max(1)); + request.max_tokens = Some(view.reply_allowance(fit_window, calibration)); let estimated_prompt_tokens = view.estimated_prompt_tokens; if rejected_prompt_tokens.is_some_and(|previous| estimated_prompt_tokens >= previous) { return Some(Contribution::deliberation_fault( @@ -314,6 +317,25 @@ impl LlmDeliberationFaculty { corrective_replay_used = rejected_prompt_tokens.is_some(), "provider capacity refusal: retained measured token density for prompt fitting" ); + // Only the reply's room past its reserve overflowed: the measured prompt and + // the reserve fit. Her view is not cut to make room for a reply she has not + // written; the calibration just learned the prompt's exact count, so the + // next allowance is the window's true physical room (`reply_allowance`). + if reply_room_requoted.is_none_or(|previous| requested > previous) + && requested.saturating_add(view.completion_reserve) < available + { + reply_room_requoted = Some(requested); + continuum_base::probe!( + class = "delib.reply.room_requoted", + persona = %self.persona_name, + requested_tokens = requested, + available_tokens = available, + completion_reserve = view.completion_reserve, + "the reply's physical room overshot an estimated prompt; re-sized from \ + the measured count, her view kept whole" + ); + continue; + } if rejected_measured_tokens.is_some_and(|previous| requested >= previous) { return Some(Contribution::deliberation_fault( "exact prompt correction made no measured progress; refusing further admission replay", @@ -321,8 +343,11 @@ impl LlmDeliberationFaculty { } rejected_prompt_tokens = Some(estimated_prompt_tokens); rejected_measured_tokens = Some(requested); + let view_reserve = view.completion_reserve; + // The refit makes room for the RESERVE, never the physical allowance: her + // view is not cut for a reply longer than her measured tail. view = match self.refit_rejected_prompt( - view, requested, available, sent_allowance.unwrap_or(0), + view, requested, available, view_reserve, ) { Ok(view) => view, Err(error) => { diff --git a/core/continuum-cognition/src/cognition/working_set.rs b/core/continuum-cognition/src/cognition/working_set.rs index e442340015..d08b8777cd 100644 --- a/core/continuum-cognition/src/cognition/working_set.rs +++ b/core/continuum-cognition/src/cognition/working_set.rs @@ -58,6 +58,9 @@ use dashmap::DashMap; use serde::{Deserialize, Serialize}; use uuid::Uuid; +mod reply_tail; +pub use reply_tail::ReplyTail; + /// The process's registry handle — the ONE place a spawning mind and the serving /// daemon on the same core meet. /// @@ -288,6 +291,10 @@ pub struct PersonaEmission { /// Turns recorded into the rings (saturating). `< MIN_NEED_TURNS` = no need yet. #[serde(default)] pub need_turns: u32, + /// Her last whole outputs, the ring her REPLY RESERVE is read from ([`ReplyTail`]). + /// A file from before this field loads an empty ring: no reserve measured yet. + #[serde(default)] + pub reply_tail: ReplyTail, } /// How a generation ENDED, as the emission record has to know it. The registry sizes @@ -660,6 +667,7 @@ impl WorkingSetRegistry { e.reasoning_samples[slot] = reasoning; e.answer_samples[slot] = answer; e.need_turns = e.need_turns.saturating_add(1); + e.reply_tail.push(observed); }; *self .emitted @@ -700,6 +708,7 @@ impl WorkingSetRegistry { reasoning_samples: [0; NEED_SAMPLES], answer_samples: [0; NEED_SAMPLES], need_turns: 0, + reply_tail: ReplyTail::default(), }; push_need(&mut e); e @@ -727,6 +736,12 @@ impl WorkingSetRegistry { }) } + /// The room her view leaves for the reply: the max of her last measured outputs + /// × 5/4 ([`ReplyTail::reserve`]). `None` until three turns are measured. + pub fn reply_reserve_of(&self, persona: Uuid) -> Option { + self.emission_of(persona)?.reply_tail.reserve() + } + /// Atomic tmp+rename so a crash mid-write never leaves a torn file that would /// fail to parse and silently wake her at the cold-start window. fn save(persona: Uuid, demand: &PersonaDemand) { diff --git a/core/continuum-cognition/src/cognition/working_set/reply_tail.rs b/core/continuum-cognition/src/cognition/working_set/reply_tail.rs new file mode 100644 index 0000000000..841f25425f --- /dev/null +++ b/core/continuum-cognition/src/cognition/working_set/reply_tail.rs @@ -0,0 +1,153 @@ +//! A mind's REPLY RESERVE, from the tail of what she has measurably written. +//! +//! The reserve is the room her view leaves for the reply. It was a constant, the act's +//! runaway bound (12,288 tokens), on a window of 58,880 whose replies measured p99 1,202 +//! and max 1,526 (the M5, 24 h to 2026-10-26, 1,063 completions, reasoning included): a +//! fifth of the window held for a reply eight times longer than any she wrote, leaving +//! her view and history a median 30.3k (30 `delib.window.flex` rows). +//! +//! The reserve is now the max of her last [`REPLY_TAIL_SAMPLES`] measured outputs × 5/4. +//! Its error bound is stated and checked: replayed over those captures (each reserve read +//! only from the turns before it), 2.1% of replies exceed it (`tests` below, against the +//! committed fixture). A reply longer than the reserve is never clipped by it: the request +//! carries the window's physical room after the prompt, not the reserve +//! (`DeliberationPromptView::reply_allowance`), and the longer reply joins the ring, so +//! the next reserve holds it. + +use serde::{Deserialize, Serialize}; + +/// Turns the tail is read from. With the max of N exchangeable samples, the next one +/// exceeds it with probability 1/(N+1); 64 keeps that near 1.5% before headroom. +// derived-or-floor: a SAMPLE COUNT, the statistic's window, not a bound: the reserve is the measured max over it, and its exceed rate is checked against the M5 captures below +pub const REPLY_TAIL_SAMPLES: usize = 64; +/// Turns observed before the tail sizes a reserve: the same bar the need asks. +// derived-or-floor: a TRUST bar on the sample count; below it the cold prior stands, so it never clips a measured value +const MIN_TAIL_TURNS: u32 = 3; +/// Headroom over the max (5/4), an integer ratio like the need's. +// derived-or-floor: a ratio on a measured max that only ever raises the reserve; its exceed rate (2.1%) is the validator below +const TAIL_HEADROOM_NUM: u32 = 5; +const TAIL_HEADROOM_DEN: u32 = 4; + +/// The last [`REPLY_TAIL_SAMPLES`] whole outputs (think + answer) of one mind, a ring. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(from = "TailWire", into = "TailWire")] +pub struct ReplyTail { + samples: [u32; REPLY_TAIL_SAMPLES], + /// Samples pushed (saturating); the cursor is `turns % REPLY_TAIL_SAMPLES`. + turns: u32, +} + +impl Default for ReplyTail { + fn default() -> Self { + Self { samples: [0; REPLY_TAIL_SAMPLES], turns: 0 } + } +} + +impl ReplyTail { + /// One measured output, in the server's tokens. + pub fn push(&mut self, output_tokens: u32) { + self.samples[self.turns as usize % REPLY_TAIL_SAMPLES] = output_tokens; + self.turns = self.turns.saturating_add(1); + } + + /// The reserve her view leaves for the reply: the ring's max × 5/4. `None` below + /// [`MIN_TAIL_TURNS`]: unknown is not zero, the caller keeps its cold prior. + pub fn reserve(&self) -> Option { + if self.turns < MIN_TAIL_TURNS { + return None; + } + let filled = (self.turns as usize).min(REPLY_TAIL_SAMPLES); + let max = self.samples[..filled].iter().copied().max()?; + Some(max.saturating_mul(TAIL_HEADROOM_NUM).div_ceil(TAIL_HEADROOM_DEN)) + } +} + +/// The durable form: serde derives arrays only up to 32, so the ring is a list on disk. +/// A list of another length (a file from a different ring size) keeps its newest +/// samples in order; `turns` restarts at what it kept, so the cursor stays honest. +#[derive(Serialize, Deserialize)] +struct TailWire { + samples: Vec, + turns: u32, +} + +impl From for TailWire { + fn from(tail: ReplyTail) -> Self { + let filled = (tail.turns as usize).min(REPLY_TAIL_SAMPLES); + let start = if (tail.turns as usize) < REPLY_TAIL_SAMPLES { 0 } else { tail.turns as usize % REPLY_TAIL_SAMPLES }; + let samples = (0..filled).map(|i| tail.samples[(start + i) % REPLY_TAIL_SAMPLES]).collect(); + Self { samples, turns: tail.turns } + } +} + +impl From for ReplyTail { + fn from(wire: TailWire) -> Self { + let mut tail = Self::default(); + let keep = wire.samples.len().min(REPLY_TAIL_SAMPLES); + for &sample in &wire.samples[wire.samples.len() - keep..] { + tail.push(sample); + } + tail + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // what this catches: the reserve's stated error bound drifting. Replays the M5's + // landed outputs (24 h to 2026-10-26, reasoning tokens included) per mind, in order, + // each reserve read only from that mind's earlier turns, and asserts the measured + // rates: at most 2.1% of replies exceed the reserve, and the median reserve is a + // reply's size, far under the 12,288 runaway bound it replaces. + #[test] + fn the_tail_reserve_holds_the_measured_exceed_rate_on_the_m5_captures() { + #[derive(Deserialize)] + struct Fixture { + minds: std::collections::BTreeMap>, + } + let fixture: Fixture = serde_json::from_str(include_str!( + "../../../fixtures/reply-output-tokens-m5-2026-10-26.json" + )) + .expect("the committed fixture parses"); // JUSTIFIED: a committed test fixture + let (mut sized, mut exceeded) = (0usize, 0usize); + let mut reserves = Vec::new(); + for outputs in fixture.minds.values() { + let mut tail = ReplyTail::default(); + for &output in outputs { + if let Some(reserve) = tail.reserve() { + sized += 1; + exceeded += usize::from(output > reserve); + reserves.push(reserve); + } + tail.push(output); + } + } + assert!(sized > 1_000, "the replay covers the fixture: {sized}"); + assert!(exceeded * 1_000 <= sized * 21, "{exceeded} of {sized} exceeded the reserve"); + reserves.sort_unstable(); + let median = reserves[reserves.len() / 2]; + assert!(median * 4 < 12_288, "median reserve {median}"); + } + + // what this catches: a cold ring sizing a reserve from one tiny ack, and the durable + // list losing order or the cursor across a save (a restart must not re-earn the tail). + #[test] + fn the_tail_waits_for_three_turns_and_survives_a_save_in_order() { + let mut tail = ReplyTail::default(); + tail.push(40); + tail.push(1_000); + assert_eq!(tail.reserve(), None); + tail.push(200); + assert_eq!(tail.reserve(), Some(1_250)); + for n in 0..(REPLY_TAIL_SAMPLES as u32 + 5) { + tail.push(100 + n); + } + let reloaded: ReplyTail = + serde_json::from_str(&serde_json::to_string(&tail).expect("serializes")).expect("parses"); // JUSTIFIED: test + assert_eq!(reloaded.reserve(), tail.reserve(), "the 1,000 aged out, the newest 64 kept"); + assert_eq!(reloaded.reserve(), Some((100 + REPLY_TAIL_SAMPLES as u32 + 4) * 5 / 4)); + let legacy: ReplyTail = serde_json::from_str(r#"{"samples":[9,8],"turns":2}"#).expect("parses"); // JUSTIFIED: test + assert_eq!(legacy.reserve(), None); + } +} diff --git a/core/continuum-core/src/test_env/mind_integration/registry/deliberation/prompt_shaping.rs b/core/continuum-core/src/test_env/mind_integration/registry/deliberation/prompt_shaping.rs index b3d37966e2..1dd046dffe 100644 --- a/core/continuum-core/src/test_env/mind_integration/registry/deliberation/prompt_shaping.rs +++ b/core/continuum-core/src/test_env/mind_integration/registry/deliberation/prompt_shaping.rs @@ -283,7 +283,7 @@ async fn pinned_act_result_reaches_the_prompt_even_with_an_empty_broadcast() { let estimate = LlmDeliberationFaculty::messages_cost(&roomy.messages); let snapshot = DeliberationPromptView { refit: roomy.refit, system: String::new(), input_identity: [0; 32], - estimated_prompt_tokens: estimate, completion_reserve: 0, + estimated_prompt_tokens: estimate, completion_reserve: 0, reply_bound: 0, capacity_error: None, budget_fault: None, protocol_error: None, segments: Vec::new(), messages: roomy.messages, }; diff --git a/core/continuum-core/src/test_env/mind_integration/registry/deliberation/verdicts.rs b/core/continuum-core/src/test_env/mind_integration/registry/deliberation/verdicts.rs index e0ae009304..260330b756 100644 --- a/core/continuum-core/src/test_env/mind_integration/registry/deliberation/verdicts.rs +++ b/core/continuum-core/src/test_env/mind_integration/registry/deliberation/verdicts.rs @@ -392,6 +392,7 @@ async fn standing_activity_grounding_survives_history_on_the_wire() { + reply_claim( faculty.turn_kind(&ws), faculty.working_set.as_ref().and_then(|reg| reg.need_of(persona)), + faculty.working_set.as_ref().and_then(|reg| reg.reply_reserve_of(persona)), 0, LlmDeliberationFaculty::holds_live_work(&ws), ws.directed_at_self(), diff --git a/docs/architecture/MIND-CONTEXT-AND-ENGINE-CONFIG.md b/docs/architecture/MIND-CONTEXT-AND-ENGINE-CONFIG.md index e94a599b25..8662726728 100644 --- a/docs/architecture/MIND-CONTEXT-AND-ENGINE-CONFIG.md +++ b/docs/architecture/MIND-CONTEXT-AND-ENGINE-CONFIG.md @@ -307,6 +307,59 @@ collapse the newest, admission instead of turnovers, a restart order measured pe slot/seed), Cormac (checkpoints at the head boundary and on turnover). The replay validator (`continuum-context` `examples/replay.rs`) and the live 15-minute read are the receipts for each slice. +### The reply reserve (2026-10-26) + +The reply is one claim in the window's allocation (`reply_claim.rs`). Two numbers used to be +one: the room the plan **reserves** for the reply, which sizes her view, and the request's +`max_tokens`, which bounds what she may write. An act forced both to the runaway bound, +`ACT_OUTPUT_CAP` = 12,288, after a reply was cut at its grant (Aris, 2026-10-22). On the M5 +that reserved 12,288 of a 58,880 window for replies that measured p50 268, p90 766, p99 +1,202, max 1,526 (1,063 completions over 24 h, reasoning tokens included: +`usage.outputTokens` equals the engine's decoded tokens on every row). + +The room left for her view and history, from 30 `delib.window.flex` rows at that window, is +58,880 − framing − required input − the reply's grant. Framing (13,463) already includes the +tool schemas. The median was 30.3k with the 12,288 reserve, and 40.8k with each mind's measured +max × 5/4 (about 1.8-1.9k) in its place: +10.5k, or +35%. + +Now they are separate: + +- **Reserve** (sizes the view): the max of her last 64 measured outputs × 5/4 + (`working_set/reply_tail.rs`, persisted with her emission record), or the reply-sized cold + prior before three turns. What no claim takes is her view's room to grow into, not the + reply's. +- **Request bound** (`DeliberationPromptView::reply_allowance`): the window's physical room + after the prompt, minus one token (local admission needs prompt + reply < window), never + below the reserve. The runaway bound stays only as a loop guard on the request. +- **A reply longer than the reserve** keeps writing into whatever room the window still has. + Mid-epoch that is the room her view has not grown into yet. The reply then joins the ring, so + the next reserve holds it. At an epoch's tail, where the view fills the window, the physical + room equals the reserve. A cut there is the existing loud path: the emission records the cut + answer at double, and the retry claims twice the pending peak. +- **An estimated prompt the engine counts larger** overflows only the room past the + reserve. The faculty re-quotes the reply's room from the measured count and sends the same + view whole (`delib.reply.room_requoted`). A refit after a real overflow makes room for the + reserve only, never for the physical allowance. + +**Error bound, checked:** replayed over the M5's landed outputs (each reserve read only from +that mind's earlier turns), 2.1% of replies exceed the reserve (the reply-tail test in +`reply_tail.rs` asserts this against `continuum-cognition/fixtures/reply-output-tokens-m5-2026-10-26.json`). +For comparison, max × 1.0 exceeded on 4.5% and max × 2 on 0.7%. + +**What a bigger view does to prefill, measured, not assumed:** the S1 append-tail replay +(`continuum-context --example replay --purpose "" --append-tail 173`) on the residents' +captures (window 76,032), with each mind's measured max × 5/4 in place of 12,288: + +| Mind | View, chars | Turnovers | Prefill, tokens | s/request | +|---|---|---|---|---| +| Benchy (223 req) | 205,590 -> 239,069 | 47 -> 42 | 2,002,175 -> 2,211,385 | 52 -> 57 | +| Aiko (51 req) | 200,180 -> 233,170 | 15 -> 10 | 632,749 -> 570,014 | 72 -> 65 | +| Atlas (99 req) | 205,131 -> 238,898 | 18 -> 15 | 754,369 -> 767,428 | 44 -> 45 | + +The view holds about 16% more, and turnovers fall by 16% in total. Total prefill rises 4.7% +(3.39M to 3.55M tokens): fewer turnovers, each larger. So the reserve buys retained context. +Speed comes from cheaper turnovers (collapse at a start), not from the bigger window alone. + ## Fault 2: engine configuration is decided in five places `lane_args`, `llama_server`, `backend_receipt`, `serving_plan` and `kv_cache_plan` each