Set cache_retention per lane: Long for the play loop, Short for unattended tool loops, none for single-round prose

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-03 06:14:00 +01:00
commit ded2ede38e
3 changed files with 165 additions and 3 deletions

View file

@ -8536,6 +8536,89 @@ pub(crate) mod tests {
);
}
/// The table's loop is cached under the long lifetime, and what the
/// provider caches against is stable: the instructions and the tools, which
/// come first, are identical on every round of a turn and into the next
/// turn while the world's grants do not change, and each round's
/// conversation extends the previous round's byte for byte, so the one
/// breakpoint at its end is read by the next round, including the one that
/// resumes after the player answers a question.
#[tokio::test]
async fn the_play_loop_is_cached_with_a_prefix_that_is_stable_across_rounds_and_turns() {
use model_connector::CacheRetention;
let fixture = play_world(None, "player-cache-prefix").await;
let personas = PersonaLane::new(
ControllerPort::new(fixture.world.clone()),
ScriptedPort::new(vec![]),
"gpt-5.6-sol".into(),
"gpt-5.6-sol".into(),
)
.unwrap();
let directory = tempfile::tempdir().unwrap();
let port = ScriptedPort::new(vec![
output("r0", vec![call_event("c0", ADVANCE_TIME_TOOL, serde_json::json!({"minutes": 5}))]),
output("r1", vec![call_event("c1", ASK_PLAYER_TOOL, serde_json::json!({"question": "Which way?"}))]),
output("r2", vec![call_event("c2", END_TURN_TOOL, serde_json::json!({}))]),
output("r3", vec![call_event("c3", END_TURN_TOOL, serde_json::json!({}))]),
]);
let table = PlayTable::new(
fixture.world.clone(),
personas,
port.clone(),
"gpt-5.6-terra".into(),
Arc::new(Semaphore::new(2)),
directory.path().join("play-turn-v1.cc"),
)
.unwrap();
table
.run(&fixture.principal, test_turn_id(610), "I stand at a crossroads.".into())
.await
.unwrap();
let question_id = table.store.lock().await.current().unwrap().open_question_id().unwrap();
table
.run(
&fixture.principal,
test_turn_id(611),
PlayRequest {
text: "Left.".into(),
answers: Some(question_id),
},
)
.await
.unwrap();
table
.run(&fixture.principal, test_turn_id(612), "I walk on.".into())
.await
.unwrap();
let seen = port.seen_requests();
assert_eq!(seen.len(), 4, "three rounds of the first turn and one of the next");
let wires: Vec<(Vec<InputItem>, String, String, Option<CacheRetention>)> = seen
.iter()
.map(|request| {
let wire = request.provider_request();
(
wire.input.clone(),
wire.instructions.clone(),
serde_json::to_string(&wire.tools).unwrap(),
wire.cache_retention,
)
})
.collect();
for (_, instructions, tools, retention) in &wires {
assert_eq!(*retention, Some(CacheRetention::Long));
assert_eq!(instructions, &wires[0].1, "instructions are the same bytes every request");
assert_eq!(tools, &wires[0].2, "the tool set is the same bytes every request");
}
for pair in wires[..3].windows(2) {
assert!(
pair[1].0.starts_with(&pair[0].0) && pair[1].0.len() > pair[0].0.len(),
"a round's conversation extends the previous round's"
);
}
assert_ne!(wires[3].0[0], wires[0].0[0], "the next turn opens on its own view");
}
fn ask_round_repeat() -> InferenceOutput {
output(
"r2",

View file

@ -536,6 +536,7 @@ async fn character_action(
};
let instructions = if card.claims { format!("{CHARACTER_INSTRUCTIONS}{CLAIM_INSTRUCTIONS}") } else { CHARACTER_INSTRUCTIONS.to_owned() };
let request = InferenceRequest::play(CommandId::new(), 0, &plan.character_model, &instructions, vec![InputItem::UserText { text: prompt }], vec![act], 1_200)
.map(InferenceRequest::uncached)
.map_err(|error| anyhow::anyhow!("{error}"))?;
let output = infer(port, request).await?;
let mut spoken = String::new();
@ -951,7 +952,7 @@ async fn judge_claims(
"Report your verdict on every listed claim.",
r#"{"type":"object","properties":{"verdicts":{"type":"array","items":{"type":"object","properties":{"id":{"type":"integer"},"outcome":{"type":"string","enum":["accepted","partial","refused"]},"handling":{"type":"string","enum":["defensible_yes_and","godmode_pass","refused"]},"quote":{"type":"string"},"note":{"type":"string"}},"required":["id","outcome","handling","quote","note"],"additionalProperties":false}}},"required":["verdicts"],"additionalProperties":false}"#,
);
let request = InferenceRequest::play(CommandId::new(), 0, &plan.critic_model, CLAIM_JUDGE_INSTRUCTIONS, vec![InputItem::UserText { text: prompt }], vec![report], 6_000).map_err(|error| anyhow::anyhow!("{error}"))?;
let request = InferenceRequest::play(CommandId::new(), 0, &plan.critic_model, CLAIM_JUDGE_INSTRUCTIONS, vec![InputItem::UserText { text: prompt }], vec![report], 6_000).map(InferenceRequest::uncached).map_err(|error| anyhow::anyhow!("{error}"))?;
let output = infer(port, request).await?;
for event in output.events() {
if let InferenceEvent::ToolCall { name, arguments, .. } = event {

View file

@ -32,7 +32,7 @@ use crate::{
use async_trait::async_trait;
use chrono::Utc;
use model_connector::{
ConnectorClient, ConnectorClientError, FailureKind, InputItem, ProviderRequest, ReasoningEffort,
CacheRetention, ConnectorClient, ConnectorClientError, FailureKind, InputItem, ProviderRequest, ReasoningEffort,
Refusal,
ToolChoice, ToolDefinition, TransportDisposition, TransportEventPayload, TransportInvocation,
TransportResult,
@ -137,6 +137,47 @@ impl InferenceRequest {
pub(crate) fn provider_model(&self) -> &str {
&self.provider.model
}
/// The provider request this will send, read for inspection.
pub fn provider_request(&self) -> &ProviderRequest {
&self.provider
}
/// This request without a cache breakpoint. For a call that is its own
/// whole conversation: nothing will ever read what a breakpoint writes,
/// and a write costs more than plain input.
pub fn uncached(mut self) -> Self {
self.provider.cache_retention = None;
self
}
}
/// The one owner of how long a lane's prompt prefix is kept by the provider.
///
/// The connector places one breakpoint, on the last block of the last message,
/// and the provider caches everything before it: tools, then instructions,
/// then the conversation so far. A later request reads that entry only if its
/// own prefix is byte-identical up to the entry's end, and every lane's
/// conversation is an append-only rebuild of its recorded opening prompt and
/// completed rounds, so the next round of the same loop is what reads it.
///
/// - `Play`, the table's loop: a turn can wait on the player (`ask_player`)
/// for minutes between two rounds, past the short lifetime, so the entry is
/// kept for the long one.
/// - The tool loops that run unattended (`Interpreter`, `OperationalAgent`,
/// `GroupedAgent`, `Elaboration`, which carries seed sessions too): rounds
/// follow each other in seconds, so the short lifetime covers them at the
/// cheaper write price.
/// - `Projector` and `Persona` are single-round prose: nothing reads a write.
fn lane_cache_retention(purpose: InferencePurpose) -> Option<CacheRetention> {
match purpose {
InferencePurpose::Play => Some(CacheRetention::Long),
InferencePurpose::Interpreter
| InferencePurpose::OperationalAgent
| InferencePurpose::GroupedAgent
| InferencePurpose::Elaboration => Some(CacheRetention::Short),
InferencePurpose::Projector | InferencePurpose::Persona => None,
}
}
/// The exact connector invocation, including expiry and native provenance.
@ -7170,6 +7211,7 @@ pub(super) fn tool_request(
);
provider.input = input;
provider.reasoning_effort = Some(ReasoningEffort::Medium);
provider.cache_retention = lane_cache_retention(purpose);
provider.tools = tools;
provider.tool_choice = ToolChoice::Auto;
provider.parallel_tool_calls = shape.parallel_tool_calls;
@ -7866,13 +7908,49 @@ mod tests {
}
/// v4 requests carry a required output allowance and a typed effort, and
/// name no cache retention Ghostlight never chose.
/// choose each lane's cache retention in `lane_cache_retention`.
#[test]
fn every_lane_builds_a_bounded_typed_v4_request() {
let persona = persona_request(CommandId::new(), "claude-haiku-5-5", "Speak.".into()).unwrap();
assert_eq!(persona.provider.max_output_tokens, 1_200);
assert_eq!(persona.provider.reasoning_effort, Some(ReasoningEffort::Low));
assert_eq!(persona.provider.cache_retention, None::<CacheRetention>);
let tooled = |purpose| {
tool_request(
CommandId::new(),
0,
purpose,
"claude-haiku-5-5",
"Decide.",
vec![InputItem::UserText { text: "x".into() }],
Vec::new(),
DECISION_REQUEST_SHAPE,
)
.unwrap()
.provider
.cache_retention
};
assert_eq!(tooled(InferencePurpose::Play), Some(CacheRetention::Long));
for purpose in [
InferencePurpose::Interpreter,
InferencePurpose::OperationalAgent,
InferencePurpose::GroupedAgent,
InferencePurpose::Elaboration,
] {
assert_eq!(tooled(purpose), Some(CacheRetention::Short), "{purpose:?}");
}
let play = InferenceRequest::play(
CommandId::new(),
0,
"claude-haiku-5-5",
"Play.",
vec![InputItem::UserText { text: "x".into() }],
Vec::new(),
100,
)
.unwrap();
assert_eq!(play.provider.cache_retention, Some(CacheRetention::Long));
assert_eq!(play.uncached().provider.cache_retention, None);
let interpreter =
interpreter_request(CommandId::new(), 0, "claude-haiku-5-5", vec![InputItem::UserText { text: "x".into() }])
.unwrap();