axiom_engine 0.5.0

Axiom-TTT Inference Engine – Rust implementation using candle
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! Integration coverage for S3: digest admission control in the
//! `/v1/messages` compression path.

use axiom_engine::anthropic_forwarder::AnthropicForwarder;
use axiom_engine::config::AxiomConfig;
use axiom_engine::context_compressor::CompressorConfig;
use axiom_engine::inference::InferencePipeline;
use axiom_engine::server::{create_router, AppState};
use axum::body::{to_bytes, Body};
use axum::extract::State;
use axum::http::{Method, Request, StatusCode};
use axum::routing::post;
use axum::{Json, Router};
use candle_core::Device;
use serde_json::{json, Value};
use std::fs;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, OnceLock};
use tokio::sync::Mutex as AsyncMutex;
use tower::ServiceExt;

/// `AXIOM_CVM_DIGEST`/`AXIOM_CVM_DIGEST_THRESHOLD_TOKENS` are process-global
/// env vars read inside the proxy's request path -- same rationale as
/// `cache_safety_proxy.rs`'s `env_lock`.
fn env_lock() -> &'static AsyncMutex<()> {
    static LOCK: OnceLock<AsyncMutex<()>> = OnceLock::new();
    LOCK.get_or_init(|| AsyncMutex::new(()))
}

struct EnvVarGuard(&'static [&'static str]);
impl Drop for EnvVarGuard {
    fn drop(&mut self) {
        for var in self.0 {
            std::env::remove_var(var);
        }
    }
}

#[derive(Clone, Default)]
struct Capture {
    requests: Arc<Mutex<Vec<Value>>>,
}

fn tiny_pipeline() -> InferencePipeline {
    let config = AxiomConfig {
        d_model: 16,
        n_layers: 1,
        vocab_size: 64,
        lr_inner: 1e-3,
        norm_eps: 1e-6,
    };
    InferencePipeline::new(config, Device::Cpu).expect("pipeline init")
}

async fn start_capturing_upstream() -> (String, Capture, tokio::task::JoinHandle<()>) {
    async fn handler(State(capture): State<Capture>, Json(body): Json<Value>) -> Json<Value> {
        capture.requests.lock().unwrap().push(body);
        Json(json!({
            "id": "msg_test",
            "type": "message",
            "role": "assistant",
            "model": "claude-sonnet-5",
            "content": [{"type": "text", "text": "ok"}],
            "stop_reason": "end_turn",
            "usage": {"input_tokens": 10, "output_tokens": 5}
        }))
    }
    let capture = Capture::default();
    let app = Router::new()
        .route("/v1/messages", post(handler))
        .with_state(capture.clone());
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = listener.local_addr().unwrap();
    let task = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
    (format!("http://{address}"), capture, task)
}

fn cvm_tempdir(tag: &str) -> PathBuf {
    let path = std::env::temp_dir().join(format!(
        "axiom-digest-proxy-test-{tag}-{}",
        std::process::id()
    ));
    fs::create_dir_all(&path).unwrap();
    path
}

async fn build_state(upstream: String, cvm_dir: &PathBuf) -> AppState {
    let pipeline = tokio::task::spawn_blocking(tiny_pipeline).await.unwrap();
    let cvm_store = axiom_engine::cvm_store::CvmStore::open(cvm_dir).expect("cvm store open");
    AppState::new(pipeline, "axiom-ttt-test".to_string())
        .with_anthropic_forwarder(Some(AnthropicForwarder::new(None, Some(upstream))))
        .with_compressor_config(CompressorConfig {
            heavy_message_threshold_tokens: 5,
            recall_top_k: 8,
            enabled: true,
        })
        .with_cvm_store(cvm_store)
}

async fn post_json(app: &Router, uri: &str, body: Value) -> (StatusCode, Value) {
    let req = Request::builder()
        .method(Method::POST)
        .uri(uri)
        .header("content-type", "application/json")
        .header("x-api-key", "sk-ant-test-key")
        .body(Body::from(body.to_string()))
        .unwrap();
    let resp = app.clone().oneshot(req).await.unwrap();
    let status = resp.status();
    let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
    let json: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
    (status, json)
}

/// A synthetic, well-over-4000-token `tool_result` body -- realistic
/// "heavy file read" content, code-shaped so `SkeletonDigestor` has
/// signatures to keep.
fn heavy_tool_result_text() -> String {
    (0..1200)
        .map(|i| format!("pub fn generated_function_{i}(x: i32) -> i32 {{ x + {i} }}\n"))
        .collect::<Vec<_>>()
        .join("")
}

fn tool_result_message(text: &str) -> Value {
    json!({
        "role": "user",
        "content": [
            {"type": "tool_result", "tool_use_id": "toolu_1", "content": text},
        ],
    })
}

#[tokio::test]
async fn digest_replaces_heavy_tool_result_with_stub_and_original_is_expandable() {
    let _guard = env_lock().lock().await;
    std::env::set_var("AXIOM_CVM_DIGEST", "skeleton");
    let _cleanup = EnvVarGuard(&["AXIOM_CVM_DIGEST", "AXIOM_CVM_DIGEST_THRESHOLD_TOKENS"]);

    let cvm_dir = cvm_tempdir("basic");
    let (upstream, capture, _task) = start_capturing_upstream().await;
    let state = build_state(upstream, &cvm_dir).await;
    let app = create_router(state);

    let heavy = heavy_tool_result_text();
    let session_id = "digest-basic";
    let body = json!({
        "model": "claude-sonnet-5",
        "max_tokens": 16,
        "session_id": session_id,
        // P0 safety gate: digesting requires axiom_expand in tools[].
        "tools": [{"name": "axiom_expand"}],
        "messages": [
            {"role": "user", "content": "please read this file"},
            tool_result_message(&heavy),
        ],
    });
    let status = post_json(&app, "/v1/messages", body).await.0;
    assert_eq!(status, StatusCode::OK);

    let sent = {
        let captured = capture.requests.lock().unwrap();
        assert_eq!(captured.len(), 1);
        captured[0].clone()
    };
    let sent_str = sent.to_string();
    assert!(
        !sent_str.contains("generated_function_1199"),
        "the original heavy text must not reach upstream verbatim"
    );
    assert!(sent_str.contains("AXIOM-PAGE"), "a stub line must be present");
    assert!(
        sent_str.contains("AXIOM-PAGE-END"),
        "the expand trailer must be present"
    );

    // Extract the page id from the stub and confirm it's expandable back
    // to the exact original text.
    let stub_start = sent_str.find("AXIOM-PAGE ").unwrap() + "AXIOM-PAGE ".len();
    let page_id = &sent_str[stub_start..stub_start + 16];
    let (expand_status, expand_body) = post_json(
        &app,
        "/v1/expand",
        json!({"session_id": session_id, "symbol": page_id}),
    )
    .await;
    assert_eq!(expand_status, StatusCode::OK);
    assert_eq!(expand_body["body"], json!(heavy));

    let _ = fs::remove_dir_all(&cvm_dir);
}

#[tokio::test]
async fn digest_flag_off_passes_bytes_through_unchanged() {
    let _guard = env_lock().lock().await;
    // AXIOM_CVM_DIGEST now defaults to "skeleton" (S5 passed 2026-07-11);
    // "off" is an explicit opt-out, no longer the implicit unset state.
    std::env::set_var("AXIOM_CVM_DIGEST", "off");
    let _cleanup = EnvVarGuard(&["AXIOM_CVM_DIGEST"]);

    let cvm_dir = cvm_tempdir("flag-off");
    let (upstream, capture, _task) = start_capturing_upstream().await;
    let state = build_state(upstream, &cvm_dir).await;
    let app = create_router(state);

    let heavy = heavy_tool_result_text();
    let body = json!({
        "model": "claude-sonnet-5",
        "max_tokens": 16,
        "session_id": "digest-flag-off",
        "messages": [
            {"role": "user", "content": "please read this file"},
            tool_result_message(&heavy),
        ],
    });
    let status = post_json(&app, "/v1/messages", body).await.0;
    assert_eq!(status, StatusCode::OK);

    let captured = capture.requests.lock().unwrap();
    let sent_str = captured[0].to_string();
    assert!(
        sent_str.contains("generated_function_1199"),
        "flags off -> the original heavy tool_result must pass through unchanged"
    );
    assert!(!sent_str.contains("AXIOM-PAGE"));

    let _ = fs::remove_dir_all(&cvm_dir);
}

#[tokio::test]
async fn digest_default_unset_env_var_digests_since_skeleton_is_now_the_default() {
    let _guard = env_lock().lock().await;
    // No explicit AXIOM_CVM_DIGEST set -- must fall back to the new
    // "skeleton" default (S5 passed 2026-07-11), not "off".
    std::env::remove_var("AXIOM_CVM_DIGEST");
    let _cleanup = EnvVarGuard(&["AXIOM_CVM_DIGEST"]);

    let cvm_dir = cvm_tempdir("default-unset");
    let (upstream, capture, _task) = start_capturing_upstream().await;
    let state = build_state(upstream, &cvm_dir).await;
    let app = create_router(state);

    let heavy = heavy_tool_result_text();
    let body = json!({
        "model": "claude-sonnet-5",
        "max_tokens": 16,
        "session_id": "digest-default-unset",
        // P0 safety gate: digesting requires axiom_expand in tools[].
        "tools": [{"name": "axiom_expand"}],
        "messages": [
            {"role": "user", "content": "please read this file"},
            tool_result_message(&heavy),
        ],
    });
    let status = post_json(&app, "/v1/messages", body).await.0;
    assert_eq!(status, StatusCode::OK);

    let captured = capture.requests.lock().unwrap();
    let sent_str = captured[0].to_string();
    assert!(
        !sent_str.contains("generated_function_1199"),
        "default (unset AXIOM_CVM_DIGEST) must digest, not pass the original through"
    );
    assert!(sent_str.contains("AXIOM-PAGE"));

    let _ = fs::remove_dir_all(&cvm_dir);
}

#[tokio::test]
async fn digest_only_touches_the_newest_turn_when_cache_control_present() {
    let _guard = env_lock().lock().await;
    std::env::set_var("AXIOM_CVM_DIGEST", "skeleton");
    let _cleanup = EnvVarGuard(&["AXIOM_CVM_DIGEST", "AXIOM_CVM_DIGEST_THRESHOLD_TOKENS"]);

    let cvm_dir = cvm_tempdir("newest-turn");
    let (upstream, capture, _task) = start_capturing_upstream().await;
    let state = build_state(upstream, &cvm_dir).await;
    let app = create_router(state);

    let heavy_old = heavy_tool_result_text();
    let heavy_new = heavy_tool_result_text().replace("generated_function", "newer_function");

    // Old heavy tool_result sits BEFORE a cache_control breakpoint (frozen
    // prefix); the new one is the newest turn, after the breakpoint.
    let body = json!({
        "model": "claude-sonnet-5",
        "max_tokens": 16,
        "session_id": "digest-newest-turn",
        // P0 safety gate: digesting requires axiom_expand in tools[].
        "tools": [{"name": "axiom_expand"}],
        "messages": [
            {"role": "user", "content": "first turn"},
            tool_result_message(&heavy_old),
            {"role": "assistant", "content": [
                {"type": "text", "text": "ack",
                 "cache_control": {"type": "ephemeral"}}
            ]},
            tool_result_message(&heavy_new),
        ],
    });
    let status = post_json(&app, "/v1/messages", body).await.0;
    assert_eq!(status, StatusCode::OK);

    let captured = capture.requests.lock().unwrap();
    let sent_str = captured[0].to_string();
    assert!(
        sent_str.contains("generated_function_1199"),
        "frozen-prefix tool_result (before cache_control) must survive verbatim, undigested"
    );
    assert!(
        !sent_str.contains("newer_function_1199"),
        "newest-turn tool_result (after cache_control) must have been digested"
    );

    let _ = fs::remove_dir_all(&cvm_dir);
}

#[tokio::test]
async fn digest_skipped_when_expand_tool_absent() {
    // P0 safety gate: if axiom_expand is not in the request's tools[], the
    // digest would point at a nonexistent tool. Fail closed: pass through.
    let _guard = env_lock().lock().await;
    std::env::set_var("AXIOM_CVM_DIGEST", "skeleton");
    let _cleanup = EnvVarGuard(&["AXIOM_CVM_DIGEST", "AXIOM_CVM_DIGEST_THRESHOLD_TOKENS"]);

    let cvm_dir = cvm_tempdir("no-expand-tool");
    let (upstream, capture, _task) = start_capturing_upstream().await;
    let state = build_state(upstream, &cvm_dir).await;
    let app = create_router(state);

    let heavy = heavy_tool_result_text();
    let body = json!({
        "model": "claude-sonnet-5",
        "max_tokens": 16,
        "session_id": "digest-no-expand",
        // NOTE: no axiom_expand here -- only unrelated tools.
        "tools": [{"name": "Read"}, {"name": "Bash"}],
        "messages": [
            {"role": "user", "content": "please read this file"},
            tool_result_message(&heavy),
        ],
    });
    let status = post_json(&app, "/v1/messages", body).await.0;
    assert_eq!(status, StatusCode::OK);

    let captured = capture.requests.lock().unwrap();
    let sent_str = captured[0].to_string();
    assert!(
        sent_str.contains("generated_function_1199"),
        "without axiom_expand in tools[], heavy text must pass through undigested"
    );
    assert!(
        !sent_str.contains("AXIOM-PAGE"),
        "no digest stub must be emitted when expansion is unavailable"
    );

    let _ = fs::remove_dir_all(&cvm_dir);
}

#[tokio::test]
async fn digest_skipped_when_tools_array_missing() {
    // P0 safety gate: missing tools[] also fails closed.
    let _guard = env_lock().lock().await;
    std::env::set_var("AXIOM_CVM_DIGEST", "skeleton");
    let _cleanup = EnvVarGuard(&["AXIOM_CVM_DIGEST", "AXIOM_CVM_DIGEST_THRESHOLD_TOKENS"]);

    let cvm_dir = cvm_tempdir("no-tools-array");
    let (upstream, capture, _task) = start_capturing_upstream().await;
    let state = build_state(upstream, &cvm_dir).await;
    let app = create_router(state);

    let heavy = heavy_tool_result_text();
    let body = json!({
        "model": "claude-sonnet-5",
        "max_tokens": 16,
        "session_id": "digest-no-tools",
        "messages": [
            {"role": "user", "content": "please read this file"},
            tool_result_message(&heavy),
        ],
    });
    let status = post_json(&app, "/v1/messages", body).await.0;
    assert_eq!(status, StatusCode::OK);

    let captured = capture.requests.lock().unwrap();
    let sent_str = captured[0].to_string();
    assert!(
        sent_str.contains("generated_function_1199"),
        "without tools[] the heavy text must pass through undigested"
    );

    let _ = fs::remove_dir_all(&cvm_dir);
}

#[tokio::test]
async fn expand_unknown_page_id_returns_actionable_error() {
    // A well-formed page id that is not in this session's store must fail
    // with an error naming the session_id/page_id cause, not a bare 404.
    let _guard = env_lock().lock().await;

    let cvm_dir = cvm_tempdir("expand-404");
    let (upstream, _capture, _task) = start_capturing_upstream().await;
    let state = build_state(upstream, &cvm_dir).await;
    let app = create_router(state);

    let (status, body) = post_json(
        &app,
        "/v1/expand",
        json!({"session_id": "wrong-session", "symbol": "a1b2c3d4e5f60718"}),
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    assert_eq!(body["found"], json!(false));
    let err = body["error"].as_str().unwrap();
    assert!(
        err.contains("a1b2c3d4e5f60718"),
        "error must name the page id, got: {err}"
    );
    assert!(
        err.contains("wrong-session"),
        "error must name the session id, got: {err}"
    );
    assert!(
        err.contains("session_id"),
        "error must point at the session_id fix, got: {err}"
    );

    let _ = fs::remove_dir_all(&cvm_dir);
}