inky-engine 3.0.2

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple M5 Macs
//! A mounted file cartridge stitches a cold read. `INK_FILE_REUSE=1` keeps the prompt
//! checkpoint in that conversation's twin (`approx_twin`: secret salt, auth namespace,
//! full card id). The identical repeat of the same card binds it. A different card, a
//! request with no card, and another auth namespace (another key) miss it and stitch.
use super::*;
use crate::ikv::{write_ikv_cartridge_raw, IkvCatalog, IkvHmacKey};
use crate::tokenizer::Tokenizer;
use std::sync::Arc;
use std::time::{Duration, Instant};

const SALT: &str = "test-salt";
/// Auth namespace of the key that mounted the cartridge.
const NS_KEY_A: u64 = 7;
/// Auth namespace of a different key. `derive_cache_namespace` mixes the credential in,
/// and `approx_twin` mixes that namespace into the twin, so this key's twin is not key A's.
const NS_KEY_B: u64 = 8;

fn card_owner(ns: u64, card: &str) -> u64 {
    approx_twin(SALT, ns, Some(card))
}

fn finish_to(
    cache: &mut ServeBlockCache,
    pools: &mut BlockPools,
    table: &mut BlockTable,
    state: &mut LaneBlockState,
    prompt: &[u32],
    end: usize,
) {
    while state.written < end {
        let start = state.written;
        let len = (end - start).min(BLOCK - start % BLOCK);
        cache.ensure_span_blocks(pools, table, start, len).unwrap();
        cache.finish_prefill_span(pools, table, state, prompt, start, len, || fake_cs(9));
    }
}

fn drive(
    cache: &mut ServeBlockCache,
    pools: &mut BlockPools,
    namespace: u64,
    owner: u64,
    prompt: &[u32],
) -> (usize, usize) {
    let cap = prompt.len().div_ceil(BLOCK) + 16;
    let mut table = BlockTable::new(u32::try_from(cap).unwrap()).unwrap();
    let mut state = LaneBlockState { namespace, owner, prompt_len: prompt.len(), ..Default::default() };
    let matched = match cache.begin_admit_bind(pools, 0, &mut table, &mut state, prompt) {
        AdmitBindOutcome::Immediate(x) => x.map_or(0, |(pos, _)| pos),
        AdmitBindOutcome::Restoring { .. } => panic!("no spill store configured"),
    };
    let plans = cache.plan_stitches(pools, namespace, prompt, matched);
    let mut from_cartridge = 0usize;
    for p in &plans {
        finish_to(cache, pools, &mut table, &mut state, prompt, p.stitch_start);
        let count = p.heal_start - p.stitch_start;
        match cache.start_stitch_plan(pools, 0, &mut table, &mut state, prompt, p) {
            StitchStartOutcome::Staging => {
                let began = Instant::now();
                loop {
                    let tbl_ptr: *mut BlockTable = &mut table;
                    let state_ptr: *mut LaneBlockState = &mut state;
                    let mut done =
                        cache.poll_ikv_stages(pools, |lane| (lane == 0).then_some((&(), tbl_ptr, state_ptr)));
                    if let Some(result) = done.pop() {
                        assert_eq!(result.stitched_tokens, Some(count));
                        from_cartridge += count;
                        break;
                    }
                    assert!(began.elapsed() < crate::serve::TEST_HANG_GUARD, "hang guard: cartridge staging did not finish");
                    cache.wait_restore_activity(Duration::from_millis(20));
                }
            }
            other => panic!("unexpected stitch outcome {other:?}"),
        }
    }
    finish_to(cache, pools, &mut table, &mut state, prompt, prompt.len());
    cache.release_lane(pools, &mut table, &mut state);
    (matched, from_cartridge)
}

fn missed_warm(matched: usize, ikv: usize, prompt_len: usize, what: &str) {
    assert!(ikv > 0, "{what} must stitch, matched={matched} ikv={ikv}");
    assert!(
        matched + BLOCK < prompt_len,
        "{what} must miss the warm checkpoint, matched={matched} prompt={prompt_len}"
    );
}

/// Cold full-file read stitches. With `INK_FILE_REUSE=1` the same card's identical repeat binds
/// the twin and does not stitch again. A different card, no card, and another key miss that
/// checkpoint and stitch. With the switch off, the same card stitches again.
#[test]
fn file_reuse_warm_repeat_takes_the_warm_path() {
    let tk = Tokenizer::for_byte_test();
    let lines: Vec<_> = (0..70)
        .map(|i| format!("pub fn field_{i:03}(value: u32) -> u32 {{ value.wrapping_add({}) }}\n", 2000 + i))
        .collect();
    let file = lines.concat();
    let file_tokens = tk.encode(&file, false);
    assert!(file_tokens.len() >= MIN_STITCH_TOKENS, "fixture {}", file_tokens.len());
    let dir = ScratchDir::new("file-reuse");
    let key = IkvHmacKey::from_bytes(&[0x55; 32]).unwrap();
    let kvb = crate::blocks::KVB_KV4;
    let stride = BlockKind::Full.stride_for_mode(crate::blocks::KvMode::Kv4) as usize;
    let n_pages = file_tokens.len().div_ceil(BLOCK);
    let pages: Vec<_> = (0..n_pages).map(|i| vec![i as u8; stride]).collect();
    let path = dir.0.join("fields.ikv");
    write_ikv_cartridge_raw(&path, "src/fields.rs", kvb, 1024, 42, false, 16, &file_tokens, &pages, Some(&key))
        .unwrap();
    drop(pages);
    let catalog = Arc::new(IkvCatalog::load_dir(&dir.0, kvb, 1024, 42, false, &key).unwrap());
    let prompt_text = format!("TOOL READ src/fields.rs\n{file}\nReview this source.");
    let prompt = tk.encode(&prompt_text, false);
    // Same length, so the file span stays put and the cartridge still matches, but the prefix does not.
    let other_header = prompt_text.replacen("TOOL READ", "TOOL REED", 1);
    assert_eq!(other_header.len(), prompt_text.len());
    let other_header = tk.encode(&other_header, false);
    let owner_a = card_owner(NS_KEY_A, "card-a");
    let owner_b = card_owner(NS_KEY_A, "card-b");
    let owner_other_key = card_owner(NS_KEY_B, "card-a");
    assert_ne!(owner_a, owner_b);
    assert_ne!(owner_a, owner_other_key);
    assert_ne!(owner_a, NS_KEY_A);

    let blocks = prompt.len().div_ceil(BLOCK) + 16;
    {
        let mut cache = ServeBlockCache::new();
        cache.set_kv_stitch(true);
        cache.set_file_reuse(false);
        cache.set_ikv_catalog_for_namespace(catalog.clone(), NS_KEY_A);
        let mut pools = BlockPools::with_capacities_mode(blocks * 3, blocks * 3, crate::blocks::KvMode::Kv4).unwrap();
        let (cold_matched, cold_ikv) = drive(&mut cache, &mut pools, NS_KEY_A, owner_a, &prompt);
        assert_eq!(cold_matched, 0, "flag off cold matched");
        assert!(cold_ikv > 0, "flag off cold should stitch the file");
        let (warm_matched, warm_ikv) = drive(&mut cache, &mut pools, NS_KEY_A, owner_a, &prompt);
        missed_warm(warm_matched, warm_ikv, prompt.len(), "without INK_FILE_REUSE the identical repeat");
        assert!(cache.starts.values().all(|s| !s.approx), "flag off saves no twin checkpoint");
        cache.shutdown(&mut pools);
        assert_zero_pool_leaks(&pools);
    }

    let mut cache = ServeBlockCache::new();
    cache.set_kv_stitch(true);
    cache.set_file_reuse(true);
    cache.set_ikv_catalog_for_namespace(catalog.clone(), NS_KEY_A);
    let mut pools = BlockPools::with_capacities_mode(blocks * 8, blocks * 8, crate::blocks::KvMode::Kv4).unwrap();
    let (cold_matched, cold_ikv) = drive(&mut cache, &mut pools, NS_KEY_A, owner_a, &prompt);
    assert_eq!(cold_matched, 0, "cold matched");
    assert!(cold_ikv > 0, "cold should stitch the file");
    let twin = owner_a;
    assert!(
        cache.starts.values().any(|s| s.approx && s.namespace == twin),
        "the warm checkpoint lives in the card's twin"
    );
    let exact_after_cold = cache.starts.values().filter(|s| !s.approx).count();
    let (warm_matched, warm_ikv) = drive(&mut cache, &mut pools, NS_KEY_A, owner_a, &prompt);
    assert!(
        warm_matched + BLOCK >= prompt.len() && warm_ikv == 0,
        "identical repeat must take the warm path, matched={warm_matched} ikv={warm_ikv} prompt={}",
        prompt.len()
    );
    assert_eq!(
        cache.starts.values().filter(|s| !s.approx).count(),
        exact_after_cold,
        "the warm bind adds no exact start"
    );
    assert_eq!(cache.stats().approx_start_matches, 1, "the warm bind is the approximate start");

    let (card_b_matched, card_b_ikv) = drive(&mut cache, &mut pools, NS_KEY_A, owner_b, &prompt);
    missed_warm(card_b_matched, card_b_ikv, prompt.len(), "a different card");
    let (no_card_matched, no_card_ikv) = drive(&mut cache, &mut pools, NS_KEY_A, 0, &prompt);
    missed_warm(no_card_matched, no_card_ikv, prompt.len(), "a request with no card id");
    let (header_matched, header_ikv) = drive(&mut cache, &mut pools, NS_KEY_A, owner_a, &other_header);
    missed_warm(header_matched, header_ikv, other_header.len(), "a different header on the same card");

    // Remount the same cartridge into the other key's namespace. The miss has to be the twin,
    // not "this key has no cartridge".
    cache.set_ikv_catalog_for_namespace(catalog, NS_KEY_B);
    let (key_b_matched, key_b_ikv) = drive(&mut cache, &mut pools, NS_KEY_B, owner_other_key, &prompt);
    missed_warm(key_b_matched, key_b_ikv, prompt.len(), "a different key");

    cache.shutdown(&mut pools);
    assert_zero_pool_leaks(&pools);
}