Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

requirements.authoring.cache_checkpoints

Requirements index · View definition

evidence Valid

Requirement

For backends that accept explicit cache checkpoints, when the backend and model support prompt caching, every provider request MUST place one cache checkpoint after the system prompt of cite requirements.authoring.prompt_parts and another at the end of its last message, so each request reuses the tool definitions and system prompt that earlier assessments of its kind sent, and the conversation its own earlier requests sent. Cache checkpoints MUST NOT change the content of a request.

For OpenAI, which caches matching prompt prefixes automatically, the harness MUST keep the system prompt and tool definitions unchanged across requests in one conversation and replay prior conversation content in its original order. It MUST NOT insert checkpoint blocks.

Rationale

The tests cover each obligation in requirements.authoring.cache_checkpoints.

Backends with explicit checkpoints (Bedrock)

  • tests/authoring_cli.rs#fn[claude_requests_carry_cache_checkpoints_and_record_cache_usage] runs a two-request Bedrock Claude conversation. It covers a tool-call round and a reasoning turn.
  • For every request it asserts the system array has exactly two entries: the system text, then a cachePoint.
  • For every request it asserts the last message’s final block is a cachePoint. It also asserts the whole body contains exactly two cachePoint occurrences, so there are no extra checkpoints.
  • It asserts the second request, which follows a reasoning turn, still ends in a checkpoint.
  • Checkpoints must not change content. The test runs the same conversation against a non-caching model (fixture-uncached-model), which gets no cachePoint. It then asserts that each cached request, after without_cache_points strips the checkpoint blocks, equals the corresponding plain request.
  • “When the backend and model support caching” is covered in two places. The CLI test checks the non-caching model end to end. The unit test src/authoring/providers.rs#mod[tests]/fn[cache_checkpoints_are_requested_for_caching_models] checks bedrock_caches for Claude, an inference-profile ARN, Nova, Llama (negative) and an unknown model (negative).
  • The same unit test checks that place_cache_checkpoints sets only the cache option, by comparing the serialized request with an expected one. It also checks that checkpoints are requested after a reasoning turn.
  • Ollama has no explicit checkpoints, so it falls outside the “backends that accept explicit checkpoints” clause.

OpenAI

  • tests/authoring_cli.rs#fn[openai_responses_replays_tool_calls_and_records_usage] asserts the instructions (system prompt) are non-empty and identical across both requests. It asserts the tools arrays are identical across the requests.
  • It asserts the second request’s input begins with exactly the first request’s input, then the function_call and function_call_output in order. That covers replay of prior content in its original order.
  • The recursive assert_no_checkpoints checks every request body for cachePoint, cache_control, and cache_point or cache_checkpoint type blocks. That covers “MUST NOT insert checkpoint blocks”.

Not assessed here

  • The system prompt being identical across assessments of a kind is the job of requirements.authoring.prompt_parts. The CLI test also carries a {test} reference to that requirement.

I found no obligation, boundary or failure case without a test and an assertion.

Inputs

Implementation

Input 8: outline src/authoring/providers.rs impl[RigProvider]/fn[connect]
    // {impl}`requirements.authoring.usage_requests`
    // {impl}`requirements.authoring.credentials`
    // {impl}`requirements.authoring.cache_checkpoints`
    // {impl}`requirements.configuration.serialization`
    pub(super) async fn connect(config: &BackendConfig) -> io::Result<Self> {
        let model = match config {
            BackendConfig::Bedrock(config) => {
                let sdk = aws_sdk_bedrockruntime::Client::new(&bedrock_sdk_config(config).await);
                rig_bedrock::client::BedrockRuntime::from(sdk)
                    .completion(&config.model)
                    .erase()
            }
            BackendConfig::Openai(config) => {
                let key = config.api_key()?;
                rig_core::providers::openai::OpenAIConfig::new(key)
                    .with_base_url(config.endpoint())
                    .client()
                    .responses(config.model())
                    .erase()
            }
            BackendConfig::Ollama(config) => {
                // Rig's reqwest transport sends each request once; it has no
                // hidden retry layer to disable.
                let mut provider = rig_core::providers::ollama::OllamaConfig::new()
                    .with_base_url(config.endpoint());
                if let Some(key) = config.api_key()? {
                    provider = provider.with_api_key(key);
                }
                provider.client().native_completion(&config.model).erase()
            }
        };
        Ok(Self {
            model,
            options: config.options_json()?,
            bedrock: matches!(config, BackendConfig::Bedrock(_)),
            openai: matches!(config, BackendConfig::Openai(_)),
            caches: match config {
                BackendConfig::Bedrock(config) => bedrock_caches(&config.model),
                // Ollama has no checkpoints; OpenAI manages prompt caching.
                BackendConfig::Ollama(_) | BackendConfig::Openai(_) => false,
            },
        })
    }
Input 9: outline src/authoring/providers.rs impl[RigProvider/CompletionProvider]/fn[complete]
    // {impl}`requirements.authoring.configuration_storage`
    // {impl}`requirements.authoring.cache_checkpoints`
    async fn complete(&self, mut request: CompletionRequest) -> io::Result<CompletionResponse> {
        let mut options = self
            .options
            .as_object()
            .expect("configuration options are a map")
            .clone();
        if self.bedrock {
            apply_bedrock_options(&mut request, &mut options)?;
        }
        if self.caches {
            place_cache_checkpoints(&mut request);
        }
        request.additional_params = (!options.is_empty()).then_some(Value::Object(options));
        let mut response = self.model.call(request).await.map_err(provider_failure)?;
        if self.bedrock {
            normalize_bedrock_client_calls(&mut response)?;
        }
        Ok(response)
    }

Tests

Input 3: outline src/authoring/providers.rs mod[tests]/fn[cache_checkpoints_are_requested_for_caching_models]
    // {test}`requirements.authoring.cache_checkpoints`
    #[test]
    fn cache_checkpoints_are_requested_for_caching_models() {
        assert!(bedrock_caches(
            "us.anthropic.claude-sonnet-4-5-20250929-v1:0"
        ));
        assert!(bedrock_caches(
            "arn:aws:bedrock:us-east-1:123:inference-profile/us.anthropic.claude-opus-4-1-20250805-v1:0"
        ));
        assert!(bedrock_caches("us.amazon.nova-pro-v1:0"));
        assert!(!bedrock_caches("meta.llama3-70b-instruct-v1:0"));
        assert!(!bedrock_caches("fixture-bedrock-model"));

        let mut request = CompletionRequest::new("subject").preamble("system");
        place_cache_checkpoints(&mut request);
        assert_eq!(request.options.cache, Some(CacheRetention::Short));
        // Only the cache option changes.
        let mut expected = CompletionRequest::new("subject").preamble("system");
        expected.options.cache = Some(CacheRetention::Short);
        assert_eq!(
            serde_json::to_value(&request).unwrap(),
            serde_json::to_value(&expected).unwrap()
        );

        // Checkpoints are requested after a reasoning turn too.
        let mut request = CompletionRequest::new("subject").preamble("system");
        request.chat_history.push(Message::Assistant(
            rig_core::message::AssistantMessage::new(vec![AssistantContent::Reasoning(
                Reasoning::new("Think."),
            )]),
        ));
        place_cache_checkpoints(&mut request);
        assert_eq!(request.options.cache, Some(CacheRetention::Short));
    }
Input 4: outline tests/authoring_cli.rs fn[claude_requests_carry_cache_checkpoints_and_record_cache_usage]
// {test}`requirements.authoring.cache_checkpoints`
// {test}`requirements.authoring.usage_requests`
// {test}`requirements.authoring.prompt_parts`
#[test]
fn claude_requests_carry_cache_checkpoints_and_record_cache_usage() {
    let checkpoint = json!({"cachePoint":{"type":"default"}});
    let (cached, usage) = bedrock_run("us.anthropic.claude-sonnet-4-5-20250929-v1:0");
    assert_eq!(cached.len(), 2);
    for body in &cached {
        // One checkpoint follows the system prompt...
        let system = body["system"].as_array().unwrap();
        assert_eq!(system.len(), 2, "{body}");
        assert!(system[0]["text"].as_str().unwrap().starts_with("# Task"));
        assert_eq!(system[1], checkpoint);
        // ...and one ends the last message, and there are no others.
        let messages = body["messages"].as_array().unwrap();
        let last = messages.last().unwrap()["content"].as_array().unwrap();
        assert_eq!(last.last().unwrap(), &checkpoint, "{body}");
        assert_eq!(body.to_string().matches("cachePoint").count(), 2, "{body}");
    }
    assert_eq!(cached[1]["messages"].as_array().unwrap().len(), 3);
    // The second request follows a reasoning turn and still ends in a
    // checkpoint.
    assert!(
        cached[1]["messages"][1]
            .to_string()
            .contains("reasoningContent")
    );
    // The checkpoints change nothing else: a model without caching gets the
    // same request without them.
    let (plain, _) = bedrock_run("fixture-uncached-model");
    assert!(!plain[0].to_string().contains("cachePoint"));
    for (cached, plain) in cached.iter().zip(&plain) {
        assert_eq!(&without_cache_points(cached), plain);
    }
    // Cache reads and writes are recorded per request and in total.
    let requests = usage["requests"].as_array().unwrap();
    assert_eq!(requests[0]["tokens"]["cached_input"], 0);
    assert_eq!(requests[0]["tokens"]["cache_creation_input"], 1000);
    assert_eq!(requests[1]["tokens"]["cached_input"], 1000);
    assert_eq!(requests[1]["tokens"]["cache_creation_input"], 200);
    assert_eq!(usage["tokens"]["cached_input"], 1000);
    assert_eq!(usage["tokens"]["cache_creation_input"], 1200);
}
Input 5: outline tests/authoring_cli.rs fn[openai_responses_replays_tool_calls_and_records_usage]
// {test}`requirements.authoring.provider`
// {test}`requirements.authoring.rig_configuration_mapping`
// {test}`requirements.authoring.usage_requests`
// {test}`requirements.authoring.configuration_storage`
// {test}`requirements.authoring.usage_storage`
// {test}`requirements.authoring.configuration_precedence`
// {test}`requirements.authoring.cache_checkpoints`
#[test]
// {test}`requirements.authoring.usage_storage`
fn openai_responses_replays_tool_calls_and_records_usage() {
    fn assert_no_checkpoints(value: &Value) {
        match value {
            Value::Object(fields) => {
                for (key, value) in fields {
                    assert!(
                        !matches!(key.as_str(), "cachePoint" | "cache_control"),
                        "explicit cache checkpoint: {key}"
                    );
                    if key == "type" {
                        assert!(
                            !matches!(value.as_str(), Some("cache_point" | "cache_checkpoint")),
                            "explicit cache checkpoint block: {value}"
                        );
                    }
                    assert_no_checkpoints(value);
                }
            }
            Value::Array(values) => {
                for value in values {
                    assert_no_checkpoints(value);
                }
            }
            _ => {}
        }
    }

    let response = |id: &str, name: &str, arguments: Value| {
        json!({
            "id": format!("resp_{id}"), "object":"response", "status":"completed",
            "model":"fixture-openai", "output":[{
                "type":"function_call", "id":format!("fc_{id}"), "call_id":id,
                "name":name, "arguments":arguments.to_string(), "status":"completed"
            }],
            "usage":{"input_tokens":11,"output_tokens":7,"total_tokens":18,
                "input_tokens_details":{"cached_tokens":3},
                "output_tokens_details":{"reasoning_tokens":2}}
        })
    };
    let server = Server::start(vec![
        response(
            "read",
            "habeas",
            json!({"file":"extra.txt","line_start":10}),
        ),
        response(
            "submit",
            "submit_judgment",
            json!({"determination":false,"rationale":"Missing implementation."}),
        ),
    ]);
    let fixture = Fixture::new(&server.endpoint);
    fs::write(fixture.config.join("habeas/config.toml"), format!(
        "version = 1\n[authoring]\ndefault = 'mock'\n[authoring.configs.mock]\nbackend = 'openai'\nmodel = 'fixture-openai'\npolicy = 'once'\nendpoint = '{}'\napi_key_env = 'HABEAS_TEST_MODEL_KEY'\n[authoring.configs.mock.options]\nmax_output_tokens = 1024\nreasoning = {{ effort = 'low' }}\n", server.endpoint)).unwrap();
    let output = fixture.run(&["author-evidence", SUBJECT]);
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let requests = server.finish();
    assert_eq!(requests.len(), 2);
    for request in &requests {
        assert!(request.headers.starts_with("POST /responses HTTP/1.1\r\n"));
        assert!(request.headers.contains(&format!("Bearer {AUTH}")));
        assert_eq!(request.body["model"], "fixture-openai");
        assert_eq!(request.body["max_output_tokens"], 1024);
        assert_eq!(request.body["reasoning"]["effort"], "low");
        assert_eq!(request.body["tools"].as_array().unwrap().len(), 10);
        assert_no_checkpoints(&request.body);
    }
    assert!(
        !requests[0].body["instructions"]
            .as_str()
            .unwrap()
            .is_empty()
    );
    assert_eq!(
        requests[0].body["instructions"],
        requests[1].body["instructions"]
    );
    assert_eq!(requests[0].body["tools"], requests[1].body["tools"]);
    let initial_input = requests[0].body["input"].as_array().unwrap();
    let history = requests[1].body["input"].as_array().unwrap();
    assert_eq!(history.len(), initial_input.len() + 2);
    assert_eq!(&history[..initial_input.len()], initial_input.as_slice());
    assert_eq!(history[initial_input.len()]["type"], "function_call");
    assert_eq!(history[initial_input.len()]["call_id"], "read");
    assert_eq!(
        history[initial_input.len() + 1]["type"],
        "function_call_output"
    );
    assert_eq!(history[initial_input.len() + 1]["call_id"], "read");
    let usage = fixture.usage();
    assert_eq!(usage["backend"], "openai");
    assert_eq!(usage["outcome"], "completed");
    assert_eq!(usage["request_count"], 2);
    assert_eq!(usage["tokens"]["input"], 22);
    assert_eq!(usage["tokens"]["output"], 14);
    assert_eq!(usage["tokens"]["cached_input"], 6);
    assert_eq!(usage["tokens"]["reasoning"], 4);
    assert!(!usage.to_string().contains(AUTH));
}

Referenced definitions

Input 2: requirements selection requirements.authoring.prompt_parts
:::{req} prompt_parts
Each assessment conversation MUST send its prompt as a system prompt followed by
one user message, the subject message, filled from the first and second text
blocks of the prompt requirement for the assessment's kind. The kinds are
requirement, example, citation review, site review, and a verifier of each of
those. A system prompt MUST be the same for every assessment of its kind, so
every placeholder whose value depends on the subject MUST be in the subject
message.
:::

Other sources

Input 1: requirements selection requirements.authoring.cache_checkpoints
:::{req} cache_checkpoints
For backends that accept explicit cache checkpoints, when the backend and model
support prompt caching, every provider request MUST place one cache checkpoint
after the system prompt of {cite}`requirements.authoring.prompt_parts` and
another at the end of its last message, so each request reuses the tool
definitions and system prompt that earlier assessments of its kind sent, and
the conversation its own earlier requests sent. Cache checkpoints MUST NOT
change the content of a request.

For OpenAI, which caches matching prompt prefixes automatically, the harness
MUST keep the system prompt and tool definitions unchanged across requests in
one conversation and replay prior conversation content in its original order.
It MUST NOT insert checkpoint blocks.
:::
Input 6: outline tests/authoring_cli.rs fn[bedrock_run]
/// Runs one Bedrock assessment that reads a file and then submits, against
/// model `model`, returning the two request bodies and the usage record.
// {cite}`habeas:util`
fn bedrock_run(model: &str) -> (Vec<Value>, Value) {
    let (output, bodies, usage) = bedrock_exchange(
        model,
        vec![
            json!({
                "output":{"message":{"role":"assistant","content":[
                    {"reasoningContent":{"reasoningText":{"text":"Read the extra source.","signature":"sig"}}},
                    {"toolUse":
                    {"toolUseId":"read","name":"habeas","input":{"file":"extra.txt","line_start":1}}}]}},
                "stopReason":"tool_use",
                "usage":{"inputTokens":7,"outputTokens":5,"totalTokens":1012,
                    "cacheReadInputTokens":0,"cacheWriteInputTokens":1000},
                "metrics":{"latencyMs":1}
            }),
            json!({
                "output":{"message":{"role":"assistant","content":[{"toolUse":
                    {"toolUseId":"submit","name":"submit_judgment","input":
                        {"determination":true,"rationale":"The supplied sources support the subject."}}}]}},
                "stopReason":"tool_use",
                "usage":{"inputTokens":9,"outputTokens":5,"totalTokens":1214,
                    "cacheReadInputTokens":1000,"cacheWriteInputTokens":200},
                "metrics":{"latencyMs":1}
            }),
        ],
    );
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    (bodies, usage)
}
Input 7: outline tests/authoring_cli.rs fn[without_cache_points]
/// Removes every `cachePoint` block from a Converse request body.
// {cite}`habeas:util`
fn without_cache_points(body: &Value) -> Value {
    let mut body = body.clone();
    let strip = |blocks: &mut Value| {
        if let Some(blocks) = blocks.as_array_mut() {
            blocks.retain(|block| block.get("cachePoint").is_none());
        }
    };
    strip(&mut body["system"]);
    for message in body["messages"].as_array_mut().unwrap() {
        strip(&mut message["content"]);
    }
    body
}