Skip to main content

submilli_engine/stdlib/embedding/
mod.rs

1//! `submilli:embedding` — remote text embeddings from inside a Submilli program.
2//!
3//! Rust host functions registered directly under the package name. Each op runs
4//! `check_security_call` before anything leaves the process; the one gated
5//! capability is `embedding.embed`, cataloged in [`crate::stdlib::capabilities`]
6//! — keep it in sync when adding or removing a gate (see AGENTS.md).
7//!
8//! Dispatch is the embedder's: [`StoreData::embedding_provider`] holds the
9//! provider, and a runtime with none refuses every op rather than inventing a
10//! vector — the rule `submilli:llm` follows.
11//!
12//! **One capability, per-alias filtering.** `embed` and `models()` share the
13//! grant, with `input_count` in the filter context. `models()` filters each
14//! candidate through the same `model` filter that gates `embed`, so a listing
15//! never offers an alias the caller would be denied at call time.
16//!
17//! **No input text or vector crosses this boundary in metadata.** Not in the
18//! filter context, not in an error, not in a log. The context carries `model`
19//! and `input_count`.
20//!
21//! **Vectors stay compact, in the GC heap.** A result is a backing struct whose
22//! hidden field holds the vectors as a packed `i8` array: little-endian `f32`
23//! bytes, row-major, `count × dimensions × 4` bytes — the storage a `Uint8Array`
24//! uses. The array is allocated through the GC limiter, which collects inside
25//! host calls, so a discarded result is reclaimed before the heap grows: the
26//! vectors live in the GC heap, never in host memory the collector cannot see.
27//! The field has no getter and its type is unreachable from the guest, so only
28//! `vector(i)` and `bytes(i)` read it, copying one row out on demand; a
29//! plain `number[][]` would cost about 60 bytes per number.
30
31pub mod declaration;
32
33use crate::runtime::effects::{self, NativeError};
34use std::sync::Arc;
35
36use wasmtime::{FuncType, HeapType, Linker, RefType, StructType, Val, ValType};
37
38use crate::runtime::ModelCallUsage;
39use crate::runtime::StoreData;
40use crate::runtime::call_log::{ModelUsage, Payload, Side, record_payload, record_usage};
41use crate::runtime::decision::CallTicket;
42use crate::runtime::embedding::{
43    EmbeddingBatch, EmbeddingBoundKind, EmbeddingError, EmbeddingLimits, EmbeddingMalformedReason,
44    EmbeddingModel, EmbeddingProvider, EmbeddingTokenBudget, Purpose, SubBatchSettlement,
45};
46use crate::runtime::fuel;
47use crate::runtime::host::{
48    abi_arg, abi_result, fatal_host_error, quota_exceeded_error, range_error, read_string_arg,
49    register_host_fn, register_host_value_async, type_error, write_boxed_number_struct,
50    write_submilli_array_struct_precharged, write_submilli_string_struct,
51    write_submilli_uint8array_struct, write_uint8_array_precharged,
52};
53use crate::runtime::intrinsic_types::build_intrinsic_types;
54use crate::stdlib::abi::{
55    self, HostView, backing_struct, f64_field, install_field_getters, nullable_object_field,
56    raw_bytes_field, string_field,
57};
58use crate::stdlib::shared::{
59    audit_quota_denial, check_security_call, filters_candidate, mark_filtered, optional_number,
60    preflight_models, sanitize_description,
61};
62
63pub use crate::runtime::EMBEDDING_MODULE_NAME as MODULE_NAME;
64pub use declaration::package_declaration;
65
66/// The single capability gating every op in this package.
67pub const CAPABILITY: &str = "embedding.embed";
68
69// `$EmbeddingsBacking` field indices (0 is the vtable).
70const E_VECTORS: usize = 1;
71const E_COUNT: usize = 2;
72const E_DIMENSIONS: usize = 3;
73const E_IDENTITY: usize = 4;
74const E_MODEL: usize = 5;
75const E_INPUT_TOKENS: usize = 6;
76
77// `$EmbeddingModelBacking` field indices (0 is the vtable).
78const M_NAME: usize = 1;
79const M_DESCRIPTION: usize = 2;
80const M_DIMENSIONS: usize = 3;
81const M_MAX_INPUT_TOKENS: usize = 4;
82const M_MAX_INPUT_BYTES: usize = 5;
83const M_IDENTITY: usize = 6;
84
85#[derive(serde::Serialize)]
86struct EmbedRequest {
87    model: String,
88    texts: Vec<String>,
89    purpose: Purpose,
90}
91
92pub fn install(linker: &mut Linker<StoreData>) -> wasmtime::Result<()> {
93    let engine = linker.engine().clone();
94    let intr = build_intrinsic_types(&engine)?;
95    let string = ValType::Ref(RefType::new(
96        false,
97        HeapType::ConcreteStruct(intr.string.clone()),
98    ));
99    let array = ValType::Ref(RefType::new(
100        false,
101        HeapType::ConcreteStruct(intr.array.clone()),
102    ));
103    let uint8 = ValType::Ref(RefType::new(
104        false,
105        HeapType::ConcreteStruct(intr.uint8_array.clone()),
106    ));
107    // `Embeddings` crosses the boundary as the universal `(ref null $Object)`
108    // lowering; a `Direct` receiver is the non-null `(ref $Object)`.
109    let nullable_object = ValType::Ref(RefType::new(
110        true,
111        HeapType::ConcreteStruct(intr.object.clone()),
112    ));
113    let receiver = ValType::Ref(RefType::new(
114        false,
115        HeapType::ConcreteStruct(intr.object.clone()),
116    ));
117
118    register_host_value_async(
119        linker,
120        MODULE_NAME,
121        crate::mangle::package_symbol(MODULE_NAME, "embed"),
122        FuncType::new(
123            &engine,
124            [string.clone(), array.clone(), string.clone()],
125            [nullable_object.clone()],
126        ),
127        |caller, params| {
128            Box::pin(async move {
129                let model =
130                    read_string_arg(&mut *caller, abi_arg(params, 0)?, "embedding.embed (model)")?;
131                let purpose = read_string_arg(
132                    &mut *caller,
133                    abi_arg(params, 2)?,
134                    "embedding.embed (purpose)",
135                )?;
136                embed(caller, &model, abi_arg(params, 1)?, &purpose).await
137            })
138        },
139    )?;
140
141    register_host_value_async(
142        linker,
143        MODULE_NAME,
144        crate::mangle::package_symbol(MODULE_NAME, "models"),
145        FuncType::new(&engine, [], [array.clone()]),
146        |caller, _params| Box::pin(async move { models(caller).await }),
147    )?;
148
149    for view in HOST_VIEWS {
150        install_field_getters(linker, &engine, &receiver, view)?;
151    }
152    install_methods(linker, &engine, receiver, array, uint8)
153}
154
155const EMBEDDINGS_VIEW: HostView = HostView {
156    module: MODULE_NAME,
157    interface: "Embeddings",
158    backing: embeddings_backing_struct,
159    properties: &[
160        ("count", E_COUNT),
161        ("dimensions", E_DIMENSIONS),
162        ("identity", E_IDENTITY),
163        ("model", E_MODEL),
164        ("inputTokens", E_INPUT_TOKENS),
165    ],
166};
167
168const EMBEDDING_MODEL_VIEW: HostView = HostView {
169    module: MODULE_NAME,
170    interface: "EmbeddingModel",
171    backing: model_backing_struct,
172    properties: &[
173        ("name", M_NAME),
174        ("description", M_DESCRIPTION),
175        ("dimensions", M_DIMENSIONS),
176        ("maxInputTokens", M_MAX_INPUT_TOKENS),
177        ("maxInputBytes", M_MAX_INPUT_BYTES),
178        ("identity", M_IDENTITY),
179    ],
180};
181
182/// The host-backed interfaces this package's values are.
183pub(crate) const HOST_VIEWS: &[&HostView] = &[&EMBEDDINGS_VIEW, &EMBEDDING_MODEL_VIEW];
184
185fn install_methods(
186    linker: &mut Linker<StoreData>,
187    engine: &wasmtime::Engine,
188    receiver: ValType,
189    array: ValType,
190    uint8: ValType,
191) -> wasmtime::Result<()> {
192    let embeddings_key = crate::mangle::package_symbol(MODULE_NAME, "Embeddings");
193
194    register_host_fn(
195        linker,
196        MODULE_NAME,
197        crate::mangle::extend(&embeddings_key, "vector"),
198        FuncType::new(engine, [receiver.clone(), ValType::F64], [array]),
199        |caller, params, results| {
200            let row = read_row(
201                caller,
202                abi_arg(params, 0)?,
203                abi_arg(params, 1)?,
204                "embedding.vector",
205            )?;
206            *abi_result(results, 0)? = build_number_array(caller, &row)?;
207            Ok(())
208        },
209    )?;
210
211    register_host_fn(
212        linker,
213        MODULE_NAME,
214        crate::mangle::extend(&embeddings_key, "bytes"),
215        FuncType::new(engine, [receiver, ValType::F64], [uint8]),
216        |caller, params, results| {
217            let row = read_row(
218                caller,
219                abi_arg(params, 0)?,
220                abi_arg(params, 1)?,
221                "embedding.bytes",
222            )?;
223            *abi_result(results, 0)? = Val::AnyRef(Some(
224                write_submilli_uint8array_struct(caller, &row)?.to_anyref(),
225            ));
226            Ok(())
227        },
228    )
229}
230
231/// One `embed`: gate, bound, resolve, reserve, dispatch, settle.
232///
233/// The ordering is the contract and is load-bearing at every step.
234///
235/// 1. **Gate before anything leaves.** A denial must cost nothing and reveal
236///    nothing, so the capability check runs ahead of the provider — which is
237///    what knows whether an alias exists.
238/// 2. **Per-call caps, then alias, then per-input limit.** Each refusal happens
239///    before the budget is touched, so a refused call charges nothing and the
240///    provider is never called.
241/// 3. **Reserve before dispatching.** The whole estimate is reserved up front.
242/// 4. **Settle exactly once** on success and on failure, from the settlements the
243///    provider recorded; a call that never sent releases its whole reservation.
244async fn embed(
245    caller: &mut wasmtime::Caller<'_, StoreData>,
246    model: &str,
247    texts: &Val,
248    purpose: &str,
249) -> wasmtime::Result<Val> {
250    let elements = crate::runtime::prelude::collection::read_array_vals(caller, texts)?;
251    let ticket = gate(caller, model, elements.len())?;
252
253    let budget = execution_budget(caller);
254    let limits = budget.limits();
255    let texts = read_texts(caller, model, &elements, &limits)?;
256    // The texts are first in hand once the per-call bounds pass, so the request is
257    // recorded here: a call refused for size has no copy to keep.
258    record_payload(&*caller, ticket, Side::Request, || {
259        let body = serde_json::to_vec(&texts).unwrap_or_default();
260        let bytes: usize = texts.iter().map(String::len).sum();
261        Payload::meta(serde_json::json!({
262            "op": "embed",
263            "model": model,
264            "purpose": purpose,
265            "count": texts.len(),
266        }))
267        .with_owned_body(body)
268        .with_size(bytes as u64)
269    });
270    let purpose = parse_purpose(model, purpose)?;
271
272    let request = EmbedRequest {
273        model: model.to_owned(),
274        texts,
275        purpose,
276    };
277    let mut response = effects::execute(
278        caller,
279        "embedding.embed",
280        request,
281        move |caller, _, request| Box::pin(call_provider(caller, ticket, request)),
282    )
283    .await?;
284    // Charge even a partially failed batch before exposing its result or error.
285    if let Some(settlement) = &mut response.settlement {
286        settlement.charge();
287    } else {
288        budget.restore_spend(response.used, response.held, response.requests);
289    }
290    let batch = response.result.map_err(NativeError::into_error)?;
291    build_embeddings(caller, batch)
292}
293
294#[derive(serde::Serialize, serde::Deserialize)]
295struct EmbeddingResponse {
296    result: Result<EmbeddingBatch, NativeError>,
297    used: u64,
298    held: u64,
299    requests: u64,
300    #[serde(skip)]
301    settlement: Option<EmbeddingSettlement>,
302}
303
304/// Retain live reservation cleanup if storing the outcome fails. Replay has no
305/// live reservation and restores only the recorded per-run counters.
306struct EmbeddingSettlement {
307    budget: Option<Arc<EmbeddingTokenBudget>>,
308    reserved: u64,
309    settlements: Vec<SubBatchSettlement>,
310}
311
312impl EmbeddingSettlement {
313    fn charge(&mut self) {
314        if let Some(budget) = self.budget.take() {
315            budget.settle(self.reserved, &self.settlements);
316        }
317    }
318}
319
320impl Drop for EmbeddingSettlement {
321    fn drop(&mut self) {
322        self.charge();
323    }
324}
325
326async fn call_provider(
327    caller: &mut wasmtime::Caller<'_, StoreData>,
328    ticket: Option<CallTicket>,
329    request: EmbedRequest,
330) -> wasmtime::Result<EmbeddingResponse> {
331    let model = request.model.as_str();
332    let texts = request.texts;
333    let purpose = request.purpose;
334    let budget = execution_budget(caller);
335    let provider = provider(caller, model)?;
336    check_inputs(caller, &*provider, model, &texts).await?;
337
338    let sent: usize = texts.iter().map(String::len).sum();
339    fuel::charge(&mut *caller, fuel::IO, sent as u64)?;
340
341    let estimate = provider.estimate_tokens(model, &texts);
342    budget
343        .reserve(model, estimate)
344        .map_err(|error| quota_throw(caller, ticket, model, error))?;
345    let requests_before = budget.requests();
346    let dispatched = provider.embed(model, &texts, purpose, &budget).await;
347    let requests = budget.requests().saturating_sub(requests_before);
348    let settlements = match &dispatched {
349        Ok(batch) => batch.settlements(),
350        Err(error) => error.settlements(),
351    };
352    let (used, held) = settlements.iter().fold((0u64, 0u64), |(used, held), part| {
353        (
354            used.saturating_add(part.reported)
355                .saturating_add(part.indeterminate),
356            held.saturating_add(part.indeterminate),
357        )
358    });
359    let settlement = EmbeddingSettlement {
360        budget: Some(budget),
361        reserved: estimate,
362        settlements: settlements.to_vec(),
363    };
364    let result = match dispatched {
365        // The provider returned a batch, so the dispatch ran. A short or long
366        // row count is a guest error, not an absent call: the budget still
367        // settles the batch's tokens.
368        Ok(batch) if batch.count() != texts.len() => {
369            note_embedding_usage(caller, ticket, model, batch.input_tokens());
370            Err(throw(EmbeddingError::Malformed {
371                alias: model.to_string(),
372                reason: EmbeddingMalformedReason::CountMismatch,
373                settlements: Vec::new(),
374            }))
375        }
376        Ok(batch) => {
377            let received = (batch.values().len() as u64).saturating_mul(4);
378            record_payload(&*caller, ticket, Side::Response, || {
379                Payload::meta(serde_json::json!({
380                    "count": batch.count(),
381                    "dimensions": batch.dimensions(),
382                    "identity": batch.identity(),
383                    "model": model,
384                    "inputTokens": batch.input_tokens(),
385                }))
386                .with_size(received)
387            });
388            note_embedding_usage(caller, ticket, model, batch.input_tokens());
389            fuel::settle(&mut *caller, fuel::IO, received)?;
390            Ok(batch)
391        }
392        Err(error) => {
393            // Some sub-batches may have completed before the provider failed.
394            let reported = error
395                .settlements()
396                .iter()
397                .fold(0u64, |sum, part| sum.saturating_add(part.reported));
398            if reported > 0 {
399                note_embedding_usage(caller, ticket, model, Some(reported));
400            }
401            Err(quota_throw(caller, ticket, model, error))
402        }
403    };
404    let result = match result {
405        Err(error) if crate::runtime::host::ends_the_run(&error) => return Err(error),
406        result => result.map_err(|error| NativeError::capture(&error)),
407    };
408    Ok(EmbeddingResponse {
409        result,
410        used,
411        held,
412        requests,
413        settlement: Some(settlement),
414    })
415}
416
417/// Record the usage the call log keeps, and the same counts for the embedder.
418///
419/// Only `call_provider` may call this. Replay restores the recorded outcome
420/// without entering that action.
421fn note_embedding_usage(
422    caller: &mut wasmtime::Caller<'_, StoreData>,
423    ticket: Option<CallTicket>,
424    model: &str,
425    input_tokens: Option<u64>,
426) {
427    record_usage(
428        &*caller,
429        ticket,
430        ModelUsage {
431            input_tokens,
432            output_tokens: None,
433        },
434    );
435    caller
436        .data_mut()
437        .note_model_call(ModelCallUsage::embedding(model, input_tokens));
438}
439
440/// The capability check, run before any bytes leave the process. The context is
441/// exactly `model` and `input_count`; input text is never in it.
442fn gate(
443    caller: &mut wasmtime::Caller<'_, StoreData>,
444    model: &str,
445    input_count: usize,
446) -> wasmtime::Result<Option<CallTicket>> {
447    check_security_call(
448        caller,
449        CAPABILITY,
450        serde_json::json!({ "model": model, "input_count": input_count }),
451    )
452}
453
454/// Bound the call by count and total bytes, then read the texts. The count is
455/// checked on the element list, before any string is copied out of the guest.
456fn read_texts(
457    caller: &mut wasmtime::Caller<'_, StoreData>,
458    model: &str,
459    elements: &[Val],
460    limits: &EmbeddingLimits,
461) -> wasmtime::Result<Vec<String>> {
462    let count = elements.len() as u64;
463    if count > limits.max_texts_per_call {
464        return Err(throw(EmbeddingError::BoundsExceeded {
465            alias: model.to_string(),
466            kind: EmbeddingBoundKind::TextCount,
467            actual: count,
468            limit: limits.max_texts_per_call,
469        }));
470    }
471    if elements.is_empty() {
472        return Err(range_error(format!(
473            "embedding.embed(\"{model}\"): at least one text is required — pass a non-empty array"
474        )));
475    }
476    let mut texts = Vec::with_capacity(elements.len());
477    let mut total = 0u64;
478    for element in elements {
479        let text = read_string_arg(caller, element, "embedding.embed (texts)")?;
480        total = total.saturating_add(text.len() as u64);
481        if total > limits.max_bytes_per_call {
482            return Err(throw(EmbeddingError::BoundsExceeded {
483                alias: model.to_string(),
484                kind: EmbeddingBoundKind::TotalBytes,
485                actual: total,
486                limit: limits.max_bytes_per_call,
487            }));
488        }
489        texts.push(text);
490    }
491    Ok(texts)
492}
493
494fn parse_purpose(model: &str, purpose: &str) -> wasmtime::Result<Purpose> {
495    match purpose {
496        "query" => Ok(Purpose::Query),
497        "document" => Ok(Purpose::Document),
498        _ => Err(range_error(format!(
499            "embedding.embed(\"{model}\"): purpose must be \"query\" or \"document\""
500        ))),
501    }
502}
503
504/// Resolve the alias and refuse any input over its byte limit, before the budget
505/// is touched. Numbering is from 0, like the vectors.
506async fn check_inputs(
507    caller: &mut wasmtime::Caller<'_, StoreData>,
508    provider: &dyn EmbeddingProvider,
509    model: &str,
510    texts: &[String],
511) -> wasmtime::Result<()> {
512    let Some(limit) = provider.max_input_bytes(model) else {
513        let available = available_aliases(caller, provider).await?;
514        return Err(throw(EmbeddingError::UnknownModel {
515            alias: model.to_string(),
516            available,
517        }));
518    };
519    // The provider repeats this check. Doing it here too keeps the refusal ahead
520    // of the budget reservation (see the ordering in [`embed`]) and does not
521    // depend on every provider implementing it.
522    let too_long = texts.iter().position(|text| text.len() as u64 > limit);
523    if let Some(index) = too_long {
524        return Err(throw(EmbeddingError::InputTooLong {
525            alias: model.to_string(),
526            index: Some(index),
527            limit: Some(limit),
528            settlements: Vec::new(),
529        }));
530    }
531    Ok(())
532}
533
534/// The aliases this caller may use, for an unknown-alias error. Filtered through
535/// the capability like `models()`, so the error cannot enumerate aliases the
536/// policy hides.
537async fn available_aliases(
538    caller: &mut wasmtime::Caller<'_, StoreData>,
539    provider: &dyn EmbeddingProvider,
540) -> wasmtime::Result<Vec<String>> {
541    let candidates = provider.models().await.map_err(throw)?;
542    let mut names = Vec::new();
543    for candidate in candidates {
544        if may_embed(caller, &candidate.name)? {
545            names.push(candidate.name);
546        }
547    }
548    Ok(names)
549}
550
551/// `models()`: check runtime invariants, then gate each candidate with the same
552/// `model` filter that gates `embed`.
553///
554/// Filtering acts **only** on a policy denial. An invariant denial means the
555/// check itself could not be made, and swallowing it would turn a runtime
556/// refusal into a silently short listing.
557async fn models(caller: &mut wasmtime::Caller<'_, StoreData>) -> wasmtime::Result<Val> {
558    preflight_models(caller, CAPABILITY, "input_count")?;
559    let candidates = effects::execute(caller, "embedding.models", (), |caller, _, ()| {
560        Box::pin(async move { provider(caller, "")?.models().await.map_err(throw) })
561    })
562    .await?;
563    let mut built = Vec::with_capacity(candidates.len());
564    for candidate in candidates {
565        if may_embed(caller, &candidate.name)? {
566            built.push(build_model(caller, candidate)?);
567        }
568    }
569    abi::new_array(caller, &built)
570}
571
572/// The per-candidate gate. A denial omits the alias rather than failing the
573/// call: a listing that threw on the first forbidden alias would itself disclose
574/// that the operator configured it.
575fn may_embed(caller: &mut wasmtime::Caller<'_, StoreData>, model: &str) -> wasmtime::Result<bool> {
576    let keeps = filters_candidate(gate(caller, model, 0).map(|_| ()))?;
577    if !keeps {
578        mark_filtered(&*caller);
579    }
580    Ok(keeps)
581}
582
583/// Clone the provider out of the store before any `await`. Runs *after* the
584/// capability check, deliberately: see [`embed`].
585fn provider(
586    caller: &wasmtime::Caller<'_, StoreData>,
587    model: &str,
588) -> wasmtime::Result<Arc<dyn EmbeddingProvider>> {
589    caller.data().embedding_provider.clone().ok_or_else(|| {
590        throw(EmbeddingError::NotConfigured {
591            alias: model.to_string(),
592        })
593    })
594}
595
596/// The execution's budget, or an unmetered one in the pure-interpreter path. The
597/// per-call caps in its limits still apply there.
598fn execution_budget(caller: &mut wasmtime::Caller<'_, StoreData>) -> Arc<EmbeddingTokenBudget> {
599    caller
600        .data_mut()
601        .embedding_budget
602        .get_or_insert_with(|| Arc::new(EmbeddingTokenBudget::unmetered()))
603        .clone()
604}
605
606/// [`throw`] plus an audit record when the failure is a budget refusal.
607fn quota_throw(
608    caller: &wasmtime::Caller<'_, StoreData>,
609    ticket: Option<CallTicket>,
610    model: &str,
611    error: EmbeddingError,
612) -> wasmtime::Error {
613    if !error.is_budget_exceeded() {
614        return throw(error);
615    }
616    if let Err(denial) = audit_quota_denial(
617        caller,
618        ticket,
619        CAPABILITY,
620        model,
621        "embedding-token budget exceeded",
622    ) {
623        return denial;
624    }
625    throw(error)
626}
627
628/// Every failure but an internal one reaches the guest as a catchable error.
629/// The `Display` impls exclude input text and vectors, so the message passes
630/// through whole. An [`EmbeddingError::Internal`] is a host invariant failure
631/// and ends the run, like every other internal host failure.
632///
633/// Budget refusals are quota errors, count/byte/length bounds are argument range
634/// errors, a malformed provider response is a type error, and the rest keep the
635/// base error type.
636fn throw(error: EmbeddingError) -> wasmtime::Error {
637    let message = error.to_string();
638    match error {
639        EmbeddingError::BudgetExceeded { .. } => quota_exceeded_error(message),
640        EmbeddingError::BoundsExceeded { .. } | EmbeddingError::InputTooLong { .. } => {
641            range_error(message)
642        }
643        EmbeddingError::Malformed { .. } => type_error(message),
644        EmbeddingError::Internal { .. } => fatal_host_error(message),
645        EmbeddingError::NotConfigured { .. }
646        | EmbeddingError::UnknownModel { .. }
647        | EmbeddingError::Unauthorized { .. }
648        | EmbeddingError::Provider { .. } => wasmtime::Error::msg(message),
649    }
650}
651
652fn embeddings_backing_struct(engine: &wasmtime::Engine) -> wasmtime::Result<StructType> {
653    let intr = build_intrinsic_types(engine)?;
654    backing_struct(
655        engine,
656        &intr,
657        vec![
658            raw_bytes_field(&intr),       // vectors (hidden: no getter)
659            f64_field(),                  // count
660            f64_field(),                  // dimensions
661            string_field(&intr),          // identity
662            string_field(&intr),          // model
663            nullable_object_field(&intr), // inputTokens
664        ],
665    )
666}
667
668fn model_backing_struct(engine: &wasmtime::Engine) -> wasmtime::Result<StructType> {
669    let intr = build_intrinsic_types(engine)?;
670    backing_struct(
671        engine,
672        &intr,
673        vec![
674            string_field(&intr),          // name
675            nullable_object_field(&intr), // description
676            f64_field(),                  // dimensions
677            nullable_object_field(&intr), // maxInputTokens
678            f64_field(),                  // maxInputBytes
679            string_field(&intr),          // identity
680        ],
681    )
682}
683
684/// Seal `batch`: copy its vectors into a packed byte array in the GC heap and
685/// hand the guest a backing struct that holds it in a hidden field.
686///
687/// Charge `count × dimensions × 4` bytes once, before encoding. A recorded
688/// native batch can be replayed if this conversion runs out of fuel.
689/// At most two host copies of the vectors are live at once (the encoded bytes
690/// and the engine's internal copy); the batch's own floats are gone before the
691/// array is allocated.
692fn build_embeddings(
693    caller: &mut wasmtime::Caller<'_, StoreData>,
694    batch: EmbeddingBatch,
695) -> wasmtime::Result<Val> {
696    let byte_count = batch
697        .values()
698        .len()
699        .checked_mul(4)
700        .ok_or_else(|| fatal_host_error("embedding.embed: result size overflows"))?;
701    fuel::charge(&mut *caller, fuel::COPY, byte_count as u64)?;
702    let mut bytes = Vec::new();
703    bytes
704        .try_reserve_exact(byte_count)
705        .map_err(|error| fatal_host_error(format!("embedding.embed: {error}")))?;
706    for value in batch.values() {
707        bytes.extend_from_slice(&value.to_le_bytes());
708    }
709    let count = batch.count() as f64;
710    let dimensions = batch.dimensions() as f64;
711    let identity = batch.identity().to_string();
712    let model = batch.model().to_string();
713    let input_tokens = batch.input_tokens().map(|n| n as f64);
714    drop(batch);
715
716    // Allocated through the GC limiter, which collects before the heap grows.
717    let array_ty = build_intrinsic_types(caller.engine())?.raw_uint8_array;
718    let vectors = write_uint8_array_precharged(&mut *caller, array_ty, &bytes)?;
719    drop(bytes);
720
721    let identity = string_val(caller, &identity)?;
722    let model = string_val(caller, &model)?;
723    let input_tokens = optional_number(caller, input_tokens)?;
724
725    let ty = embeddings_backing_struct(caller.engine())?;
726    abi::new_backing(
727        caller,
728        ty,
729        &[
730            Val::AnyRef(Some(vectors.to_anyref())),
731            Val::F64(count.to_bits()),
732            Val::F64(dimensions.to_bits()),
733            identity,
734            model,
735            input_tokens,
736        ],
737    )
738}
739
740fn build_model(
741    caller: &mut wasmtime::Caller<'_, StoreData>,
742    model: EmbeddingModel,
743) -> wasmtime::Result<Val> {
744    let name = string_val(caller, &model.name)?;
745    let description = match model.description.as_deref().and_then(sanitize_description) {
746        Some(text) => string_val(caller, &text)?,
747        None => crate::runtime::prelude::undefined::value(caller)?,
748    };
749    let max_input_tokens = optional_number(caller, model.max_input_tokens.map(|n| n as f64))?;
750    let identity = string_val(caller, &model.identity)?;
751    let ty = model_backing_struct(caller.engine())?;
752    abi::new_backing(
753        caller,
754        ty,
755        &[
756            name,
757            description,
758            Val::F64((model.dimensions as f64).to_bits()),
759            max_input_tokens,
760            Val::F64((model.max_input_bytes as f64).to_bits()),
761            identity,
762        ],
763    )
764}
765
766fn string_val(caller: &mut wasmtime::Caller<'_, StoreData>, text: &str) -> wasmtime::Result<Val> {
767    Ok(Val::AnyRef(Some(
768        write_submilli_string_struct(caller, text)?.to_anyref(),
769    )))
770}
771
772/// Copy row `index` out of the sealed result. The index must be an integer below
773/// `count`; anything else is the program's mistake, a `RangeError`.
774fn read_row(
775    caller: &mut wasmtime::Caller<'_, StoreData>,
776    receiver: &Val,
777    index: &Val,
778    ctx: &str,
779) -> wasmtime::Result<Vec<u8>> {
780    let Val::F64(bits) = index else {
781        return Err(fatal_host_error(format!("{ctx}: index is not a number")));
782    };
783    let index = f64::from_bits(*bits);
784
785    let st = abi::backing_receiver(caller, receiver)?;
786    let Val::AnyRef(Some(vectors)) = st.field(&mut *caller, E_VECTORS)? else {
787        return Err(fatal_host_error(format!(
788            "{ctx}: result vectors are missing"
789        )));
790    };
791    let vectors = vectors
792        .as_array(&mut *caller)?
793        .ok_or_else(|| fatal_host_error(format!("{ctx}: result vectors are not an array")))?;
794    let (Val::F64(count), Val::F64(dimensions)) = (
795        st.field(&mut *caller, E_COUNT)?,
796        st.field(&mut *caller, E_DIMENSIONS)?,
797    ) else {
798        return Err(fatal_host_error(format!("{ctx}: result shape is missing")));
799    };
800    let (count, dimensions) = (f64::from_bits(count), f64::from_bits(dimensions));
801    let in_range = index.is_finite() && index.fract() == 0.0 && index >= 0.0 && index < count;
802    if !in_range {
803        return Err(range_error(format!(
804            "{ctx}: index {index} is out of range for {count} vectors — use an integer from 0 to \
805             count - 1"
806        )));
807    }
808    let row_bytes = (dimensions as usize)
809        .checked_mul(4)
810        .ok_or_else(|| fatal_host_error(format!("{ctx}: row size overflows")))?;
811    let offset = (index as usize)
812        .checked_mul(row_bytes)
813        .and_then(|offset| u32::try_from(offset).ok())
814        .ok_or_else(|| fatal_host_error(format!("{ctx}: row offset overflows")))?;
815    // The row copy-out is charged by size, before it is made.
816    fuel::charge(&mut *caller, fuel::COPY, row_bytes as u64)?;
817    let mut row = Vec::new();
818    row.try_reserve_exact(row_bytes)
819        .map_err(|error| fatal_host_error(format!("{ctx}: {error}")))?;
820    row.resize(row_bytes, 0);
821    vectors
822        .read_i8(&mut *caller, offset, &mut row)
823        .map_err(|error| fatal_host_error(format!("{ctx}: {error}")))?;
824    Ok(row)
825}
826
827/// A `number[]` of the row's components, widened from `f32`.
828fn build_number_array(
829    caller: &mut wasmtime::Caller<'_, StoreData>,
830    row: &[u8],
831) -> wasmtime::Result<Val> {
832    // Admit the whole array before boxing any element.
833    fuel::charge(&mut *caller, fuel::ELEM, (row.len() / 4) as u64)?;
834    let mut boxed = Vec::with_capacity(row.len() / 4);
835    for chunk in row.as_chunks::<4>().0 {
836        let value = f32::from_le_bytes(*chunk);
837        boxed.push(Val::AnyRef(Some(
838            write_boxed_number_struct(caller, f64::from(value))?.to_anyref(),
839        )));
840    }
841    Ok(Val::AnyRef(Some(
842        write_submilli_array_struct_precharged(caller, &boxed)?.to_anyref(),
843    )))
844}
845
846#[cfg(test)]
847mod tests {
848    use std::pin::Pin;
849    use std::sync::atomic::{AtomicUsize, Ordering};
850    use std::sync::{Arc, Mutex};
851
852    use crate::runtime::{
853        CheckOutcome, EmbeddingBatch, EmbeddingError, EmbeddingFailureReason, EmbeddingLimits,
854        EmbeddingModel, EmbeddingProvider, EmbeddingTokenBudget, Purpose, RuntimeConfig,
855        SecurityCheck, SharedTokenBudget, StoreData, SubBatchSettlement, Vfs, dispatch_main_async,
856        install_runtime_async,
857    };
858
859    type BoxFuture<'a, T> = Pin<Box<dyn std::future::Future<Output = T> + Send + 'a>>;
860
861    /// What the mock answers a send with.
862    #[derive(Clone, Copy)]
863    enum Outcome {
864        /// Succeeds and reports usage equal to the estimate.
865        Reported,
866        /// Fails after sending; the estimate stays held.
867        TransportFailure,
868        /// Sends, then reports an internal bookkeeping failure.
869        Internal,
870        /// Sent, then failed, having reported this many tokens.
871        FailedAfter(u64),
872        /// Returns one row for however many texts were sent, with 50 input tokens.
873        CountMismatch,
874    }
875
876    /// Counts `embed` calls and answers deterministically. The `embed` count is
877    /// what proves "the provider was not called".
878    struct MockProvider {
879        dimensions: usize,
880        max_input_bytes: u64,
881        outcome: Outcome,
882        embed_calls: AtomicUsize,
883        /// Provider-reported input tokens on a successful batch. `None` leaves
884        /// the batch's count unreported, which is the older mock's behavior.
885        input_tokens: Option<u64>,
886    }
887
888    impl MockProvider {
889        fn new(dimensions: usize, max_input_bytes: u64, outcome: Outcome) -> Arc<Self> {
890            Arc::new(Self {
891                dimensions,
892                max_input_bytes,
893                outcome,
894                embed_calls: AtomicUsize::new(0),
895                input_tokens: None,
896            })
897        }
898
899        fn reporting(tokens: u64) -> Arc<Self> {
900            Arc::new(Self {
901                dimensions: 2,
902                max_input_bytes: 1_000,
903                outcome: Outcome::Reported,
904                embed_calls: AtomicUsize::new(0),
905                input_tokens: Some(tokens),
906            })
907        }
908
909        fn calls(&self) -> usize {
910            self.embed_calls.load(Ordering::Relaxed)
911        }
912    }
913
914    impl EmbeddingProvider for MockProvider {
915        fn embed<'a>(
916            &'a self,
917            alias: &'a str,
918            texts: &'a [String],
919            _purpose: Purpose,
920            budget: &'a EmbeddingTokenBudget,
921        ) -> BoxFuture<'a, Result<EmbeddingBatch, EmbeddingError>> {
922            self.embed_calls.fetch_add(1, Ordering::Relaxed);
923            Box::pin(async move {
924                let estimate = self.estimate_tokens(alias, texts);
925                budget.mark_sent(alias, estimate)?;
926                if matches!(self.outcome, Outcome::Internal) {
927                    return Err(EmbeddingError::Internal {
928                        alias: alias.to_string(),
929                        settlements: vec![SubBatchSettlement {
930                            estimate,
931                            reported: 0,
932                            indeterminate: estimate,
933                        }],
934                    });
935                }
936                if matches!(self.outcome, Outcome::TransportFailure) {
937                    return Err(EmbeddingError::Provider {
938                        alias: alias.to_string(),
939                        reason: EmbeddingFailureReason::Transport,
940                        settlements: vec![SubBatchSettlement {
941                            estimate,
942                            reported: 0,
943                            indeterminate: estimate,
944                        }],
945                    });
946                }
947                if matches!(self.outcome, Outcome::CountMismatch) {
948                    let values = vec![0.5f32; self.dimensions];
949                    return EmbeddingBatch::new(values, 1, self.dimensions, "emb1:mock", alias)
950                        .map(|batch| {
951                            batch.with_input_tokens(Some(50)).with_settlements(vec![
952                                SubBatchSettlement {
953                                    estimate,
954                                    reported: 50,
955                                    indeterminate: 0,
956                                },
957                            ])
958                        })
959                        .map_err(|_| EmbeddingError::Malformed {
960                            alias: alias.to_string(),
961                            reason: crate::runtime::EmbeddingMalformedReason::CountMismatch,
962                            settlements: Vec::new(),
963                        });
964                }
965                if let Outcome::FailedAfter(reported) = self.outcome {
966                    return Err(EmbeddingError::Provider {
967                        alias: alias.to_string(),
968                        reason: EmbeddingFailureReason::Transport,
969                        settlements: vec![SubBatchSettlement {
970                            estimate,
971                            reported,
972                            indeterminate: estimate.saturating_sub(reported),
973                        }],
974                    });
975                }
976                let values = vec![0.5f32; texts.len() * self.dimensions];
977                EmbeddingBatch::new(values, texts.len(), self.dimensions, "emb1:mock", alias)
978                    .map(|batch| {
979                        batch
980                            .with_input_tokens(self.input_tokens)
981                            .with_settlements(vec![SubBatchSettlement {
982                                estimate,
983                                reported: self.input_tokens.unwrap_or(estimate),
984                                indeterminate: 0,
985                            }])
986                    })
987                    .map_err(|_| EmbeddingError::Malformed {
988                        alias: alias.to_string(),
989                        reason: crate::runtime::EmbeddingMalformedReason::InvalidBody,
990                        settlements: Vec::new(),
991                    })
992            })
993        }
994
995        fn models<'a>(&'a self) -> BoxFuture<'a, Result<Vec<EmbeddingModel>, EmbeddingError>> {
996            let model = EmbeddingModel {
997                name: "mock".to_string(),
998                description: None,
999                dimensions: self.dimensions as u64,
1000                max_input_tokens: None,
1001                max_input_bytes: self.max_input_bytes,
1002                identity: "emb1:mock".to_string(),
1003            };
1004            Box::pin(async move { Ok(vec![model]) })
1005        }
1006
1007        fn max_input_bytes(&self, alias: &str) -> Option<u64> {
1008            (alias == "mock").then_some(self.max_input_bytes)
1009        }
1010    }
1011
1012    struct RecordingPolicy(Arc<Mutex<Vec<serde_json::Value>>>);
1013
1014    impl SecurityCheck for RecordingPolicy {
1015        fn check(
1016            &self,
1017            _caller: &str,
1018            _capability: &str,
1019            context: &serde_json::Value,
1020        ) -> CheckOutcome {
1021            if let Ok(mut contexts) = self.0.lock() {
1022                contexts.push(context.clone());
1023            }
1024            CheckOutcome::Allow { rule: None }
1025        }
1026    }
1027
1028    /// Runs `source` against the provider and returns what the host observed:
1029    /// the `main` result and the host-attached bytes still held at the end.
1030    struct Run {
1031        result: wasmtime::Result<String>,
1032        host_attached_bytes: u64,
1033        /// GC heap growth the limiter has observed for the whole run.
1034        observed_bytes: u64,
1035        model_calls: Vec<crate::runtime::ModelCallUsage>,
1036    }
1037
1038    async fn run(
1039        source: &str,
1040        provider: Option<Arc<MockProvider>>,
1041        budget: Option<Arc<EmbeddingTokenBudget>>,
1042        policy: Option<Arc<dyn SecurityCheck>>,
1043    ) -> Run {
1044        let compiled = crate::compile_script(source, "test.ts", crate::FileId(0), &[], &[])
1045            .expect("compile clean");
1046        let cfg = RuntimeConfig::default();
1047        let engine = cfg.engine().expect("engine");
1048        let mut data = StoreData::with_vfs("test-run".into(), Vfs::tempdir().expect("tempdir"));
1049        data.install_type_info(compiled.type_info.clone());
1050        data.embedding_provider = provider.map(|p| p as Arc<dyn EmbeddingProvider>);
1051        data.embedding_budget = budget;
1052        if let Some(policy) = policy {
1053            data.security_check = policy;
1054        }
1055        let mut store = cfg.store_async(&engine, data).expect("store");
1056        crate::runtime::install_tenant_limits(&mut store);
1057        let module = wasmtime::Module::new(&engine, &compiled.wasm).expect("module");
1058        let mut linker = wasmtime::Linker::<StoreData>::new(&engine);
1059        install_runtime_async(&mut linker, &mut store)
1060            .await
1061            .expect("install");
1062        let inst = linker
1063            .instantiate_async(&mut store, &module)
1064            .await
1065            .expect("instantiate");
1066        let result = dispatch_main_async(&mut store, &inst)
1067            .await
1068            .map(Option::unwrap_or_default);
1069        let host_attached_bytes = store.data().tenant_limits.host_attached_bytes();
1070        let observed_bytes = store.data().tenant_limits.observed_bytes();
1071        let model_calls = store.data().model_calls().to_vec();
1072        Run {
1073            result,
1074            host_attached_bytes,
1075            observed_bytes,
1076            model_calls,
1077        }
1078    }
1079
1080    fn budget(limits: EmbeddingLimits) -> Arc<EmbeddingTokenBudget> {
1081        Arc::new(EmbeddingTokenBudget::new(
1082            limits,
1083            SharedTokenBudget::new(u64::MAX),
1084        ))
1085    }
1086
1087    const ROUND_TRIP: &str = r#"import embedding from "submilli:embedding";
1088        function main(): void {
1089          const r = embedding.embed("mock", ["a", "b", "c"], "document");
1090          assert(r.count === 3, "three vectors");
1091        }"#;
1092
1093    /// `Embeddings` and `EmbeddingModel` stringify through their properties;
1094    /// the vectors, read through methods, are not among them.
1095    #[tokio::test]
1096    async fn embeddings_and_models_stringify_their_properties() {
1097        let provider = MockProvider::new(4, 10, Outcome::Reported);
1098        let run = run(
1099            r#"import embedding from "submilli:embedding";
1100               function main(): string {
1101                 const r = embedding.embed("mock", ["a"], "document");
1102                 return JSON.stringify(r)! + "|" + JSON.stringify(embedding.models())!;
1103               }"#,
1104            Some(provider),
1105            None,
1106            None,
1107        )
1108        .await;
1109        let out = run.result.expect("program completes");
1110        let (embeddings, models) = out.split_once('|').expect("two values");
1111        let embeddings: serde_json::Value = serde_json::from_str(embeddings).expect("JSON");
1112        assert_eq!(embeddings["count"], 1, "{embeddings}");
1113        assert_eq!(embeddings["dimensions"], 4, "{embeddings}");
1114        assert_eq!(embeddings["model"], "mock", "{embeddings}");
1115        assert!(embeddings.get("vectors").is_none(), "{embeddings}");
1116        assert_eq!(
1117            models,
1118            r#"[{"name":"mock","dimensions":4,"maxInputBytes":10,"identity":"emb1:mock"}]"#
1119        );
1120    }
1121
1122    /// AE1: an over-length input is refused before the provider is called, and
1123    /// the budget is unchanged.
1124    #[tokio::test]
1125    async fn ae1_over_length_input_is_refused_before_the_provider_and_the_budget() {
1126        let provider = MockProvider::new(4, 10, Outcome::Reported);
1127        let budget = budget(EmbeddingLimits::default());
1128        let run = run(
1129            r#"import embedding from "submilli:embedding";
1130               function main(): void {
1131                 let message = "";
1132                 try {
1133                   embedding.embed("mock", ["ok", "ok", "this one is too long"], "document");
1134                 } catch (e: RangeError) {
1135                   message = e.message;
1136                 }
1137                 assert(message.indexOf("text 2") >= 0, "names index 2: " + message);
1138               }"#,
1139            Some(Arc::clone(&provider)),
1140            Some(Arc::clone(&budget)),
1141            None,
1142        )
1143        .await;
1144        run.result.expect("program completes");
1145        assert_eq!(provider.calls(), 0, "the provider is never called");
1146        assert_eq!(budget.used(), 0, "nothing is charged");
1147        assert_eq!(budget.held(), 0, "nothing is held");
1148        assert_eq!(budget.requests(), 0, "nothing counts as sent");
1149    }
1150
1151    /// AE6: an exhausted per-run budget is a `QuotaExceededError` and nothing is
1152    /// sent.
1153    #[tokio::test]
1154    async fn ae6_exhausted_budget_refuses_without_calling_the_provider() {
1155        let provider = MockProvider::new(4, 1_000, Outcome::Reported);
1156        let budget = budget(EmbeddingLimits {
1157            per_execution_tokens: 1,
1158            ..EmbeddingLimits::default()
1159        });
1160        let run = run(
1161            r#"import embedding from "submilli:embedding";
1162               function main(): void {
1163                 let quota = false;
1164                 try {
1165                   embedding.embed("mock", ["more than one token of text"], "document");
1166                 } catch (e: QuotaExceededError) {
1167                   quota = true;
1168                 }
1169                 assert(quota, "the call is a QuotaExceededError");
1170               }"#,
1171            Some(Arc::clone(&provider)),
1172            Some(Arc::clone(&budget)),
1173            None,
1174        )
1175        .await;
1176        run.result.expect("program completes");
1177        assert_eq!(provider.calls(), 0, "the provider is never called");
1178        assert_eq!(budget.used(), 0, "the refusal charged nothing");
1179        assert_eq!(budget.requests(), 0);
1180    }
1181
1182    /// Settlement is applied once on success: the reported usage is committed and
1183    /// nothing stays held.
1184    #[tokio::test]
1185    async fn success_settles_reported_usage() {
1186        let provider = MockProvider::new(4, 1_000, Outcome::Reported);
1187        let budget = budget(EmbeddingLimits::default());
1188        let run = run(ROUND_TRIP, Some(provider), Some(Arc::clone(&budget)), None).await;
1189        run.result.expect("program completes");
1190        assert_eq!(
1191            budget.used(),
1192            3,
1193            "three one-byte texts estimate one token each"
1194        );
1195        assert_eq!(budget.held(), 0, "reported usage leaves nothing held");
1196        assert_eq!(budget.requests(), 1);
1197    }
1198
1199    /// A send that fails after leaving keeps its estimate held (unknown spend is
1200    /// indeterminate, not free), and the program sees a catchable error.
1201    #[tokio::test]
1202    async fn failure_after_send_settles_the_estimate_as_held() {
1203        let provider = MockProvider::new(4, 1_000, Outcome::TransportFailure);
1204        let budget = budget(EmbeddingLimits::default());
1205        let run = run(
1206            r#"import embedding from "submilli:embedding";
1207               function main(): void {
1208                 let message = "";
1209                 try {
1210                   embedding.embed("mock", ["secret text"], "document");
1211                 } catch (e: Error) {
1212                   message = e.message;
1213                 }
1214                 assert(message.indexOf("transport") >= 0, message);
1215                 assert(message.indexOf("secret text") < 0, "no input text in the error");
1216               }"#,
1217            Some(provider),
1218            Some(Arc::clone(&budget)),
1219            None,
1220        )
1221        .await;
1222        run.result.expect("program completes");
1223        assert_eq!(budget.held(), 4, "ceil(11 / 3) tokens stay held");
1224        assert_eq!(budget.used(), 4, "and count against the run");
1225    }
1226
1227    /// AE8: a 128 x 3,072 result is held at 4 bytes per number in the GC heap —
1228    /// not the ~60 bytes a plain array costs — and reading one vector or its
1229    /// bytes works.
1230    #[tokio::test]
1231    async fn ae8_results_are_held_at_four_bytes_per_number() {
1232        const COUNT: u64 = 128;
1233        const DIMENSIONS: u64 = 3072;
1234        let source = |texts: u32| {
1235            format!(
1236                r#"import embedding from "submilli:embedding";
1237               function main(): void {{
1238                 const texts: string[] = [];
1239                 for (let i = 0; i < {texts}; i = i + 1) {{
1240                   texts.push("t");
1241                 }}
1242                 const r = embedding.embed("mock", texts, "document");
1243                 assert(r.count === {texts} && r.dimensions === 3072, "shape");
1244                 assert(r.vector(0).length === 3072, "reading vector 0 returns 3,072 numbers");
1245                 assert(r.bytes(0).length === 12288, "exporting it returns 12,288 bytes");
1246                 if ({texts} > 5) {{
1247                   assert(r.vector(5).length === 3072, "reading vector 5 returns 3,072 numbers");
1248                   assert(r.bytes(5).length === 12288, "exporting it returns 12,288 bytes");
1249                 }}
1250                 let range = false;
1251                 try {{
1252                   r.vector({texts});
1253                 }} catch (e: RangeError) {{
1254                   range = true;
1255                 }}
1256                 assert(range, "reading vector {texts} is a RangeError");
1257               }}"#
1258            )
1259        };
1260        let provider = |_| MockProvider::new(DIMENSIONS as usize, 1_000, Outcome::Reported);
1261        let one = run(&source(1), Some(provider(())), None, None).await;
1262        one.result.expect("one-vector program completes");
1263        let many = run(&source(COUNT as u32), Some(provider(())), None, None).await;
1264        many.result.expect("program completes");
1265
1266        // The two runs differ only in the result: 127 more vectors. The GC heap
1267        // growth the limiter observed grows by that many vectors at 4 bytes per
1268        // number (within 10%: the heap grows in steps, and 127 one-character texts ride along).
1269        let expected = (COUNT - 1) * DIMENSIONS * 4;
1270        let grown = many.observed_bytes.saturating_sub(one.observed_bytes);
1271        assert!(
1272            grown >= expected - expected / 10 && grown <= expected + expected / 10,
1273            "the result costs about count x dimensions x 4 bytes of GC heap: grew {grown}, \
1274             expected about {expected}"
1275        );
1276        assert_eq!(
1277            many.host_attached_bytes, 0,
1278            "the vectors are not host-attached bytes"
1279        );
1280    }
1281
1282    /// Discarded results are reclaimed by collection: 100 results of 128 x 3,072
1283    /// numbers (1.5 MiB each, 150 MiB in all) fit the default 50 MB store when
1284    /// each loop pass drops the last one. The texts are built once so the loop
1285    /// allocates almost nothing else and only the results press on the heap.
1286    #[tokio::test]
1287    async fn discarded_results_are_collected_under_the_default_cap() {
1288        let provider = MockProvider::new(3072, 1_000, Outcome::Reported);
1289        let run = run(
1290            r#"import embedding from "submilli:embedding";
1291               function main(): void {
1292                 const texts: string[] = [];
1293                 for (let i = 0; i < 128; i = i + 1) {
1294                   texts.push("t");
1295                 }
1296                 let total = 0;
1297                 for (let round = 0; round < 100; round = round + 1) {
1298                   const r = embedding.embed("mock", texts, "document");
1299                   total = total + r.count;
1300                 }
1301                 assert(total === 12800, "every round returned its vectors");
1302               }"#,
1303            Some(provider),
1304            Some(budget(EmbeddingLimits::default())),
1305            None,
1306        )
1307        .await;
1308        run.result
1309            .expect("program completes without memory exhaustion");
1310    }
1311
1312    /// The hidden vectors array is sealed: no declared member reaches it, and a
1313    /// cast to `Uint8Array` is refused at run time rather than aliasing it.
1314    #[tokio::test]
1315    async fn the_hidden_vectors_are_not_reachable_from_the_guest() {
1316        for member in ["vectors", "handle", "data", "buffer"] {
1317            let source = format!(
1318                r#"import embedding from "submilli:embedding";
1319                   function main(): void {{
1320                     const r = embedding.embed("mock", ["a"], "document");
1321                     const hidden = r.{member};
1322                   }}"#
1323            );
1324            assert!(
1325                crate::compile_script(&source, "test.ts", crate::FileId(0), &[], &[]).is_err(),
1326                "`Embeddings.{member}` must not type-check"
1327            );
1328        }
1329        let provider = MockProvider::new(4, 1_000, Outcome::Reported);
1330        let cast = run(
1331            r#"import embedding from "submilli:embedding";
1332               function main(): void {
1333                 const r = embedding.embed("mock", ["a"], "document");
1334                 const u = r as unknown as Uint8Array;
1335                 u[0] = 255;
1336               }"#,
1337            Some(provider),
1338            None,
1339            None,
1340        )
1341        .await;
1342        assert!(
1343            cast.result.is_err(),
1344            "casting the result to a Uint8Array must fail, not expose the vectors"
1345        );
1346
1347        // Hashing the result as bytes must never read the vectors. The cast to
1348        // `string | Uint8Array` refuses at run time (the value is neither); the
1349        // host-level refusal behind it is pinned by
1350        // `a_host_read_of_the_result_as_a_uint8array_is_refused`.
1351        for call in [
1352            "crypto.sha256(x)",
1353            "crypto.hmacSha256(crypto.randomBytes(4), x)",
1354        ] {
1355            let provider = MockProvider::new(4, 1_000, Outcome::Reported);
1356            let source = format!(
1357                r#"import embedding from "submilli:embedding";
1358                   import crypto from "submilli:crypto";
1359                   function main(): void {{
1360                     const r = embedding.embed("mock", ["a"], "document");
1361                     const x = r as unknown as (string | Uint8Array);
1362                     crypto.sha256(crypto.randomBytes(1));
1363                     {call};
1364                   }}"#
1365            );
1366            let outcome = run(&source, Some(provider), None, None).await;
1367            assert!(
1368                outcome.result.is_err(),
1369                "`{call}` on the result must fail, not hash the vectors"
1370            );
1371        }
1372    }
1373
1374    /// The host-side seal behind every `Uint8Array` argument: a backing struct
1375    /// with a hidden byte field is not a `$Uint8Array`, so reading it as one is
1376    /// refused even if a cast were bypassed.
1377    #[tokio::test]
1378    async fn a_host_read_of_the_result_as_a_uint8array_is_refused() {
1379        let compiled = crate::compile_script(
1380            "function main(): void {}",
1381            "test.ts",
1382            crate::FileId(0),
1383            &[],
1384            &[],
1385        )
1386        .expect("compile clean");
1387        let cfg = RuntimeConfig::default();
1388        let engine = cfg.engine().expect("engine");
1389        let mut data = StoreData::with_vfs("test-run".into(), Vfs::tempdir().expect("tempdir"));
1390        data.install_type_info(compiled.type_info.clone());
1391        let mut store = cfg.store_async(&engine, data).expect("store");
1392        crate::runtime::install_tenant_limits(&mut store);
1393        let module = wasmtime::Module::new(&engine, &compiled.wasm).expect("module");
1394        let mut linker = wasmtime::Linker::<StoreData>::new(&engine);
1395        install_runtime_async(&mut linker, &mut store)
1396            .await
1397            .expect("install");
1398        linker
1399            .instantiate_async(&mut store, &module)
1400            .await
1401            .expect("instantiate");
1402
1403        let probe = wasmtime::Func::new(
1404            &mut store,
1405            wasmtime::FuncType::new(&engine, [], []),
1406            |mut caller, _, _| {
1407                let batch = EmbeddingBatch::new(vec![1.0, 2.0], 1, 2, "id", "mock")
1408                    .map_err(wasmtime::Error::new)?;
1409                let sealed = super::build_embeddings(&mut caller, batch)?;
1410                let refused =
1411                    crate::runtime::host::read_uint8_array_arg(&mut caller, &sealed, "probe");
1412                match refused {
1413                    Err(error) if error.to_string().contains("expects a Uint8Array") => Ok(()),
1414                    other => Err(wasmtime::Error::msg(format!(
1415                        "the sealed result was not refused: {other:?}"
1416                    ))),
1417                }
1418            },
1419        );
1420        probe
1421            .call_async(&mut store, &[], &mut [])
1422            .await
1423            .expect("the host refuses to read the sealed result as bytes");
1424    }
1425
1426    /// The vectors count against the run's memory cap like any GC object: a store
1427    /// too small for the result ends the run.
1428    #[tokio::test]
1429    async fn the_result_charge_counts_against_the_run_memory_cap() {
1430        let provider = MockProvider::new(3072, 1_000, Outcome::Reported);
1431        let compiled = crate::compile_script(
1432            r#"import embedding from "submilli:embedding";
1433               function main(): void {
1434                 const texts: string[] = [];
1435                 for (let i = 0; i < 128; i = i + 1) {
1436                   texts.push("t");
1437                 }
1438                 embedding.embed("mock", texts, "document");
1439               }"#,
1440            "test.ts",
1441            crate::FileId(0),
1442            &[],
1443            &[],
1444        )
1445        .expect("compile clean");
1446        let cfg = RuntimeConfig::default();
1447        let engine = cfg.engine().expect("engine");
1448        let mut data = StoreData::with_vfs("test-run".into(), Vfs::tempdir().expect("tempdir"));
1449        data.install_type_info(compiled.type_info.clone());
1450        data.embedding_provider = Some(provider);
1451        let budget = budget(EmbeddingLimits::default());
1452        data.embedding_budget = Some(Arc::clone(&budget));
1453        let mut store = cfg.store_async(&engine, data).expect("store");
1454        crate::runtime::install_tenant_limits(&mut store);
1455        let module = wasmtime::Module::new(&engine, &compiled.wasm).expect("module");
1456        let mut linker = wasmtime::Linker::<StoreData>::new(&engine);
1457        install_runtime_async(&mut linker, &mut store)
1458            .await
1459            .expect("install");
1460        let inst = linker
1461            .instantiate_async(&mut store, &module)
1462            .await
1463            .expect("instantiate");
1464        // Leave the program less than the 128 x 3,072 x 4 = 1.5 MiB of
1465        // vectors it is about to ask for.
1466        let cap = store.data().tenant_limits.observed_bytes() + 100_000;
1467        store.data_mut().tenant_limits.max_total_bytes = cap;
1468        let result = dispatch_main_async(&mut store, &inst).await;
1469        let error = result.expect_err("the cap refuses the result");
1470        assert!(
1471            crate::runtime::is_memory_exhausted(&error),
1472            "a memory refusal ends the run: {error:?}"
1473        );
1474        // The result is built after settlement: the provider's spend is
1475        // committed even though the guest never sees it.
1476        assert_eq!(budget.used(), 128, "the reported usage is settled");
1477        assert_eq!(budget.held(), 0, "nothing stays held");
1478    }
1479
1480    /// An internal provider failure ends the run rather than becoming a catchable
1481    /// error, and the sent sub-batch stays held.
1482    #[tokio::test]
1483    async fn an_internal_provider_failure_ends_the_run_and_settles_the_budget() {
1484        let provider = MockProvider::new(4, 1_000, Outcome::Internal);
1485        let budget = budget(EmbeddingLimits::default());
1486        let run = run(
1487            r#"import embedding from "submilli:embedding";
1488               function main(): void {
1489                 try {
1490                   embedding.embed("mock", ["secret text"], "document");
1491                 } catch (e: Error) {
1492                   assert(false, "an internal failure must not be catchable");
1493                 }
1494               }"#,
1495            Some(provider),
1496            Some(Arc::clone(&budget)),
1497            None,
1498        )
1499        .await;
1500        let error = run.result.expect_err("the run ends");
1501        assert!(
1502            crate::runtime::host::ends_the_run(&error),
1503            "an internal failure is fatal: {error:?}"
1504        );
1505        assert_eq!(budget.held(), 4, "ceil(11 / 3) tokens stay held");
1506        assert_eq!(budget.used(), 4);
1507    }
1508
1509    /// The filter context is exactly `model` and `input_count`; input text never
1510    /// reaches policy, and `models()` asks with `input_count` 0.
1511    #[tokio::test]
1512    async fn the_filter_context_carries_the_numbers_and_never_the_text() {
1513        const SECRET: &str = "the patient's diagnosis is confidential";
1514        let provider = MockProvider::new(4, 1_000, Outcome::Reported);
1515        let contexts = Arc::new(Mutex::new(Vec::new()));
1516        let policy: Arc<dyn SecurityCheck> = Arc::new(RecordingPolicy(Arc::clone(&contexts)));
1517        let run = run(
1518            &format!(
1519                r#"import embedding from "submilli:embedding";
1520                   function main(): void {{
1521                     embedding.embed("mock", ["{SECRET}", "b"], "query");
1522                     embedding.models();
1523                   }}"#
1524            ),
1525            Some(provider),
1526            None,
1527            Some(policy),
1528        )
1529        .await;
1530        run.result.expect("program completes");
1531
1532        let contexts = contexts.lock().expect("contexts");
1533        assert_eq!(contexts.len(), 2, "one check per embed, one per candidate");
1534        for context in contexts.iter() {
1535            let mut keys: Vec<&str> = context
1536                .as_object()
1537                .expect("an object context")
1538                .keys()
1539                .map(String::as_str)
1540                .collect();
1541            keys.sort_unstable();
1542            assert_eq!(keys, ["input_count", "model"]);
1543            assert!(!context.to_string().contains("patient"), "{context}");
1544        }
1545        assert_eq!(contexts[0]["input_count"], 2, "embed: the text count");
1546        assert_eq!(contexts[1]["input_count"], 0, "models: zero");
1547    }
1548
1549    /// An unknown alias is refused after the gate and before the budget, naming
1550    /// the aliases that exist.
1551    #[tokio::test]
1552    async fn an_unknown_alias_names_the_available_ones_and_charges_nothing() {
1553        let provider = MockProvider::new(4, 1_000, Outcome::Reported);
1554        let budget = budget(EmbeddingLimits::default());
1555        let run = run(
1556            r#"import embedding from "submilli:embedding";
1557               function main(): void {
1558                 let message = "";
1559                 try {
1560                   embedding.embed("ghost", ["a"], "document");
1561                 } catch (e: Error) {
1562                   message = e.message;
1563                 }
1564                 assert(message.indexOf("mock") >= 0, message);
1565               }"#,
1566            Some(Arc::clone(&provider)),
1567            Some(Arc::clone(&budget)),
1568            None,
1569        )
1570        .await;
1571        run.result.expect("program completes");
1572        assert_eq!(provider.calls(), 0);
1573        assert_eq!(budget.used(), 0);
1574    }
1575
1576    /// A successful embed records the alias the program passed and the tokens
1577    /// the provider reported. That record is not an llm call of the same name.
1578    #[tokio::test]
1579    async fn an_embed_records_input_tokens_for_the_alias() {
1580        let provider = MockProvider::reporting(42);
1581        let run = run(
1582            r#"import embedding from "submilli:embedding";
1583               function main(): void {
1584                 embedding.embed("mock", ["a", "b"], "document");
1585               }"#,
1586            Some(provider),
1587            None,
1588            None,
1589        )
1590        .await;
1591        run.result.expect("program completes");
1592        let calls = run.model_calls;
1593        assert_eq!(
1594            calls,
1595            vec![crate::runtime::ModelCallUsage::embedding("mock", Some(42))]
1596        );
1597        assert_eq!(
1598            crate::runtime::ModelCallUsage::summed_by_model(&calls),
1599            vec![crate::runtime::ModelCallUsage::embedding("mock", Some(42))]
1600        );
1601    }
1602
1603    /// A failed embed that already reported tokens still records them. The call
1604    /// log does, and the embedder's bill must not disagree.
1605    #[tokio::test]
1606    async fn a_failed_embed_that_reported_tokens_keeps_them() {
1607        let provider = MockProvider::new(2, 1_000, Outcome::FailedAfter(4));
1608        let run = run(
1609            r#"import embedding from "submilli:embedding";
1610               function main(): void {
1611                 embedding.embed("mock", ["a"], "document");
1612               }"#,
1613            Some(provider),
1614            None,
1615            None,
1616        )
1617        .await;
1618        assert!(run.result.is_err(), "the failed embed reaches the guest");
1619        assert_eq!(
1620            run.model_calls,
1621            vec![crate::runtime::ModelCallUsage::embedding("mock", Some(4))]
1622        );
1623    }
1624
1625    /// A provider `Ok` whose row count does not match still ran. The guest sees
1626    /// an error; the embedder still sees the tokens the batch reported.
1627    #[tokio::test]
1628    async fn a_count_mismatch_still_records_reported_tokens() {
1629        let provider = MockProvider::new(2, 1_000, Outcome::CountMismatch);
1630        let run = run(
1631            r#"import embedding from "submilli:embedding";
1632               function main(): void {
1633                 embedding.embed("mock", ["a", "b"], "document");
1634               }"#,
1635            Some(provider),
1636            None,
1637            None,
1638        )
1639        .await;
1640        assert!(run.result.is_err(), "a short batch is a guest error");
1641        assert_eq!(
1642            run.model_calls,
1643            vec![crate::runtime::ModelCallUsage::embedding("mock", Some(50))]
1644        );
1645    }
1646}