1use std::fmt;
4#[cfg(not(target_arch = "wasm32"))]
5use std::io;
6use std::path::Path;
7
8use nativeview_abi::xxh64;
9use nativeview_codec::ByteReader;
10use nativeview_store::wire::{WireDecoder, WireEncoder};
11use nativeview_store::{NodeId, NodeStore};
12
13use crate::store_backend::Frame0SubmitError;
14use crate::{BackendApplyStats, StoreBackend, StoreWireReplica};
15
16use super::{PersistenceError, remove_corrupt_frame0, write_file_atomic};
17#[cfg(not(target_arch = "wasm32"))]
18use super::{ReadBoundedError, read_file_bounded};
19
20pub const DEFAULT_FRAME0_FILE_NAME: &str = "frame0.nv02";
21pub const FRAME0_FOOTER_SIZE: usize = 40;
22pub const MAX_FRAME0_FILE_BYTES: usize = 64 * 1024 * 1024;
24
25const FRAME0_XXH64_SEED: u64 = 0x4E56_4546_524D_3032;
26#[cfg(not(target_arch = "wasm32"))]
27const NV02_MAGIC_BYTES: [u8; 4] = *b"NV02";
28
29#[repr(transparent)]
31#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
32pub struct AppBuildId(pub u64);
33
34impl PartialEq<u64> for AppBuildId {
35 #[inline]
36 fn eq(&self, other: &u64) -> bool {
37 self.0 == *other
38 }
39}
40
41impl fmt::Display for AppBuildId {
42 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43 write!(f, "{}", self.0)
44 }
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
48pub struct Frame0Meta {
49 pub table_schema_hash: u64,
50 pub app_build_id: AppBuildId,
51 pub env_hash: u64,
52}
53
54impl Frame0Meta {
55 pub fn default_core() -> Self {
58 Self {
59 table_schema_hash: nativeview_tables::tables::core_tables_schema_hash(),
60 app_build_id: AppBuildId(0),
61 env_hash: 0,
62 }
63 }
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub struct Frame0Footer {
68 pub node_count: u32,
69 pub flags: u32,
70 pub table_schema_hash: u64,
71 pub app_build_id: AppBuildId,
72 pub env_hash: u64,
73 pub payload_xxh64: u64,
74}
75
76impl Frame0Footer {
77 pub fn to_bytes(self) -> [u8; FRAME0_FOOTER_SIZE] {
78 let mut out = [0u8; FRAME0_FOOTER_SIZE];
79 out[0..4].copy_from_slice(&self.node_count.to_le_bytes());
80 out[4..8].copy_from_slice(&self.flags.to_le_bytes());
81 out[8..16].copy_from_slice(&self.table_schema_hash.to_le_bytes());
82 out[16..24].copy_from_slice(&self.app_build_id.0.to_le_bytes());
83 out[24..32].copy_from_slice(&self.env_hash.to_le_bytes());
84 out[32..40].copy_from_slice(&self.payload_xxh64.to_le_bytes());
85 out
86 }
87
88 pub fn from_bytes(b: &[u8; FRAME0_FOOTER_SIZE]) -> Self {
89 let mut r = ByteReader::new(b);
90 Self {
91 node_count: r.read_u32().unwrap_or(0),
92 flags: r.read_u32().unwrap_or(0),
93 table_schema_hash: r.read_u64().unwrap_or(0),
94 app_build_id: AppBuildId(r.read_u64().unwrap_or(0)),
95 env_hash: r.read_u64().unwrap_or(0),
96 payload_xxh64: r.read_u64().unwrap_or(0),
97 }
98 }
99}
100
101#[derive(Debug, Clone, PartialEq, Eq)]
102pub enum Frame0Miss {
103 NotFound,
104 Io(String),
105 FlagsMismatch(u32),
106 Corrupt(&'static str),
107 Backend(String),
108 SchemaMismatch { expected: u64, actual: u64 },
109 BuildIdMismatch { expected: u64, actual: u64 },
110 EnvHashMismatch { expected: u64, actual: u64 },
111}
112
113impl fmt::Display for Frame0Miss {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 match self {
116 Self::NotFound => write!(f, "frame0.nv02 not found"),
117 Self::Io(e) => write!(f, "frame0.nv02 I/O error: {e}"),
118 Self::FlagsMismatch(fl) => write!(f, "frame0.nv02 unsupported flags: {fl:#x}"),
119 Self::Corrupt(m) => write!(f, "frame0.nv02 corrupt: {m}"),
120 Self::Backend(e) => write!(f, "frame0.nv02 backend commit error: {e}"),
121 Self::SchemaMismatch { expected, actual } => {
122 write!(
123 f,
124 "frame0.nv02 schema mismatch: {expected:#x} != {actual:#x}"
125 )
126 }
127 Self::BuildIdMismatch { expected, actual } => {
128 write!(
129 f,
130 "frame0.nv02 build_id mismatch: {expected:#x} != {actual:#x}"
131 )
132 }
133 Self::EnvHashMismatch { expected, actual } => {
134 write!(
135 f,
136 "frame0.nv02 env_hash mismatch: {expected:#x} != {actual:#x}"
137 )
138 }
139 }
140 }
141}
142
143impl std::error::Error for Frame0Miss {}
144
145pub struct Frame0File;
147
148impl Frame0File {
149 pub fn encode(store: &NodeStore, meta: Frame0Meta) -> Result<Vec<u8>, PersistenceError> {
150 let live_nodes = store.stats().live_nodes;
151 let node_count =
152 u32::try_from(live_nodes).map_err(|_| PersistenceError::PayloadTooLarge(live_nodes))?;
153 let mut out = Vec::with_capacity(live_nodes.saturating_mul(64) + FRAME0_FOOTER_SIZE + 64);
154 WireEncoder::default().encode_full(store, &mut out);
155 if out.len().saturating_add(FRAME0_FOOTER_SIZE) > MAX_FRAME0_FILE_BYTES {
156 return Err(PersistenceError::PayloadTooLarge(out.len()));
157 }
158 append_footer(&mut out, node_count, meta);
159 Ok(out)
160 }
161
162 pub fn encode_nv02(
163 nv02_payload: &[u8],
164 node_count: u32,
165 meta: Frame0Meta,
166 ) -> Result<Vec<u8>, PersistenceError> {
167 let (frame, _ops) = WireDecoder::validate_header(nv02_payload)?;
168 if frame != 1 {
169 return Err(PersistenceError::Corrupt(
170 "NV02 frame0 must be keyframe (frame == 1)",
171 ));
172 }
173 let max_nodes = (nv02_payload.len() / 4).min(NodeId::MAX_INDEX as usize);
174 if (node_count as usize) > max_nodes {
175 return Err(PersistenceError::Corrupt(
176 "node_count exceeds NV02 payload capacity",
177 ));
178 }
179 if nv02_payload.len().saturating_add(FRAME0_FOOTER_SIZE) > MAX_FRAME0_FILE_BYTES {
180 return Err(PersistenceError::PayloadTooLarge(nv02_payload.len()));
181 }
182 let mut out = Vec::with_capacity(nv02_payload.len() + FRAME0_FOOTER_SIZE);
183 out.extend_from_slice(nv02_payload);
184 append_footer(&mut out, node_count, meta);
185 Ok(out)
186 }
187
188 pub fn save(
189 path: impl AsRef<Path>,
190 store: &NodeStore,
191 meta: Frame0Meta,
192 ) -> Result<Frame0Footer, PersistenceError> {
193 let bytes = Self::encode(store, meta)?;
194 write_file_atomic(path.as_ref(), &bytes, true)?;
195 let arr: [u8; FRAME0_FOOTER_SIZE] = bytes[bytes.len() - FRAME0_FOOTER_SIZE..]
196 .try_into()
197 .map_err(|_| PersistenceError::Corrupt("footer slice"))?;
198 Ok(Frame0Footer::from_bytes(&arr))
199 }
200
201 pub fn save_bytes(
202 path: impl AsRef<Path>,
203 envelope_bytes: &[u8],
204 ) -> Result<(), PersistenceError> {
205 write_file_atomic(path.as_ref(), envelope_bytes, true)
206 }
207
208 pub fn validate_bytes(
209 bytes: &[u8],
210 expected: Frame0Meta,
211 ) -> Result<(Frame0Footer, &[u8]), Frame0Miss> {
212 if bytes.len() > MAX_FRAME0_FILE_BYTES {
213 return Err(Frame0Miss::Corrupt("frame0.nv02 exceeds max size"));
214 }
215 if bytes.len() < FRAME0_FOOTER_SIZE {
216 return Err(Frame0Miss::Corrupt("truncated below 40-byte footer"));
217 }
218 let split = bytes.len() - FRAME0_FOOTER_SIZE;
219 let payload = &bytes[..split];
220 let arr: [u8; FRAME0_FOOTER_SIZE] = bytes[split..]
221 .try_into()
222 .map_err(|_| Frame0Miss::Corrupt("invalid footer slice"))?;
223 let footer = Frame0Footer::from_bytes(&arr);
224 if xxh64(&bytes[..bytes.len() - 8], FRAME0_XXH64_SEED) != footer.payload_xxh64 {
225 return Err(Frame0Miss::Corrupt("XXH64 checksum mismatch"));
226 }
227 let Ok((frame, _ops)) = WireDecoder::validate_header(payload) else {
228 return Err(Frame0Miss::Corrupt("invalid NV02 keyframe header"));
229 };
230 if frame != 1 {
231 return Err(Frame0Miss::Corrupt(
232 "NV02 frame0 must be keyframe (frame == 1)",
233 ));
234 }
235 let max_nodes = (payload.len() / 4).min(NodeId::MAX_INDEX as usize);
236 if (footer.node_count as usize) > max_nodes {
237 return Err(Frame0Miss::Corrupt(
238 "footer node_count exceeds NV02 payload capacity",
239 ));
240 }
241 if footer.flags != 0 {
242 return Err(Frame0Miss::FlagsMismatch(footer.flags));
243 }
244 if footer.table_schema_hash != expected.table_schema_hash {
245 return Err(Frame0Miss::SchemaMismatch {
246 expected: expected.table_schema_hash,
247 actual: footer.table_schema_hash,
248 });
249 }
250 if footer.app_build_id != expected.app_build_id {
251 return Err(Frame0Miss::BuildIdMismatch {
252 expected: expected.app_build_id.0,
253 actual: footer.app_build_id.0,
254 });
255 }
256 if footer.env_hash != expected.env_hash {
257 return Err(Frame0Miss::EnvHashMismatch {
258 expected: expected.env_hash,
259 actual: footer.env_hash,
260 });
261 }
262 Ok((footer, payload))
263 }
264
265 pub fn read_and_validate_bytes(
269 bytes: &[u8],
270 expected_schema_hash: u64,
271 expected_app_build_id: u64,
272 expected_env_hash: u64,
273 ) -> Result<(Frame0Footer, &[u8]), Frame0Miss> {
274 Self::validate_bytes(
275 bytes,
276 Frame0Meta {
277 table_schema_hash: expected_schema_hash,
278 app_build_id: AppBuildId(expected_app_build_id),
279 env_hash: expected_env_hash,
280 },
281 )
282 }
283
284 pub fn read_and_validate(
285 path: impl AsRef<Path>,
286 expected: Frame0Meta,
287 ) -> Result<(Frame0Footer, Vec<u8>), Frame0Miss> {
288 let mut buf = Vec::new();
289 let footer = Self::read_into_buf(path.as_ref(), expected, &mut buf)?;
290 buf.truncate(buf.len() - FRAME0_FOOTER_SIZE);
291 Ok((footer, buf))
292 }
293
294 pub fn boot_bytes_into_replica<B: StoreBackend>(
295 bytes: &[u8],
296 expected: Frame0Meta,
297 replica: &mut StoreWireReplica<B>,
298 ) -> Result<(Frame0Footer, BackendApplyStats), Frame0Miss> {
299 let (footer, payload) = Self::validate_bytes(bytes, expected)?;
300 Self::boot_validated_into_replica(footer, payload, replica, None)
301 }
302
303 pub fn boot_into_replica<B: StoreBackend>(
304 path: impl AsRef<Path>,
305 expected: Frame0Meta,
306 replica: &mut StoreWireReplica<B>,
307 ) -> Result<(Frame0Footer, BackendApplyStats), Frame0Miss> {
308 Self::boot_into_replica_with_buf(path, expected, &mut Vec::new(), replica)
309 }
310
311 pub fn boot_into_replica_with_buf<B: StoreBackend>(
312 path: impl AsRef<Path>,
313 expected: Frame0Meta,
314 scratch: &mut Vec<u8>,
315 replica: &mut StoreWireReplica<B>,
316 ) -> Result<(Frame0Footer, BackendApplyStats), Frame0Miss> {
317 let path = path.as_ref();
318 let footer = Self::read_into_buf(path, expected, scratch)?;
319 let payload = &scratch[..scratch.len() - FRAME0_FOOTER_SIZE];
320 Self::boot_validated_into_replica(footer, payload, replica, Some(path))
321 }
322
323 fn boot_validated_into_replica<B: StoreBackend>(
324 footer: Frame0Footer,
325 payload: &[u8],
326 replica: &mut StoreWireReplica<B>,
327 disk_path: Option<&Path>,
328 ) -> Result<(Frame0Footer, BackendApplyStats), Frame0Miss> {
329 let res = replica.submit_frame0_nv02(payload, footer.node_count as usize);
330 map_frame0_submit_result(res, footer, disk_path)
331 }
332
333 #[cfg(not(target_arch = "wasm32"))]
336 pub fn file_has_nv02_magic(path: &Path) -> bool {
337 use std::io::Read as _;
338 let Ok(mut f) = std::fs::File::open(path) else {
339 return false;
340 };
341 let mut magic = [0u8; 4];
342 f.read_exact(&mut magic).is_ok() && magic == NV02_MAGIC_BYTES
343 }
344
345 fn read_into_buf(
346 path: &Path,
347 expected: Frame0Meta,
348 buf: &mut Vec<u8>,
349 ) -> Result<Frame0Footer, Frame0Miss> {
350 #[cfg(target_arch = "wasm32")]
351 {
352 let _ = (path, expected, buf);
353 Err(Frame0Miss::NotFound)
354 }
355 #[cfg(not(target_arch = "wasm32"))]
356 {
357 let mut file = match std::fs::File::open(path) {
358 Ok(f) => f,
359 Err(e) if e.kind() == io::ErrorKind::NotFound => return Err(Frame0Miss::NotFound),
360 Err(e) => return Err(Frame0Miss::Io(e.to_string())),
361 };
362 match read_file_bounded(&mut file, MAX_FRAME0_FILE_BYTES, buf) {
363 Ok(()) => {}
364 Err(ReadBoundedError::Io(e)) => return Err(Frame0Miss::Io(e.to_string())),
365 Err(ReadBoundedError::TooLarge) => {
366 drop(file);
367 if Self::file_has_nv02_magic(path) {
368 let _ = std::fs::remove_file(path);
369 }
370 return Err(Frame0Miss::Corrupt("frame0.nv02 exceeds max size"));
371 }
372 }
373 drop(file);
374 Self::validate_bytes(buf, expected)
375 .map(|(f, _)| f)
376 .map_err(|miss| {
377 if matches!(miss, Frame0Miss::Corrupt(_)) && buf.starts_with(&NV02_MAGIC_BYTES) {
378 let _ = std::fs::remove_file(path);
379 }
380 miss
381 })
382 }
383 }
384}
385
386fn map_frame0_submit_result(
387 res: Result<BackendApplyStats, Frame0SubmitError>,
388 footer: Frame0Footer,
389 disk_path: Option<&Path>,
390) -> Result<(Frame0Footer, BackendApplyStats), Frame0Miss> {
391 match res {
392 Ok(stats) => Ok((footer, stats)),
393 Err(Frame0SubmitError::NodeCountMismatch) => {
394 remove_corrupt_frame0(disk_path);
395 Err(Frame0Miss::Corrupt("footer node_count mismatch"))
396 }
397 Err(Frame0SubmitError::Wire) => {
398 remove_corrupt_frame0(disk_path);
399 Err(Frame0Miss::Corrupt("NV02 decode failed"))
400 }
401 Err(Frame0SubmitError::Alloc) => {
402 Err(Frame0Miss::Backend("NV02 allocation failed".to_string()))
403 }
404 Err(Frame0SubmitError::Backend(err)) => Err(Frame0Miss::Backend(err.to_string())),
405 }
406}
407
408fn append_footer(out: &mut Vec<u8>, node_count: u32, meta: Frame0Meta) {
409 let f = Frame0Footer {
410 node_count,
411 flags: 0,
412 table_schema_hash: meta.table_schema_hash,
413 app_build_id: meta.app_build_id,
414 env_hash: meta.env_hash,
415 payload_xxh64: 0,
416 };
417 let start = out.len();
418 out.extend_from_slice(&f.to_bytes());
419 let hash = xxh64(&out[..start + 32], FRAME0_XXH64_SEED);
420 out[start + 32..start + 40].copy_from_slice(&hash.to_le_bytes());
421}
422
423#[cfg(test)]
424mod tests {
425 use super::*;
426
427 #[test]
428 fn frame0_submit_alloc_error_maps_to_backend_miss_and_preserves_disk_file() {
429 let path = std::env::temp_dir().join(format!(
430 "nv_frame0_alloc_preserve_{}.nv02",
431 std::process::id()
432 ));
433 std::fs::write(&path, b"valid-cache-sentinel").expect("write sentinel");
434 let footer = Frame0Footer {
435 node_count: 1,
436 flags: 0,
437 table_schema_hash: 0,
438 app_build_id: AppBuildId(0),
439 env_hash: 0,
440 payload_xxh64: 0,
441 };
442 assert!(matches!(
443 map_frame0_submit_result(Err(Frame0SubmitError::Alloc), footer, Some(&path)),
444 Err(Frame0Miss::Backend(ref msg)) if msg.contains("allocation")
445 ));
446 assert!(
447 path.exists(),
448 "transient Frame0SubmitError::Alloc must preserve disk cache"
449 );
450 assert!(matches!(
451 map_frame0_submit_result(Err(Frame0SubmitError::Wire), footer, Some(&path)),
452 Err(Frame0Miss::Corrupt(_))
453 ));
454 assert!(
455 !path.exists(),
456 "deterministic Frame0SubmitError::Wire / Budget must remove corrupt disk cache"
457 );
458 }
459
460 #[test]
461 fn frame0_rejects_table_schema_hash_when_only_resource_kind_changes() {
462 use nativeview_store::{FlatResource, NvTable, Res, ValidatedWords};
463
464 struct KindAlpha;
465 impl FlatResource for KindAlpha {
466 const KIND: nativeview_abi::Key64 = nativeview_abi::Key64::of("test.frame0.kind_alpha");
467 type View<'a> = &'a [u32];
468 fn write_words(&self, out: &mut Vec<u32>) -> bool {
469 out.push(1);
470 true
471 }
472 fn validate(w: &[u32]) -> bool {
473 w.len() == 1
474 }
475 fn view(w: ValidatedWords<'_, Self>) -> &[u32] {
476 w.as_slice()
477 }
478 }
479
480 struct KindBeta;
481 impl FlatResource for KindBeta {
482 const KIND: nativeview_abi::Key64 = nativeview_abi::Key64::of("test.frame0.kind_beta");
483 type View<'a> = &'a [u32];
484 fn write_words(&self, out: &mut Vec<u32>) -> bool {
485 out.push(2);
486 true
487 }
488 fn validate(w: &[u32]) -> bool {
489 w.len() == 1
490 }
491 fn view(w: ValidatedWords<'_, Self>) -> &[u32] {
492 w.as_slice()
493 }
494 }
495
496 #[allow(dead_code)]
497 #[derive(nativeview_store::NvTable)]
498 #[nv_table(name = "test.frame0.res_kind_schema", storage = "sparse")]
499 struct SchemaAlpha {
500 #[effect(paint)]
501 payload: Res<KindAlpha>,
502 }
503
504 #[allow(dead_code)]
505 #[derive(nativeview_store::NvTable)]
506 #[nv_table(name = "test.frame0.res_kind_schema", storage = "sparse")]
507 struct SchemaBeta {
508 #[effect(paint)]
509 payload: Res<KindBeta>,
510 }
511
512 let store = NodeStore::new();
513 let meta_alpha = Frame0Meta {
514 table_schema_hash: nativeview_store::tables_schema_hash(&[&SchemaAlpha::DESC]),
515 app_build_id: AppBuildId(1),
516 env_hash: 0,
517 };
518 let meta_beta = Frame0Meta {
519 table_schema_hash: nativeview_store::tables_schema_hash(&[&SchemaBeta::DESC]),
520 app_build_id: AppBuildId(1),
521 env_hash: 0,
522 };
523 assert_ne!(meta_alpha.table_schema_hash, meta_beta.table_schema_hash);
524 let bytes = Frame0File::encode(&store, meta_alpha).expect("encode frame0");
525 assert_eq!(
526 Frame0File::validate_bytes(&bytes, meta_beta).unwrap_err(),
527 Frame0Miss::SchemaMismatch {
528 expected: meta_beta.table_schema_hash,
529 actual: meta_alpha.table_schema_hash,
530 }
531 );
532 }
533}