ifc_lite_processing/result_cache/
mod.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Native warm-load cache of complete processing results (phase 1).
6//!
7//! A [`ResultCache`] wraps [`process`](crate::process): on a full pass whose
8//! source bytes, output-affecting request fields and engine identity match a
9//! stored entry, it replays that entry's exact [`ProcessingResult`] (every
10//! mesh, instance, frame, transform, metadata field, diagnostic and refusal
11//! count, in order, float bits intact) instead of processing. Otherwise it
12//! runs the unchanged pipeline and, in [`CacheMode::ReadWrite`], stores the
13//! result. `process` itself stays pure: callers that never build a cache never
14//! reach this module, and [`CacheMode::Off`] calls straight through without
15//! hashing anything.
16//!
17//! What it does not do (phase 1): replay sink events (the cached entry point
18//! takes no sink, so streaming and callback consumers keep calling `process`),
19//! cache a cancellable pass, trust an injected entity index, or cache the
20//! prepared-source tier (index/discovery). A request it cannot replay reports
21//! [`CacheOutcome::Bypass`] and runs live; it never returns a hit with missing
22//! outputs.
23//!
24//! Trust model: entries live in a per-user private directory (0700/0600,
25//! owner-checked, `O_NOFOLLOW`, digest-only names, see `store.rs`). Every
26//! entry is treated as untrusted input: bounded reads, checked arithmetic,
27//! per-section SHA-256 verified before anything is decoded, and any failure is
28//! a warning plus a miss and a recompute, never a panic or a partial result.
29//! The checksums detect damage, not authorship: a process running as the same
30//! user can write a self-consistent entry with wrong geometry, and this cache
31//! cannot tell. Environments that need that guarantee need authenticated
32//! entries or a separate trusted writer, which phase 1 does not provide.
33//!
34//! Keys, layout and store policy: `key.rs`, `envelope.rs`, `store.rs`.
35
36mod config;
37mod envelope;
38mod fs_private;
39mod key;
40mod mesh_codec;
41mod meta_codec;
42mod store;
43mod wire;
44mod report;
45#[cfg(test)]
46#[path = "codec_tests.rs"]
47mod codec_tests;
48#[cfg(test)]
49#[path = "store_tests.rs"]
50mod store_tests;
51
52pub use config::{default_directory, CacheMode, PassHook, ResultCacheConfig};
53pub use report::{BypassReason, CacheOutcome, CacheReport, CacheWork, MissReason, PublishOutcome};
54use config::HookSink;
55
56use crate::{ProcessingRequest, ProcessingResult};
57use envelope::EntryIdentity;
58use std::time::Instant;
59use store::{ReadEntry, ReadError, Store};
60
61/// A result and what the cache did to produce it.
62pub struct CachedProcessing {
63    pub result: ProcessingResult,
64    pub report: CacheReport,
65}
66
67/// A reusable cache context. Cheap to build; holds no open files.
68#[derive(Debug, Clone, Default)]
69pub struct ResultCache {
70    config: ResultCacheConfig,
71}
72
73/// Why a stored entry was not used. Display text goes into warnings.
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub(crate) enum CodecError {
76    Truncated,
77    Overflow,
78    BadMagic,
79    Unsupported(u32),
80    Layout(&'static str),
81    IdentityMismatch,
82    Checksum(&'static str),
83    Malformed(&'static str, &'static str),
84    Invariant(&'static str),
85}
86
87impl std::fmt::Display for CodecError {
88    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89        match self {
90            Self::Truncated => f.write_str("truncated"),
91            Self::Overflow => f.write_str("length or count overflows"),
92            Self::BadMagic => f.write_str("not a result-cache entry"),
93            Self::Unsupported(v) => write!(f, "unsupported entry format version {v}"),
94            Self::Layout(what) => write!(f, "bad layout: {what}"),
95            Self::IdentityMismatch => f.write_str("entry identity does not match its key"),
96            Self::Checksum(section) => write!(f, "{section} checksum mismatch"),
97            Self::Malformed(section, what) => write!(f, "malformed {section}: {what}"),
98            Self::Invariant(what) => write!(f, "invariant: {what}"),
99        }
100    }
101}
102
103impl ResultCache {
104    pub fn new(config: ResultCacheConfig) -> Self {
105        Self { config }
106    }
107
108    pub fn config(&self) -> &ResultCacheConfig {
109        &self.config
110    }
111
112    /// Process `content` as `request` asks, replaying a stored result when one
113    /// matches. The pass runs without a sink (see the module docs).
114    pub fn process(&self, content: &[u8], request: &ProcessingRequest) -> CachedProcessing {
115        let mut report = CacheReport::new(CacheOutcome::Off);
116        if self.config.mode == CacheMode::Off {
117            return self.run_live(content, request, report, None);
118        }
119        let request_digest = match key::request_digest(request) {
120            Ok(digest) => digest,
121            Err(reason) => {
122                report.outcome = CacheOutcome::Bypass(reason);
123                return self.run_live(content, request, report, None);
124            }
125        };
126        // Inside an execution account, source stop or terminal domain the
127        // pass can be refused or degraded by that scope; a hit would hand back
128        // a complete result the scope would not have produced, and a stored
129        // result could be a degraded one (PR #9614 review 2, R2-2).
130        if ifc_lite_geometry::resource::ambient_scope_active() {
131            report.outcome = CacheOutcome::Bypass(BypassReason::AmbientResourceScope);
132            return self.run_live(content, request, report, None);
133        }
134        let writable = self.config.mode == CacheMode::ReadWrite;
135        let Some(root) = self.config.directory.clone().or_else(default_directory) else {
136            report.outcome = CacheOutcome::Bypass(BypassReason::Unavailable("no cache directory".into()));
137            return self.run_live(content, request, report, None);
138        };
139        let store = match Store::open(&root, writable, self.config.max_bytes, self.config.max_entry_bytes)
140            .map(|store| store.with_min_free(self.config.min_free_bytes)) {
141            Ok(store) => Some(store),
142            Err(e) if !writable && e.kind() == std::io::ErrorKind::NotFound => None,
143            Err(e) => {
144                report.warn(format!("result cache unavailable at {}: {e}", root.display()));
145                report.outcome = CacheOutcome::Bypass(BypassReason::Unavailable(e.to_string()));
146                return self.run_live(content, request, report, None);
147            }
148        };
149
150        // Snapshot the engine (build, executable, effective output policy)
151        // before anything runs, so the key names the policy the pass will use.
152        let Some(engine) = key::EngineIdentity::current(&self.config.engine_salt) else {
153            report.warn("result cache: executable identity unreadable".into());
154            report.outcome = CacheOutcome::Bypass(BypassReason::Unavailable("no engine identity".into()));
155            return self.run_live(content, request, report, None);
156        };
157        let started = Instant::now();
158        let source_sha256 = key::source_digest(content);
159        report.work.hash = started.elapsed();
160        report.work.bytes_hashed = content.len() as u64;
161        let engine_digest = engine.digest();
162        let source_len = content.len() as u64;
163        let id = EntryIdentity {
164            key: key::cache_key(&source_sha256, source_len, &request_digest, &engine_digest),
165            source_sha256,
166            source_len,
167            request_digest,
168            engine_digest,
169        };
170        let key_hex = key::hex(&id.key);
171        report.key = Some(key_hex.clone());
172        let Some(store) = store else {
173            report.outcome = CacheOutcome::Miss(MissReason::Absent);
174            return self.run_live(content, request, report, None);
175        };
176        match lookup(&store, &key_hex, &id, self.config.max_entry_bytes, &mut report) {
177            Ok(_) if engine.policy_changed() => {
178                // A setter ran while the entry was read: the snapshot the key
179                // named is no longer the policy, so do not return it. The live
180                // run is not stored either (its policy may be mixed).
181                report.outcome = CacheOutcome::Miss(MissReason::PolicyChangedDuringLookup);
182                let publish = writable.then_some(Publish { store: &store, id: &id, key_hex: &key_hex, engine: &engine });
183                self.run_live(content, request, report, publish)
184            }
185            Ok((mut result, entry)) => {
186                if writable {
187                    store.touch(&entry);
188                }
189                result.stats.from_cache = true;
190                report.outcome = CacheOutcome::Hit;
191                CachedProcessing { result, report }
192            }
193            Err((reason, entry)) => {
194                if let (true, Some(entry)) = (writable, entry.as_ref()) {
195                    store.remove_if_same(&key_hex, entry);
196                }
197                report.outcome = CacheOutcome::Miss(reason);
198                let publish = writable.then_some(Publish { store: &store, id: &id, key_hex: &key_hex, engine: &engine });
199                self.run_live(content, request, report, publish)
200            }
201        }
202    }
203
204    /// The unchanged pipeline, then (read-write misses only) publication.
205    fn run_live(
206        &self,
207        content: &[u8],
208        request: &ProcessingRequest,
209        mut report: CacheReport,
210        publish: Option<Publish<'_>>,
211    ) -> CachedProcessing {
212        let started = Instant::now();
213        let (result, observed) = match &self.config.pass_hook {
214            Some(hook) => crate::processor::process_observed(content, request, &mut HookSink(hook, 0)),
215            None => crate::processor::process_observed(content, request, &mut ()),
216        };
217        report.work.process = started.elapsed();
218        if let Some(Publish { engine, .. }) = &publish {
219            // Any policy setter during the pass, even one undone before it
220            // ended, may have produced mixed output that is not this key's.
221            // A job of THIS pass ran under foreign resource state (decided by
222            // the pass itself, PR #9614 review 3, R3-3); or any stop happened
223            // anywhere during it; or it reported a refusal a replay would not
224            // repeat (scan reports R3-4, texture binaries R4-1).
225            let skip = if engine.policy_changed() {
226                Some(PublishOutcome::SkippedPolicyChanged)
227            } else if observed.foreign_resource_scope || engine.resource_stopped() {
228                Some(PublishOutcome::SkippedResourceStop)
229            } else if engine.refusal_reported() {
230                Some(PublishOutcome::SkippedRefusalReported)
231            } else {
232                None
233            };
234            if let Some(skip) = skip {
235                report.publish = skip;
236                return CachedProcessing { result, report };
237            }
238        }
239        if let Some(Publish { store, id, key_hex, .. }) = publish {
240            let limit = self.config.max_entry_bytes.min(self.config.max_bytes);
241            let at_least = envelope::payload_lower_bound(&result);
242            if at_least > limit {
243                // Certainly too big: refuse before encoding (no copy at all).
244                report.publish = PublishOutcome::SkippedOversized { bytes: at_least, limit };
245                return CachedProcessing { result, report };
246            }
247            let started = Instant::now();
248            let encoded = envelope::encode_parts(&result, id);
249            report.work.encode = started.elapsed();
250            report.publish = match encoded {
251                Ok(entry) => {
252                    let started = Instant::now();
253                    let outcome = store.publish_parts(key_hex, &entry.parts());
254                    report.work.write = started.elapsed();
255                    if matches!(outcome, PublishOutcome::Published { .. }) {
256                        report.work.entry_bytes_written = entry.len() as u64;
257                    }
258                    outcome
259                }
260                Err(e) => PublishOutcome::Unencodable(e.to_string()),
261            };
262            if let PublishOutcome::Failed(why) | PublishOutcome::Unencodable(why) = &report.publish {
263                report.warn(format!("result cache: not stored: {why}"));
264            }
265        }
266        CachedProcessing { result, report }
267    }
268}
269
270/// Where a read-write miss publishes, and the engine snapshot it was keyed on.
271struct Publish<'a> {
272    store: &'a Store,
273    id: &'a EntryIdentity,
274    key_hex: &'a str,
275    engine: &'a key::EngineIdentity,
276}
277
278type Lookup = Result<(ProcessingResult, ReadEntry), (MissReason, Option<ReadEntry>)>;
279
280/// Read, validate and decode one entry, timing each step into `report`.
281fn lookup(store: &Store, key_hex: &str, id: &EntryIdentity, limit: u64, report: &mut CacheReport) -> Lookup {
282    let started = Instant::now();
283    let read = store.read(key_hex);
284    report.work.read = started.elapsed();
285    let entry = match read {
286        Ok(Some(entry)) => entry,
287        Ok(None) => return Err((MissReason::Absent, None)),
288        Err(ReadError::Oversized(bytes)) => {
289            report.warn(format!("result cache: entry {key_hex} is {bytes} bytes, over the per-entry limit"));
290            return Err((MissReason::Oversized { bytes, limit }, None));
291        }
292        Err(ReadError::Io(e)) => {
293            report.warn(format!("result cache: could not read entry {key_hex}: {e}"));
294            return Err((MissReason::ReadFailed(e.to_string()), None));
295        }
296    };
297    report.work.entry_bytes_read = entry.bytes.len() as u64;
298    let started = Instant::now();
299    let layout = envelope::validate_entry(&entry.bytes, id);
300    report.work.validate = started.elapsed();
301    let decoded = layout.and_then(|layout| {
302        let started = Instant::now();
303        let decoded = envelope::decode_entry(&entry.bytes, &layout);
304        report.work.decode = started.elapsed();
305        decoded
306    });
307    match decoded {
308        Ok(result) => {
309            report.work.bytes_decoded = (entry.bytes.len() - envelope::BODY_START) as u64;
310            Ok((result, entry))
311        }
312        Err(e) => {
313            report.warn(format!("result cache: rejected entry {key_hex}: {e}"));
314            let reason = match e {
315                CodecError::Unsupported(version) => MissReason::Unsupported(version),
316                CodecError::IdentityMismatch => MissReason::IdentityMismatch,
317                other => MissReason::Corrupt(other.to_string()),
318            };
319            Err((reason, Some(entry)))
320        }
321    }
322}