ctb_formats_dcstring/navigator/
policy.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Projection policies, diagnostic actions, and forgiving defaults.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use super::{
30    Arc, BTreeMap, BinaryPayload, DEFAULT_MAX_PROJECTION_DEPTH,
31    DcBinaryResolver, DcCharExt, DcExpressionEvaluator, DcMixedDecode,
32    DcMstring, DcString, Digest, Duration, Integer, IpAddr, Ipv4Addr, Ipv6Addr,
33    Natural, PathBuf, Read, Seek, SyntaxRuleResolver, SystemTime, UNIX_EPOCH,
34};
35
36/// Maximum binary payload size (in bytes) eagerly loaded into memory when
37/// navigating or expanding frames from a seekable on-disk `.dcmm` file.
38/// Larger binary regions are represented as [`BinaryPayloadRef::FileSpan`].
39pub const INLINE_BINARY_THRESHOLD: u64 = 4096;
40
41/// Default maximum eagerly parsed metadata size for a seekable encapsulation.
42pub const MAX_BINARY_METADATA_BYTES: u64 = 1_048_576;
43
44/// Default maximum checksum-metadata nesting depth allowed when parsing
45/// textual binary encapsulation metadata.
46pub const DEFAULT_MAX_ENCAPSULATION_METADATA_DEPTH: usize = 32;
47
48/// Default maximum decoded payload size allowed when parsing a textual binary
49/// encapsulation into memory.
50pub const DEFAULT_MAX_ENCAPSULATION_PAYLOAD_BYTES: u64 = 67_108_864;
51
52/// Action to take when a syntax or projection anomaly is encountered.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum DiagnosticAction {
55    /// Immediately abort parsing or projection and return an `Err`.
56    Error,
57    /// Emit a warning via `warn_fmt!` and continue with recovery/fallback.
58    Warn,
59    /// Emit an informational log via `log_fmt!` and continue with recovery/fallback.
60    Log,
61    /// Continue silently with recovery/fallback (diagnostics are still recorded in the arena/inspector).
62    Ignore,
63}
64
65/// Version of the minimal trusted bootstrap kernel contract governing physical token
66/// codecs (`DcTF`, `.dcmm` header, `Dc 203`..`Dc 204`), `SeedGraphIndex` active triple
67/// resolution (`Dc 584`, `Dc 610`, `Dc 591`, `Dc 592`, `Dc 611`), `.Semantic:Pattern`
68/// operators (`Dc 599`..`Dc 607`, `Dc 642`..`Dc 644`), and Dc-WASM binary lowering
69/// (`Dc 647`..`Dc 1928`) + 32-byte mailbox ABI (`0..32`).
70///
71/// The foundational execution contract is explicitly specified and selectable by version
72/// during bootstrap before any document or graph interpretation that depends on it.
73#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
74pub enum BootstrapKernelVersion {
75    /// Initial frozen minimal trusted bootstrap kernel specification (v1).
76    V1 = 1,
77}
78
79impl Default for BootstrapKernelVersion {
80    fn default() -> Self {
81        Self::CURRENT
82    }
83}
84
85impl BootstrapKernelVersion {
86    /// The current supported bootstrap kernel version (`V1`).
87    pub const CURRENT: Self = Self::V1;
88
89    /// Returns the numeric version identifier (`1` for `V1`).
90    #[must_use]
91    pub const fn as_u32(self) -> u32 {
92        match self {
93            Self::V1 => 1,
94        }
95    }
96
97    /// Selects a [`BootstrapKernelVersion`] from an explicit numeric version identifier
98    /// during bootstrap before interpretation that depends on it.
99    ///
100    /// # Errors
101    /// Returns an error if `version` is not a supported bootstrap kernel version.
102    pub fn try_from_u32(version: u32) -> Result<Self> {
103        match version {
104            1 => Ok(Self::V1),
105            other => bail!(
106                "Unsupported bootstrap kernel version {other}: only version {} (V1) is supported by this host",
107                Self::CURRENT.as_u32()
108            ),
109        }
110    }
111
112    /// Verifies that the decoded WebAssembly `(prefix_opt, subopcode)` is permitted
113    /// under this bootstrap kernel version.
114    ///
115    /// In [`BootstrapKernelVersion::V1`], the `0xFB` GC opcode page (`Dc 903`..`Dc 1158`),
116    /// exception-handling instructions (`0x08` `throw`, `0x0A` `throw_ref`, `0x1F` `try_table`),
117    /// and `0xFD` Relaxed SIMD (`subopcode >= 256`, `Dc 1671`..`Dc 1926`) are explicitly gated.
118    ///
119    /// # Errors
120    /// Returns an error if the opcode belongs to a gated proposal page in `self`.
121    pub fn ensure_wasm_opcode_supported(
122        self,
123        prefix_opt: Option<u8>,
124        subopcode: u32,
125    ) -> Result<()> {
126        match self {
127            Self::V1 => match (prefix_opt, subopcode) {
128                (Some(0xFB), _) => bail!(
129                    "WASM 0xFB GC opcode page (subopcode {subopcode:#x}) is gated and unsupported in BootstrapKernelVersion::V1"
130                ),
131                (Some(0xFD), sub) if sub >= 256 => bail!(
132                    "WASM 0xFD Relaxed SIMD opcode page (subopcode {sub:#x}) is gated and unsupported in BootstrapKernelVersion::V1"
133                ),
134                (None, 0x08 | 0x0A | 0x1F) => bail!(
135                    "WASM exception-handling opcode {subopcode:#04x} is gated and unsupported in BootstrapKernelVersion::V1"
136                ),
137                _ => Ok(()),
138            },
139        }
140    }
141}
142
143/// Unified caller-specified policy governing how syntax errors, unknown tags,
144/// deprecated constructs, malformed or missing fields, and resource budgets
145/// are handled across Dc document parsing, validation, inspection, and typed
146/// projection.
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub struct DcProjectionPolicy {
149    /// Framing or syntax rule violation in Stage 1 (e.g. unclosed frame, bad literal header).
150    /// Unsupported checksum algorithms follow this action; recovery retains
151    /// payload bytes without verifying those checksums.
152    pub syntax_error: DiagnosticAction,
153    /// Unknown Dc tag encountered inside a container (e.g. forward-compatible field or statement).
154    pub unknown_field: DiagnosticAction,
155    /// Deprecated syntax or legacy representation (e.g. `<prefer>` replacement).
156    pub deprecated_syntax: DiagnosticAction,
157    /// Type mismatch or domain error when projecting a known field onto its Rust type.
158    pub malformed_field: DiagnosticAction,
159    /// Missing required field when projecting a struct (uses [`DcForgivingDefault`] if non-`Error`).
160    pub missing_required_field: DiagnosticAction,
161    /// Maximum container or wrapper nesting depth allowed during arena construction and projection.
162    pub max_depth: usize,
163    /// Action taken when container or wrapper nesting exceeds [`Self::max_depth`].
164    pub depth_limit_exceeded: DiagnosticAction,
165    /// Maximum eagerly allocated metadata bytes per seekable binary header.
166    /// Exceeding this resource budget is an error under every diagnostic policy.
167    pub max_binary_metadata_bytes: u64,
168    /// Maximum nested checksum-metadata levels allowed when parsing textual
169    /// binary encapsulation metadata. Exceeding this resource budget is an
170    /// error under every diagnostic policy.
171    pub max_encapsulation_metadata_depth: usize,
172    /// Maximum decoded payload bytes allowed when parsing a textual binary
173    /// encapsulation into memory. Exceeding this resource budget is an error
174    /// under every diagnostic policy.
175    pub max_encapsulation_payload_bytes: u64,
176    /// Optional diagnostic action when a document or nested document omits an
177    /// explicit `Dc 641` System-block most-recent node ID pin and does not
178    /// inherit one from an enclosing document or caller override.
179    pub missing_system_graph_pin: Option<DiagnosticAction>,
180    /// Optional designated baseline System-block snapshot node ID used when
181    /// resolving legacy documents that omit `Dc 641`. When `None`, unpinned
182    /// legacy documents resolve against the bundled System graph `HEAD` with
183    /// explicit [`super::DcPinProvenance::UnpinnedLegacyFallback`] provenance.
184    pub unpinned_fallback_most_recent_node_id: Option<u128>,
185    /// Foundational bootstrap kernel contract version governing physical codecs,
186    /// seed graph triple resolution, `.Semantic:Pattern` operators, and Dc-WASM lowering.
187    pub kernel_version: BootstrapKernelVersion,
188}
189
190impl DcProjectionPolicy {
191    /// Strict policy: errors on any syntax violation, unknown field tag,
192    /// malformed field, missing required field, or exceeded nesting depth;
193    /// warns on deprecated syntax.
194    #[must_use]
195    pub const fn strict() -> Self {
196        Self {
197            syntax_error: DiagnosticAction::Error,
198            unknown_field: DiagnosticAction::Error,
199            deprecated_syntax: DiagnosticAction::Warn,
200            malformed_field: DiagnosticAction::Error,
201            missing_required_field: DiagnosticAction::Error,
202            max_depth: DEFAULT_MAX_PROJECTION_DEPTH,
203            depth_limit_exceeded: DiagnosticAction::Error,
204            max_binary_metadata_bytes: MAX_BINARY_METADATA_BYTES,
205            max_encapsulation_metadata_depth:
206                DEFAULT_MAX_ENCAPSULATION_METADATA_DEPTH,
207            max_encapsulation_payload_bytes:
208                DEFAULT_MAX_ENCAPSULATION_PAYLOAD_BYTES,
209            missing_system_graph_pin: None,
210            unpinned_fallback_most_recent_node_id: None,
211            kernel_version: BootstrapKernelVersion::CURRENT,
212        }
213    }
214
215    /// Forgiving / best-effort policy: logs warnings and recovers at frame or
216    /// field boundaries, projecting all valid fields and substituting fallback
217    /// values for missing or damaged fields.
218    #[must_use]
219    pub const fn forgiving() -> Self {
220        Self {
221            syntax_error: DiagnosticAction::Warn,
222            unknown_field: DiagnosticAction::Warn,
223            deprecated_syntax: DiagnosticAction::Warn,
224            malformed_field: DiagnosticAction::Warn,
225            missing_required_field: DiagnosticAction::Warn,
226            max_depth: DEFAULT_MAX_PROJECTION_DEPTH,
227            depth_limit_exceeded: DiagnosticAction::Warn,
228            max_binary_metadata_bytes: MAX_BINARY_METADATA_BYTES,
229            max_encapsulation_metadata_depth:
230                DEFAULT_MAX_ENCAPSULATION_METADATA_DEPTH,
231            max_encapsulation_payload_bytes:
232                DEFAULT_MAX_ENCAPSULATION_PAYLOAD_BYTES,
233            missing_system_graph_pin: None,
234            unpinned_fallback_most_recent_node_id: None,
235            kernel_version: BootstrapKernelVersion::CURRENT,
236        }
237    }
238
239    /// Quiet forgiving policy for interactive source inspection (`DcSource::inspect`),
240    /// recording diagnostics without emitting warning logs.
241    #[must_use]
242    pub const fn forgiving_quiet() -> Self {
243        Self {
244            syntax_error: DiagnosticAction::Ignore,
245            unknown_field: DiagnosticAction::Ignore,
246            deprecated_syntax: DiagnosticAction::Ignore,
247            malformed_field: DiagnosticAction::Ignore,
248            missing_required_field: DiagnosticAction::Ignore,
249            max_depth: DEFAULT_MAX_PROJECTION_DEPTH,
250            depth_limit_exceeded: DiagnosticAction::Ignore,
251            max_binary_metadata_bytes: MAX_BINARY_METADATA_BYTES,
252            max_encapsulation_metadata_depth:
253                DEFAULT_MAX_ENCAPSULATION_METADATA_DEPTH,
254            max_encapsulation_payload_bytes:
255                DEFAULT_MAX_ENCAPSULATION_PAYLOAD_BYTES,
256            missing_system_graph_pin: None,
257            unpinned_fallback_most_recent_node_id: None,
258            kernel_version: BootstrapKernelVersion::CURRENT,
259        }
260    }
261
262    /// Returns a copy of this policy with a custom maximum nesting depth and action.
263    #[must_use]
264    pub const fn with_max_depth(
265        mut self,
266        max_depth: usize,
267        action: DiagnosticAction,
268    ) -> Self {
269        self.max_depth = max_depth;
270        self.depth_limit_exceeded = action;
271        self
272    }
273
274    /// Sets the eager metadata allocation budget for each seekable binary header.
275    #[must_use]
276    pub const fn with_max_binary_metadata_bytes(
277        mut self,
278        max_bytes: u64,
279    ) -> Self {
280        self.max_binary_metadata_bytes = max_bytes;
281        self
282    }
283
284    /// Sets the checksum-metadata nesting budget for textual binary
285    /// encapsulation metadata.
286    #[must_use]
287    pub const fn with_max_encapsulation_metadata_depth(
288        mut self,
289        max_depth: usize,
290    ) -> Self {
291        self.max_encapsulation_metadata_depth = max_depth;
292        self
293    }
294
295    /// Sets the decoded payload allocation budget for textual binary
296    /// encapsulations.
297    #[must_use]
298    pub const fn with_max_encapsulation_payload_bytes(
299        mut self,
300        max_bytes: u64,
301    ) -> Self {
302        self.max_encapsulation_payload_bytes = max_bytes;
303        self
304    }
305
306    /// Configures the diagnostic action taken when a document omits an explicit
307    /// `Dc 641` System-block most-recent node ID pin and does not inherit one
308    /// from an enclosing scope or caller override.
309    #[must_use]
310    pub const fn with_missing_system_graph_pin(
311        mut self,
312        action: DiagnosticAction,
313    ) -> Self {
314        self.missing_system_graph_pin = Some(action);
315        self
316    }
317
318    /// Configures the designated baseline System-block snapshot node ID used
319    /// when resolving legacy documents that omit `Dc 641`.
320    #[must_use]
321    pub const fn with_unpinned_fallback_most_recent_node_id(
322        mut self,
323        node_id: u128,
324    ) -> Self {
325        self.unpinned_fallback_most_recent_node_id = Some(node_id);
326        self
327    }
328
329    /// Selects the explicit [`BootstrapKernelVersion`] for this projection policy.
330    #[must_use]
331    pub const fn with_kernel_version(
332        mut self,
333        kernel_version: BootstrapKernelVersion,
334    ) -> Self {
335        self.kernel_version = kernel_version;
336        self
337    }
338
339    /// Validates and selects a [`BootstrapKernelVersion`] by numeric identifier (`1` for `V1`)
340    /// during bootstrap before any document or graph interpretation that depends on it.
341    ///
342    /// # Errors
343    /// Returns an error if `version` is not a supported bootstrap kernel version.
344    pub fn try_with_kernel_version_number(
345        mut self,
346        version: u32,
347    ) -> Result<Self> {
348        self.kernel_version = BootstrapKernelVersion::try_from_u32(version)?;
349        Ok(self)
350    }
351
352    /// Returns true if all structural and projection anomalies are set to `Error`.
353    #[must_use]
354    pub const fn is_strict(&self) -> bool {
355        matches!(self.syntax_error, DiagnosticAction::Error)
356            && matches!(self.unknown_field, DiagnosticAction::Error)
357            && matches!(self.malformed_field, DiagnosticAction::Error)
358            && matches!(self.missing_required_field, DiagnosticAction::Error)
359            && matches!(self.depth_limit_exceeded, DiagnosticAction::Error)
360    }
361
362    /// Returns true if any structural or projection anomaly is configured to recover/warn/ignore.
363    #[must_use]
364    pub const fn is_forgiving(&self) -> bool {
365        !self.is_strict()
366    }
367
368    /// Applies the configured [`DiagnosticAction`] for an anomaly message.
369    ///
370    /// # Errors
371    /// Returns an error if `action` is [`DiagnosticAction::Error`].
372    pub fn handle(
373        &self,
374        action: DiagnosticAction,
375        message: impl Into<String>,
376    ) -> Result<()> {
377        let msg = message.into();
378        match action {
379            DiagnosticAction::Error => bail!("{msg}"),
380            DiagnosticAction::Warn => {
381                warn_fmt!("{msg}");
382                Ok(())
383            }
384            DiagnosticAction::Log => {
385                log_fmt!("{msg}");
386                Ok(())
387            }
388            DiagnosticAction::Ignore => Ok(()),
389        }
390    }
391}
392
393/// Fallback value provider used when projecting structs or fields under a
394/// non-`Error` [`DcProjectionPolicy`] (`forgiving()`).
395pub trait DcForgivingDefault: Sized {
396    /// Produces a placeholder value when a required field or element is missing
397    /// or malformed in forgiving mode.
398    fn dc_forgiving_default() -> Self;
399}
400
401macro_rules! impl_forgiving_default_via_default {
402    ($($t:ty),*) => {
403        $(
404            impl DcForgivingDefault for $t {
405                fn dc_forgiving_default() -> Self {
406                    Self::default()
407                }
408            }
409        )*
410    };
411}
412
413impl_forgiving_default_via_default!(
414    u8,
415    u16,
416    u32,
417    u64,
418    u128,
419    usize,
420    i8,
421    i16,
422    i32,
423    i64,
424    i128,
425    isize,
426    bool,
427    String,
428    PathBuf,
429    Natural,
430    Integer,
431    BinaryPayload,
432    DcMstring,
433    DcString
434);
435
436impl DcForgivingDefault for Ipv4Addr {
437    fn dc_forgiving_default() -> Self {
438        Self::UNSPECIFIED
439    }
440}
441
442impl DcForgivingDefault for Ipv6Addr {
443    fn dc_forgiving_default() -> Self {
444        Self::UNSPECIFIED
445    }
446}
447
448impl DcForgivingDefault for IpAddr {
449    fn dc_forgiving_default() -> Self {
450        Self::V4(Ipv4Addr::UNSPECIFIED)
451    }
452}
453
454impl DcForgivingDefault for SystemTime {
455    fn dc_forgiving_default() -> Self {
456        UNIX_EPOCH
457    }
458}
459
460impl DcForgivingDefault for Duration {
461    fn dc_forgiving_default() -> Self {
462        Self::ZERO
463    }
464}
465
466impl DcForgivingDefault for FormatId {
467    fn dc_forgiving_default() -> Self {
468        Self::Utf8
469    }
470}
471
472impl<T> DcForgivingDefault for Option<T> {
473    fn dc_forgiving_default() -> Self {
474        None
475    }
476}
477
478impl<T> DcForgivingDefault for Vec<T> {
479    fn dc_forgiving_default() -> Self {
480        Self::new()
481    }
482}
483
484impl<K: Ord, V> DcForgivingDefault for BTreeMap<K, V> {
485    fn dc_forgiving_default() -> Self {
486        Self::new()
487    }
488}
489
490impl<T: DcForgivingDefault> DcForgivingDefault for Box<T> {
491    fn dc_forgiving_default() -> Self {
492        Self::new(T::dc_forgiving_default())
493    }
494}
495
496impl<T: DcForgivingDefault> DcForgivingDefault for Arc<T> {
497    fn dc_forgiving_default() -> Self {
498        Self::new(T::dc_forgiving_default())
499    }
500}
501
502impl<T: DcForgivingDefault, const N: usize> DcForgivingDefault for [T; N] {
503    fn dc_forgiving_default() -> Self {
504        std::array::from_fn(|_| T::dc_forgiving_default())
505    }
506}
507
508impl<A: DcForgivingDefault, B: DcForgivingDefault> DcForgivingDefault
509    for (A, B)
510{
511    fn dc_forgiving_default() -> Self {
512        (A::dc_forgiving_default(), B::dc_forgiving_default())
513    }
514}
515
516impl<A: DcForgivingDefault, B: DcForgivingDefault, C: DcForgivingDefault>
517    DcForgivingDefault for (A, B, C)
518{
519    fn dc_forgiving_default() -> Self {
520        (
521            A::dc_forgiving_default(),
522            B::dc_forgiving_default(),
523            C::dc_forgiving_default(),
524        )
525    }
526}
527
528impl<
529    A: DcForgivingDefault,
530    B: DcForgivingDefault,
531    C: DcForgivingDefault,
532    D: DcForgivingDefault,
533> DcForgivingDefault for (A, B, C, D)
534{
535    fn dc_forgiving_default() -> Self {
536        (
537            A::dc_forgiving_default(),
538            B::dc_forgiving_default(),
539            C::dc_forgiving_default(),
540            D::dc_forgiving_default(),
541        )
542    }
543}