Skip to main content

deepstrike_core/context/
measurement.rs

1//! spc_011-C-02: prompt token measurement — the three-way split the spec's §6.1 invariant
2//! ("measure provider-visible input, never underestimate") requires between what a request is
3//! *estimated* to cost before it is sent (`PromptMeasurement`, this module), what the provider
4//! actually reports back (`ProviderUsage`, Node/Python Host layer — not this crate). This module
5//! only defines a preflight fact. The `MeasurePrompt` wire tag is reserved, but A-00R removed its
6//! scheduler producer until request fingerprinting and durable replay semantics are defined.
7
8use serde::{Deserialize, Serialize};
9
10/// Where a token count came from — never just a bare `u32`, so a caller can tell "the provider's
11/// own count API said so" apart from "we guessed." The provenance remains part of the reserved
12/// contract, but no runtime currently persists or consumes this fact.
13#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
14#[serde(tag = "kind", rename_all = "snake_case")]
15pub enum MeasurementSource {
16    /// The provider's own token-counting endpoint answered (e.g. Anthropic
17    /// `messages/count_tokens`, OpenAI Responses token counting, Gemini `countTokens`).
18    Native { provider: String },
19    /// A real BPE tokenizer ran locally, but against a vocabulary that may not be the target
20    /// provider's own (e.g. cl100k standing in for a non-OpenAI vendor) — see
21    /// `FallbackEstimator` (spc_011-C-01) for the concrete counter this describes.
22    LocalExact { tokenizer: String },
23    /// The provider's own postflight usage for this exact request, fed back after execution
24    /// (spc_024-06). The authority a replay reuses — never a preflight guess.
25    Postflight,
26    /// No tokenizer ran at all; this is a coarse guess with a generous safety margin.
27    Heuristic,
28    /// A host supplied measurement tied to a canonical object fingerprint.
29    HostProvided,
30}
31
32/// Host-side token evidence for one canonical runtime object. This is deliberately separate from
33/// `CoreMessage`: a measurement may be refreshed or invalidated without changing semantics.
34#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
35#[serde(deny_unknown_fields)]
36pub struct TokenMeasurement {
37    pub fingerprint: String,
38    pub tokens: u32,
39    pub source: MeasurementSource,
40    pub confidence: MeasurementConfidence,
41}
42
43impl TokenMeasurement {
44    pub fn for_message(message: &crate::types::message::CoreMessage, tokens: u32) -> Self {
45        use sha2::{Digest as _, Sha256};
46        let digest = Sha256::digest(serde_json::to_vec(message).expect("message is serializable"));
47        let hex = digest
48            .iter()
49            .map(|b| format!("{b:02x}"))
50            .collect::<String>();
51        Self {
52            fingerprint: format!("sha256:{hex}"),
53            tokens,
54            source: MeasurementSource::HostProvided,
55            confidence: MeasurementConfidence::HighConfidence,
56        }
57    }
58}
59
60/// Host-owned accounting fact for one completed tool call. It is an input to settlement and
61/// context accounting, never a field on the runtime `ToolResult` message.
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(deny_unknown_fields)]
64pub struct ToolMeasurement {
65    pub call_id: String,
66    pub tokens: u32,
67}
68
69impl ToolMeasurement {
70    pub fn new(call_id: impl Into<String>, tokens: u32) -> Self {
71        Self {
72            call_id: call_id.into(),
73            tokens,
74        }
75    }
76}
77
78/// How much to trust `PromptMeasurement.input_tokens` when deciding whether to compress. Kept
79/// separate from `MeasurementSource` — the *reason* a number exists and how much a caller should
80/// *lean on it* are different questions (a `LocalExact` cl100k count for an Anthropic request is
81/// still nontrivially uncertain, but it is not a bare guess either).
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
83#[serde(rename_all = "snake_case")]
84pub enum MeasurementConfidence {
85    Exact,
86    HighConfidence,
87    LowConfidence,
88}
89
90/// A single preflight token-count fact about a candidate render, for a specific provider/model.
91#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
92#[serde(deny_unknown_fields)]
93pub struct PromptMeasurement {
94    pub input_tokens: u32,
95    pub source: MeasurementSource,
96    pub confidence: MeasurementConfidence,
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102
103    #[test]
104    fn constructs_all_three_measurement_source_variants() {
105        let native = MeasurementSource::Native {
106            provider: "anthropic".to_string(),
107        };
108        let local_exact = MeasurementSource::LocalExact {
109            tokenizer: "cl100k_base".to_string(),
110        };
111        let heuristic = MeasurementSource::Heuristic;
112
113        assert_ne!(native, local_exact);
114        assert_ne!(local_exact, heuristic);
115    }
116
117    #[test]
118    fn prompt_measurement_round_trips_through_json() {
119        let m = PromptMeasurement {
120            input_tokens: 1234,
121            source: MeasurementSource::Native {
122                provider: "openai".to_string(),
123            },
124            confidence: MeasurementConfidence::Exact,
125        };
126        let json = serde_json::to_string(&m).unwrap();
127        let back: PromptMeasurement = serde_json::from_str(&json).unwrap();
128        assert_eq!(m, back);
129    }
130
131    #[test]
132    fn postflight_source_round_trips_and_differs_from_preflight_kinds() {
133        // spc_024-06: observed usage fed back after execution — the authority a replay reuses.
134        let m = PromptMeasurement {
135            input_tokens: 1000,
136            source: MeasurementSource::Postflight,
137            confidence: MeasurementConfidence::Exact,
138        };
139        let json = serde_json::to_string(&m).unwrap();
140        let back: PromptMeasurement = serde_json::from_str(&json).unwrap();
141        assert_eq!(m, back);
142        assert_eq!(
143            serde_json::to_string(&m.source).unwrap(),
144            r#"{"kind":"postflight"}"#
145        );
146    }
147
148    #[test]
149    fn unknown_field_is_rejected() {
150        let raw = r#"{"input_tokens": 10, "source": {"kind": "heuristic"}, "confidence": "exact", "extra": true}"#;
151        let result: Result<PromptMeasurement, _> = serde_json::from_str(raw);
152        assert!(
153            result.is_err(),
154            "deny_unknown_fields must reject stray keys"
155        );
156    }
157
158    #[test]
159    fn tool_measurement_is_independent_from_tool_result_state() {
160        let measurement = ToolMeasurement::new("call-1", 42);
161        let json = serde_json::to_string(&measurement).unwrap();
162        let decoded: ToolMeasurement = serde_json::from_str(&json).unwrap();
163        assert_eq!(decoded, measurement);
164    }
165}