diff --git a/CONFORMANCE.md b/CONFORMANCE.md index 3761858b..7e19ea8b 100644 --- a/CONFORMANCE.md +++ b/CONFORMANCE.md @@ -82,6 +82,19 @@ The three honesty levels (R2): | --- | --- | --- | | `UC-WEB-01` | `build` | The Pages client is generated from and conforms to its Prism product model in Uorc.Page: stakeholders, features with their calls and acceptance cases, journeys, the page's UML state machine, operations, fields, controls, examples, error hints, sections, usage, links and quality measures. The generated page holds exactly the modeled elements, and a real browser walks every journey, takes every modeled transition, checks every control's enabled state in every state it reaches and holds every gated quality measure. | +## performance-theorems + +| ID | Level | Statement | +| --- | --- | --- | +| `UC-PERF-02` | `build` | For every input length n, the settled frame of Uorc.Performance is no larger than the raw frame and no larger than a coded kernel candidate, and the raw frame is two length varints of at most 10 bytes each, the n input bytes and 41 fixed bytes, so no frame of one object exceeds n + 61 bytes (archiveBound), and a stream of k such frames is within n + 61 * k bytes; the native client keeps the same rule and the same constants. | +| `UC-PERF-03` | `build` | For every list of trials, the trial the portfolio keeps (Uorc.Performance best) is no larger in bytes than any coded trial in the list (bestNoLargerThanEvery), so a portfolio archive is no larger than the archive of any strategy it scheduled. | +| `UC-PERF-04` | `build` | A step is one model input evaluated for one coded bit. For every profile word the input count lies between 3 and 24 (17 context bits, 3 fixed inputs, 2 for each of the short-match and repeat features), a frame of n bytes costs 8 * n * inputs steps, and for every frame kind (raw, reference, ncm, ncm from a named state) decode takes at most 192 steps per modelled byte (decodeStepsBound); the full profile costs 192 steps per byte and the v0.3 profile 160. The measure counts model inputs, not machine time. | +| `UC-PERF-05` | `build` | A trial carries its defect, the count of bytes at which its decode differs from the input. Admission fails every trial with a nonzero defect, keeping never raises a defect above its operands', and the trial kept from any admitted list has defect 0 (bestOfAdmittedIsExact): whatever codec point or named model state produced a trial, it can change the archive's size and never its meaning. | +| `UC-PERF-06` | `build` | A candidate dominates an incumbent when it is no larger in bytes and no larger in steps, and its gain is the drop in bytes plus steps. The gain never exceeds the drop in cost (dominanceLowersCost), no trial gains over itself, gains compose (a positive gain of a over b and of b over c gives at least their sum of a over c), and a positive gain implies no growth in bytes or in steps: dominance is a strict partial order, so consolidating winners cannot cycle. | +| `UC-PERF-07` | `build` | A trial abandoned at a bound is modelled as a trial of at most the bound's bytes. For every list of trials and every raw length, the portfolio of trials abandoned at the raw length settles to the same size as the portfolio of complete trials (boundedPortfolioSettlesTheSame), and a trial no smaller than one already kept changes neither the kept bytes nor the kept steps (skippedTrial theorems): a search that stops a candidate once it cannot win, or skips one known to be no smaller, writes an archive of the same size for fewer compress steps. | +| `UC-PERF-08` | `build` | Choosing by fewer bytes and then fewer steps, from the raw frame and any list of trials, keeps a trial that is no later in that order than every trial in the list and than the raw frame (chosenIsLeast, chosenIsNoWorseThanRaw), has exactly the size the bytes-only rule settles to (chosenKeepsTheSize), and is dominated by no trial it is no later than (leastIsUndominated); a trial no earlier than the kept one changes nothing (excludedTrial theorems). The rule lowers decode steps on byte ties at no cost in size. The released client breaks byte ties by schedule order until its model export adopts this rule. | +| `UC-PERF-09` | `build` | The potential of a codec point is its bytes plus its steps. Consolidating a candidate into an incumbent lowers the potential by exactly the candidate's gain (consolidationSpendsItsGain), which is positive exactly when the candidate dominates, and over any sequence of candidates the potential never rises (potentialNeverRises). The potential is a natural number, so an engine that consolidates only dominating candidates never regresses and consolidates at most as many times as its first potential. | + ## product-interfaces | ID | Level | Statement | @@ -168,3 +181,11 @@ The three honesty levels (R2): | `UC-INT-05` | `build` | `build_evidence` | `not_measured` | Source-owned completed-view and continuous publication proofs derive the actual chosen-profile digest and emitted-image reads, discharging canonical driver termination and OwnedHash control/cleanup lifetime for both explicit format identities and arbitrary finite source input. Initial source-layout correspondence and full product acceptance remain separate consumer obligations. | | `UC-NEU-01` | `build` | `kernel_theorem` | `not_measured` | The ncm coder's plasticity is stated as the Prism neuromorphic standard in Uorc.Neuromorphic, with kernel-checked bounds: every mixer weight stays within plus or minus 2^22 under the bounded Hebbian rule, potentiation never lowers and depression never raises a weight, the plasticity lies between 24 and 128 per 65536 (128 at the first byte, 24 in the limit), one bit's weight change is at most 16376 and every product fits a 32-bit lane, a context slot never steps past its gap to the coded bit and consolidates at count 127, and every probability-map point stays within 16 bits; the native coder reads the model's constants. | | `UC-WEB-01` | `build` | `build_evidence` | `not_measured` | The Pages client is generated from and conforms to its Prism product model in Uorc.Page: stakeholders, features with their calls and acceptance cases, journeys, the page's UML state machine, operations, fields, controls, examples, error hints, sections, usage, links and quality measures. The generated page holds exactly the modeled elements, and a real browser walks every journey, takes every modeled transition, checks every control's enabled state in every state it reaches and holds every gated quality measure. | +| `UC-PERF-02` | `build` | `kernel_theorem` | `not_measured` | For every input length n, the settled frame of Uorc.Performance is no larger than the raw frame and no larger than a coded kernel candidate, and the raw frame is two length varints of at most 10 bytes each, the n input bytes and 41 fixed bytes, so no frame of one object exceeds n + 61 bytes (archiveBound), and a stream of k such frames is within n + 61 * k bytes; the native client keeps the same rule and the same constants. | +| `UC-PERF-03` | `build` | `kernel_theorem` | `not_measured` | For every list of trials, the trial the portfolio keeps (Uorc.Performance best) is no larger in bytes than any coded trial in the list (bestNoLargerThanEvery), so a portfolio archive is no larger than the archive of any strategy it scheduled. | +| `UC-PERF-04` | `build` | `kernel_theorem` | `not_measured` | A step is one model input evaluated for one coded bit. For every profile word the input count lies between 3 and 24 (17 context bits, 3 fixed inputs, 2 for each of the short-match and repeat features), a frame of n bytes costs 8 * n * inputs steps, and for every frame kind (raw, reference, ncm, ncm from a named state) decode takes at most 192 steps per modelled byte (decodeStepsBound); the full profile costs 192 steps per byte and the v0.3 profile 160. The measure counts model inputs, not machine time. | +| `UC-PERF-05` | `build` | `kernel_theorem` | `not_measured` | A trial carries its defect, the count of bytes at which its decode differs from the input. Admission fails every trial with a nonzero defect, keeping never raises a defect above its operands', and the trial kept from any admitted list has defect 0 (bestOfAdmittedIsExact): whatever codec point or named model state produced a trial, it can change the archive's size and never its meaning. | +| `UC-PERF-06` | `build` | `kernel_theorem` | `not_measured` | A candidate dominates an incumbent when it is no larger in bytes and no larger in steps, and its gain is the drop in bytes plus steps. The gain never exceeds the drop in cost (dominanceLowersCost), no trial gains over itself, gains compose (a positive gain of a over b and of b over c gives at least their sum of a over c), and a positive gain implies no growth in bytes or in steps: dominance is a strict partial order, so consolidating winners cannot cycle. | +| `UC-PERF-07` | `build` | `kernel_theorem` | `not_measured` | A trial abandoned at a bound is modelled as a trial of at most the bound's bytes. For every list of trials and every raw length, the portfolio of trials abandoned at the raw length settles to the same size as the portfolio of complete trials (boundedPortfolioSettlesTheSame), and a trial no smaller than one already kept changes neither the kept bytes nor the kept steps (skippedTrial theorems): a search that stops a candidate once it cannot win, or skips one known to be no smaller, writes an archive of the same size for fewer compress steps. | +| `UC-PERF-08` | `build` | `kernel_theorem` | `not_measured` | Choosing by fewer bytes and then fewer steps, from the raw frame and any list of trials, keeps a trial that is no later in that order than every trial in the list and than the raw frame (chosenIsLeast, chosenIsNoWorseThanRaw), has exactly the size the bytes-only rule settles to (chosenKeepsTheSize), and is dominated by no trial it is no later than (leastIsUndominated); a trial no earlier than the kept one changes nothing (excludedTrial theorems). The rule lowers decode steps on byte ties at no cost in size. The released client breaks byte ties by schedule order until its model export adopts this rule. | +| `UC-PERF-09` | `build` | `kernel_theorem` | `not_measured` | The potential of a codec point is its bytes plus its steps. Consolidating a candidate into an incumbent lowers the potential by exactly the candidate's gain (consolidationSpendsItsGain), which is positive exactly when the candidate dominates, and over any sequence of candidates the potential never rises (potentialNeverRises). The potential is a natural number, so an engine that consolidates only dominating candidates never regresses and consolidates at most as many times as its first potential. | diff --git a/crates/uorc/src/lib.rs b/crates/uorc/src/lib.rs index 05fed5fb..21dae631 100644 --- a/crates/uorc/src/lib.rs +++ b/crates/uorc/src/lib.rs @@ -61,6 +61,7 @@ pub mod archive; pub mod chunk; mod frame; pub mod ncm; +pub mod performance; pub mod portfolio; mod store; pub mod tree; diff --git a/crates/uorc/src/performance.rs b/crates/uorc/src/performance.rs new file mode 100644 index 00000000..af33e832 --- /dev/null +++ b/crates/uorc/src/performance.rs @@ -0,0 +1,246 @@ +//! The performance vocabulary of the Prism model (`Uorc.Performance`), as the +//! native client computes it: the step measure, the codec point and the +//! choice rules (least in bytes then steps, dominance, consolidation). +//! +//! A **step** is one model input evaluated for one coded bit. It is exact and +//! deterministic, and it is read from a frame's header alone: a raw frame +//! costs one step per output byte (the copy), a reference frame costs none +//! (its bytes were produced once already), and an ncm frame costs eight bits +//! times the inputs its profile word keeps, per output byte, with or without +//! the x86 filter. The constants are the model's; `tests/performance.rs` +//! reads them from the module text. + +use crate::frame::{Info, Representation}; +use crate::ncm; +use sha2::{Digest, Sha256}; + +/// Coded bits per output byte. +pub const BITS_PER_BYTE: u64 = 8; +/// Inputs every ncm profile evaluates beside its contexts: the match model's +/// two and the bias. +pub const FIXED_INPUTS: u32 = 3; +/// Inputs each optional model (short match, repeat distance) adds. +pub const FEATURE_INPUTS: u32 = 2; +/// Context bits of a profile word. +pub const CONTEXT_BITS: u32 = 17; +/// The most inputs any profile evaluates: 17 contexts, the fixed 3, two features. +pub const MAX_INPUTS: u32 = CONTEXT_BITS + FIXED_INPUTS + 2 * FEATURE_INPUTS; +/// The bound of `Uorc.Performance.decodeStepsBound`: no frame costs more +/// steps per output byte than this (the full model). +pub const MAX_STEPS_PER_BYTE: u64 = BITS_PER_BYTE * MAX_INPUTS as u64; +/// The bit of a codec point's profile word that says the frame is coded over +/// the x86 filter (the strategy table's encoding: bits 0-19 the ncm profile, +/// bit 31 the filter). The filter changes the bytes a frame codes, not its steps. +pub const POINT_X86: u32 = 1 << 31; +/// Domain tag of a codec point's identity. +pub const CODEC_POINT_TAG: &[u8] = b"uorc/codec-point/1"; + +/// Model inputs an ncm frame coded under `profile` evaluates per bit. +pub fn inputs(profile: u32) -> u32 { + (profile & ((1 << CONTEXT_BITS) - 1)).count_ones() + + FIXED_INPUTS + + FEATURE_INPUTS * u32::from(profile & ncm::F_SHORT != 0) + + FEATURE_INPUTS * u32::from(profile & ncm::F_REP != 0) +} + +/// Steps to decode `n` output bytes of a frame of this representation and +/// profile word; `None` for a representation the model states no measure for +/// (the ulz decoders kept for earlier archives, and searched programs). +pub fn steps(representation: Representation, profile: Option, n: u64) -> Option { + match representation { + Representation::Raw => Some(n), + Representation::Reference => Some(0), + Representation::Ncm | Representation::NcmX86 => { + Some(BITS_PER_BYTE * u64::from(inputs(profile.unwrap_or(ncm::V03))) * n) + } + Representation::Ulz | Representation::UlzKernel | Representation::Program => None, + } +} + +/// [`steps`] of the frame a header describes. +pub fn frame_steps(info: &Info) -> Option { + steps(info.representation, info.ncm_profile, info.output_len) +} + +/// A point of the codec space: which decoder basis, profile word, consolidated +/// model state and lane count code a frame. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CodecPoint { + /// The basis identity the frame names (the export's library), zeros when + /// the frame is self-contained. + pub basis: [u8; 32], + /// The ncm profile word, with [`POINT_X86`] set when the frame is coded + /// over the x86 filter; 0 when the frame applies no ncm decoder. + pub profile: u32, + /// κ of the consolidated model state the frame starts from, zeros for none. + pub state: [u8; 32], + /// Lanes the frame is coded in (1 for a single stream). + pub lanes: u32, +} + +impl CodecPoint { + /// The point of the frame a header describes (no state, one lane). + pub fn of(info: &Info) -> CodecPoint { + CodecPoint { + basis: info.basis.unwrap_or([0; 32]), + profile: info.ncm_profile.unwrap_or(0) + | if info.representation == Representation::NcmX86 { + POINT_X86 + } else { + 0 + }, + state: [0; 32], + lanes: 1, + } + } + + /// κ of the point: SHA-256 over the tag, the basis, the profile word + /// (little-endian), the state and the lane count (little-endian). + pub fn kappa(&self) -> [u8; 32] { + let mut h = Sha256::new(); + h.update(CODEC_POINT_TAG); + h.update(self.basis); + h.update(self.profile.to_le_bytes()); + h.update(self.state); + h.update(self.lanes.to_le_bytes()); + h.finalize().into() + } +} + +/// κ of a corpus: SHA-256 over `uorc/corpus/1` and, for each object in order, +/// its name length (u32 LE), name, SHA-256 and length (u64 LE). +pub fn corpus_kappa<'a>(objects: impl IntoIterator) -> [u8; 32] { + let mut h = Sha256::new(); + h.update(b"uorc/corpus/1"); + for (name, digest, len) in objects { + h.update((name.len() as u32).to_le_bytes()); + h.update(name.as_bytes()); + h.update(digest); + h.update(len.to_le_bytes()); + } + h.finalize().into() +} + +/// A coded trial as the model's choice rules see it: its archive bytes and +/// its decode steps (`Uorc.Performance.Trial.coded`, without the defect). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Trial { + /// Archive bytes. + pub bytes: u64, + /// Decode steps. + pub steps: u64, +} + +impl Trial { + /// `cost`: the potential the engine lowers, bytes plus steps. + pub fn cost(self) -> u64 { + self.bytes + self.steps + } +} + +/// `gainOf`: how far `candidate` dominates `incumbent` (no larger in bytes +/// and in steps): the drop in cost, 0 when it does not dominate. +pub fn gain(candidate: Trial, incumbent: Trial) -> u64 { + if candidate.bytes <= incumbent.bytes && candidate.steps <= incumbent.steps { + incumbent.cost() - candidate.cost() + } else { + 0 + } +} + +/// `lexGap`: 0 exactly when `a` is no later than `c` in the order "fewer +/// bytes, then fewer steps". +pub fn lex_gap(a: Trial, c: Trial) -> u64 { + a.bytes.saturating_sub(c.bytes) + + a.steps + .saturating_sub(c.steps) + .min(1) + .saturating_sub(c.bytes.saturating_sub(a.bytes)) +} + +/// `pick`: the kept trial after `head` is considered. A failed trial (`None`) +/// changes nothing; a coded one replaces the kept trial when it has fewer +/// bytes, or the same bytes and fewer steps. +pub fn pick(head: Option, kept: Trial) -> Trial { + match head { + Some(h) if h.bytes < kept.bytes || (h.bytes == kept.bytes && h.steps < kept.steps) => h, + _ => kept, + } +} + +/// `chosen`: the trial kept from the raw frame and the scheduled trials +/// (`chosenIsLeast`: least in bytes, then steps; `leastIsUndominated`). +pub fn chosen(raw: Trial, trials: &[Option]) -> Trial { + trials + .iter() + .rev() + .fold(raw, |kept, &head| pick(head, kept)) +} + +/// `consolidate`: the incumbent after `candidate` is decided: the candidate +/// when it dominates with a positive gain, else the incumbent +/// (`consolidationSpendsItsGain`: the cost drops by exactly the gain). +pub fn consolidate(candidate: Trial, incumbent: Trial) -> Trial { + if gain(candidate, incumbent) > 0 { + candidate + } else { + incumbent + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn steps_follow_the_profile_word() { + assert_eq!(inputs(ncm::V03), 20); + assert_eq!(inputs(ncm::FULL), MAX_INPUTS); + assert_eq!(steps(Representation::Raw, None, 10), Some(10)); + assert_eq!(steps(Representation::Reference, None, 10), Some(0)); + assert_eq!(steps(Representation::Ncm, Some(ncm::FULL), 10), Some(1920)); + assert_eq!( + steps(Representation::NcmX86, Some(ncm::FULL), 10), + Some(10 * MAX_STEPS_PER_BYTE) + ); + for profile in [ncm::V03, ncm::FULL, 1, 0x7ffff] { + assert!(inputs(profile) <= MAX_INPUTS); + } + } + + #[test] + fn a_codec_point_is_named_by_all_its_coordinates() { + let p = CodecPoint { + basis: [1; 32], + profile: ncm::FULL, + state: [0; 32], + lanes: 1, + }; + assert_ne!(p.kappa(), CodecPoint { lanes: 2, ..p }.kappa()); + assert_ne!( + p.kappa(), + CodecPoint { + state: [2; 32], + ..p + } + .kappa() + ); + assert_ne!( + p.kappa(), + CodecPoint { + profile: ncm::V03, + ..p + } + .kappa() + ); + assert_ne!( + p.kappa(), + CodecPoint { + profile: ncm::FULL | POINT_X86, + ..p + } + .kappa() + ); + assert_eq!(p.kappa(), p.kappa()); + } +} diff --git a/crates/uorc/tests/performance.rs b/crates/uorc/tests/performance.rs new file mode 100644 index 00000000..794acacc --- /dev/null +++ b/crates/uorc/tests/performance.rs @@ -0,0 +1,356 @@ +//! UC-PERF-02..06: the native client keeps the rules the Prism model +//! `Uorc.Performance` proves. The theorems are kernel-checked by +//! `lexlean verify`; this test holds the native constants equal to the +//! model's, the theorem inventory complete, and the native frames within the +//! bounds the theorems state for the model. One test per registered row. + +use std::collections::BTreeMap; +use std::path::PathBuf; +use uorc::archive::{self, Codec}; +use uorc::{ncm, performance, portfolio, x86, Representation}; + +fn module() -> String { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../src/Uorc/Performance.lex.tex"); + std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())) +} + +fn field<'a>(decl: &'a str, key: &str) -> Option<&'a str> { + let at = decl.find(&format!("{key}: "))? + key.len() + 2; + let rest = &decl[at..]; + let end = rest.find([',', '}', '\n']).unwrap_or(rest.len()); + Some(rest[..end].trim()) +} + +/// Every parameterless `Nat` definition whose body is a literal. +fn constants(source: &str) -> BTreeMap { + let mut out = BTreeMap::new(); + for decl in source.split("definition{").skip(1) { + let decl = decl.split("\n\n").next().unwrap_or(decl); + let (Some(name), Some(result), Some(body)) = ( + field(decl, "name"), + field(decl, "result"), + field(decl, "body"), + ) else { + continue; + }; + if decl.contains("parameters: [],") && result == "Nat" { + if let Ok(v) = body.parse() { + out.insert(name.to_string(), v); + } + } + } + out +} + +/// Deterministic bytes no model predicts (xorshift64). +fn noise(n: usize, mut s: u64) -> Vec { + (0..n) + .map(|_| { + s ^= s << 13; + s ^= s >> 7; + s ^= s << 17; + (s >> 24) as u8 + }) + .collect() +} + +fn text(n: usize) -> Vec { + module().into_bytes().into_iter().cycle().take(n).collect() +} + +/// Frames of several lengths and kinds: empty, tiny, text, noise, mixed. +fn samples() -> Vec> { + let mut mixed = text(6000); + mixed.extend(noise(6000, 7)); + vec![ + Vec::new(), + vec![0], + noise(127, 1), + noise(128, 2), + noise(5000, 3), + noise(20_000, 4), + text(300), + text(20_000), + vec![0xe8; 9000], + mixed, + ] +} + +/// The frame a scheduled strategy writes for `frame` on its own. +fn strategy_frame(frame: &[u8], strategy: portfolio::Strategy) -> Option> { + let data = if strategy.x86 { + x86::filter(frame, false, 0).0 + } else { + frame.to_vec() + }; + let codec = if strategy.x86 { + Codec::NcmX86 + } else { + Codec::Ncm + }; + let payload = ncm::encode_profile(&[], &data, strategy.profile)?; + archive::linked_archive_profile(codec, strategy.profile, &[frame.len() as u64], &payload) +} + +fn proved(names: &[&str]) { + let source = module(); + let have: Vec<&str> = source + .split("theorem{") + .skip(1) + .filter_map(|decl| field(decl, "name")) + .collect(); + for name in names { + assert!(have.contains(name), "theorem {name}"); + } +} + +#[test] +fn no_native_frame_exceeds_its_input_plus_the_models_overhead_uc_perf_02() { + proved(&[ + "ulebLengthBound", + "rawLengthBound", + "settleNoLargerThanRaw", + "settleNoLargerThanKernel", + "archiveBound", + ]); + let c = constants(&module()); + let native = [ + ("ulebLimit", archive::uleb_len(u64::MAX) as u64), + ("rawFixed", archive::raw_length(&[0]) - 2), + ( + "rawOverhead", + archive::raw_length(&[0]) - 2 + 2 * archive::uleb_len(u64::MAX) as u64, + ), + ]; + for (name, value) in native { + assert_eq!(c.get(name), Some(&value), "{name}"); + } + for frame in samples() { + let n = frame.len() as u64; + // rawLength n = 2 * ulebLength n + n + rawFixed + let raw = archive::raw_archive(&frame); + assert_eq!( + raw.len() as u64, + 2 * archive::uleb_len(n) as u64 + n + c["rawFixed"] + ); + assert_eq!(raw.len() as u64, archive::raw_length(&[n])); + // archiveBound: settled against the raw frame, within n + rawOverhead + let kept = uorc::compress_frame(&frame, 0).unwrap(); + assert!(kept.len() <= raw.len(), "{n}: larger than raw"); + assert!(kept.len() as u64 <= n + c["rawOverhead"], "{n}"); + } +} + +#[test] +fn the_native_portfolio_frame_is_no_larger_than_any_scheduled_strategys_uc_perf_03() { + proved(&[ + "keepStaysNoLarger", + "keepNoLargerThanHead", + "keepNoLargerThanKept", + "bestNoLargerThanEvery", + ]); + for frame in samples() { + let kept = uorc::compress_frame(&frame, 0).unwrap(); + for strategy in portfolio::plan(&frame) { + if let Some(alone) = strategy_frame(&frame, strategy) { + assert!(kept.len() <= alone.len(), "{}: {strategy:?}", frame.len()); + } + } + } +} + +#[test] +fn native_decode_steps_are_the_models_and_within_its_bound_uc_perf_04() { + proved(&[ + "countBitsBound", + "contextsBound", + "inputsBound", + "inputsFloor", + "frameStepsBound", + "decodeStepsBound", + "fullModelSteps", + "releasedModelSteps", + ]); + let c = constants(&module()); + let native = [ + ("bitsPerByte", performance::BITS_PER_BYTE), + ("contextBits", performance::CONTEXT_BITS.into()), + ("fixedInputs", performance::FIXED_INPUTS.into()), + ("featureInputs", performance::FEATURE_INPUTS.into()), + ("maxInputs", performance::MAX_INPUTS.into()), + ("maxStepsPerByte", performance::MAX_STEPS_PER_BYTE), + ]; + for (name, value) in native { + assert_eq!(c.get(name), Some(&value), "{name}"); + } + // the closed vectors the model proves: fullModelSteps, releasedModelSteps + let steps = |profile| performance::steps(Representation::Ncm, Some(profile), 10); + assert_eq!(steps(ncm::FULL), Some(1920)); + assert_eq!(steps(ncm::V03), Some(1600)); + // inputsFloor, inputsBound for every strategy and single-bit profile + let profiles = portfolio::STRATEGIES + .iter() + .map(|s| s.profile) + .chain((0..20).map(|b| 1 << b)) + .chain([0]); + for profile in profiles { + let inputs = performance::inputs(profile); + assert!((performance::FIXED_INPUTS..=performance::MAX_INPUTS).contains(&inputs)); + } + // decodeStepsBound on the frames the client writes + for frame in samples() { + let kept = uorc::compress_frame(&frame, 0).unwrap(); + let info = uorc::inspect(&kept).unwrap(); + let steps = performance::frame_steps(&info).expect("a measured representation"); + assert!(steps <= c["maxStepsPerByte"] * frame.len() as u64); + } +} + +#[test] +fn a_frame_coded_at_any_point_decodes_to_its_input_uc_perf_05() { + proved(&[ + "admittedIsExact", + "keepPreservesExact", + "bestOfAdmittedIsExact", + ]); + for frame in samples() { + // every strategy of the portfolio, scheduled for this frame or not + for strategy in portfolio::STRATEGIES { + if let Some(alone) = strategy_frame(&frame, strategy) { + assert_eq!(uorc::decompress_frame(&alone, u64::MAX).unwrap(), frame); + // the point is read from the header alone + let info = uorc::inspect(&alone).unwrap(); + let point = performance::CodecPoint::of(&info); + assert_eq!(point.profile & performance::POINT_X86 != 0, strategy.x86); + } + } + let kept = uorc::compress_frame(&frame, 0).unwrap(); + assert_eq!(uorc::decompress_frame(&kept, u64::MAX).unwrap(), frame); + } +} + +#[test] +fn the_model_proves_dominance_is_a_strict_order_uc_perf_06() { + proved(&[ + "dominanceLowersCost", + "dominanceIsIrreflexive", + "dominanceIsTransitive", + "dominanceNeverGrows", + ]); +} + +/// Every pair of small keys, and `None` for a failed trial. +fn small_trials() -> Vec> { + let mut out = vec![None]; + for bytes in 0..5 { + for steps in 0..5 { + out.push(Some(performance::Trial { bytes, steps })); + } + } + out +} + +#[test] +fn a_bounded_trial_is_the_unbounded_one_or_cannot_win_uc_perf_07() { + proved(&[ + "boundedSettlesTheSame", + "settleOfKeep", + "boundedPortfolioSettlesTheSame", + "skippedTrialKeepsBytes", + "skippedTrialKeepsSteps", + ]); + for frame in samples() { + let raw = archive::raw_length(&[frame.len() as u64]); + for strategy in portfolio::plan(&frame) { + let Some(full) = ncm::encode_profile(&[], &frame, strategy.profile) else { + continue; + }; + // abandoned at any bound: the same payload, or none once the + // payload reaches the bound + for stop in [0, 1, full.len() / 2, full.len(), full.len() + 1, usize::MAX] { + match ncm::encode_below(&[], &frame, strategy.profile, stop) { + Some(payload) => assert_eq!(payload, full), + None => assert!(full.len() >= stop, "{}: {stop}", frame.len()), + } + } + } + // settled against the raw frame, the bounded portfolio writes what an + // unbounded one settles to: no scheduled frame below raw is lost + let kept = uorc::compress_frame(&frame, 0).unwrap(); + let least = portfolio::plan(&frame) + .into_iter() + .filter_map(|s| strategy_frame(&frame, s)) + .map(|a| a.len() as u64) + .fold(raw, u64::min); + assert!(kept.len() as u64 <= least); + } +} + +#[test] +fn the_chosen_trial_is_least_and_undominated_uc_perf_08() { + proved(&[ + "pickIsLeastOfKept", + "pickIsLeastOfHead", + "pickBytesAreSettled", + "pickStaysLeast", + "chosenIsLeast", + "pickStaysUnderRaw", + "chosenIsNoWorseThanRaw", + "chosenKeepsTheSize", + "leastIsUndominated", + "excludedTrialKeepsBytes", + "excludedTrialKeepsSteps", + ]); + let trials = small_trials(); + let raw = performance::Trial { bytes: 3, steps: 3 }; + // every list of three trials over the small keys + for a in &trials { + for b in &trials { + for c in &trials { + let list = [*a, *b, *c]; + let kept = performance::chosen(raw, &list); + assert_eq!(performance::lex_gap(kept, raw), 0); + // chosenKeepsTheSize: the bytes the size rule alone settles to + let least = list + .iter() + .flatten() + .map(|t| t.bytes) + .fold(raw.bytes, u64::min); + assert_eq!(kept.bytes, least); + for t in list.iter().flatten().chain([&raw]) { + assert_eq!(performance::lex_gap(kept, *t), 0, "{list:?}"); + assert_eq!(performance::gain(*t, kept), 0, "{list:?}"); + // an excluded trial (no earlier than the kept one) changes nothing + assert_eq!(performance::pick(Some(*t), kept), kept); + } + } + } + } +} + +#[test] +fn a_consolidation_spends_exactly_its_gain_uc_perf_09() { + proved(&[ + "consolidationSpendsItsGain", + "consolidationStaysUnder", + "potentialNeverRises", + ]); + let trials: Vec<_> = small_trials().into_iter().flatten().collect(); + for &incumbent in &trials { + for &candidate in &trials { + let next = performance::consolidate(candidate, incumbent); + let gain = performance::gain(candidate, incumbent); + assert_eq!(next.cost() + gain, incumbent.cost()); + assert!(next.bytes <= incumbent.bytes && next.steps <= incumbent.steps); + assert_eq!(gain > 0, next != incumbent); + } + // any sequence of candidates: the potential never rises + let mut shipped = incumbent; + for &candidate in trials.iter().rev() { + let before = shipped.cost(); + shipped = performance::consolidate(candidate, shipped); + assert!(shipped.cost() <= before); + } + assert!(shipped.cost() <= incumbent.cost()); + } +} diff --git a/features/suites/performance-theorems.feature b/features/suites/performance-theorems.feature new file mode 100644 index 00000000..1c602ca6 --- /dev/null +++ b/features/suites/performance-theorems.feature @@ -0,0 +1,50 @@ +# @generated from src/Uorc/Registry.lex.tex by `cargo xtask check-model --write`. +Feature: performance-theorems + + @UC-PERF-02 @build + Scenario: For every input length n, the settled frame of Uorc.Performance is no larger than the raw frame and no larger than a coded kernel candidate, and the raw frame is two length varints of at most 10 bytes each, the n input bytes and 41 fixed bytes, so no frame of one object exceeds n + 61 bytes (archiveBound), and a stream of k such frames is within n + 61 * k bytes; the native client keeps the same rule and the same constants. + Given the Uorc.Performance module and the native client's frame writer + When the locked SDK verifies the module and the native test compresses inputs of several lengths and kinds, including incompressible ones + Then archiveBound and its lemmas are kernel-checked, every native raw frame has the model's length, and every native frame is within n + 61 bytes + + @UC-PERF-03 @build + Scenario: For every list of trials, the trial the portfolio keeps (Uorc.Performance best) is no larger in bytes than any coded trial in the list (bestNoLargerThanEvery), so a portfolio archive is no larger than the archive of any strategy it scheduled. + Given the Uorc.Performance module and the native client's strategy portfolio + When the locked SDK verifies the module and the native test codes sample frames under each scheduled strategy and under the portfolio + Then bestNoLargerThanEvery is kernel-checked and the native portfolio frame is no larger than the frame of every strategy it scheduled + + @UC-PERF-04 @build + Scenario: A step is one model input evaluated for one coded bit. For every profile word the input count lies between 3 and 24 (17 context bits, 3 fixed inputs, 2 for each of the short-match and repeat features), a frame of n bytes costs 8 * n * inputs steps, and for every frame kind (raw, reference, ncm, ncm from a named state) decode takes at most 192 steps per modelled byte (decodeStepsBound); the full profile costs 192 steps per byte and the v0.3 profile 160. The measure counts model inputs, not machine time. + Given the Uorc.Performance module and the native step measure in uorc::performance + When the locked SDK verifies the module and the native test compares the native measure with the model's constants and closed vectors for sample profiles + Then the step bound theorems are kernel-checked, every native constant equals the model's, and the native step count of every sampled frame is within 192 steps per byte + + @UC-PERF-05 @build + Scenario: A trial carries its defect, the count of bytes at which its decode differs from the input. Admission fails every trial with a nonzero defect, keeping never raises a defect above its operands', and the trial kept from any admitted list has defect 0 (bestOfAdmittedIsExact): whatever codec point or named model state produced a trial, it can change the archive's size and never its meaning. + Given the Uorc.Performance module and the native client's candidate admission + When the locked SDK verifies the module and the native test decodes every frame it produced under each strategy + Then bestOfAdmittedIsExact and its lemmas are kernel-checked and every native frame decodes to its input + + @UC-PERF-06 @build + Scenario: A candidate dominates an incumbent when it is no larger in bytes and no larger in steps, and its gain is the drop in bytes plus steps. The gain never exceeds the drop in cost (dominanceLowersCost), no trial gains over itself, gains compose (a positive gain of a over b and of b over c gives at least their sum of a over c), and a positive gain implies no growth in bytes or in steps: dominance is a strict partial order, so consolidating winners cannot cycle. + Given the Uorc.Performance module + When the locked SDK verifies the module and the native test reads the module's theorem inventory + Then the four dominance theorems are kernel-checked and present + + @UC-PERF-07 @build + Scenario: A trial abandoned at a bound is modelled as a trial of at most the bound's bytes. For every list of trials and every raw length, the portfolio of trials abandoned at the raw length settles to the same size as the portfolio of complete trials (boundedPortfolioSettlesTheSame), and a trial no smaller than one already kept changes neither the kept bytes nor the kept steps (skippedTrial theorems): a search that stops a candidate once it cannot win, or skips one known to be no smaller, writes an archive of the same size for fewer compress steps. + Given the Uorc.Performance module and the native encoder's bound + When the locked SDK verifies the module and the native test abandons each scheduled strategy at several bounds + Then the bounded search theorems are kernel-checked, a native payload abandoned at a bound is the complete payload or is absent only when the complete payload reaches the bound, and the native frame is no larger than any complete scheduled frame or the raw frame + + @UC-PERF-08 @build + Scenario: Choosing by fewer bytes and then fewer steps, from the raw frame and any list of trials, keeps a trial that is no later in that order than every trial in the list and than the raw frame (chosenIsLeast, chosenIsNoWorseThanRaw), has exactly the size the bytes-only rule settles to (chosenKeepsTheSize), and is dominated by no trial it is no later than (leastIsUndominated); a trial no earlier than the kept one changes nothing (excludedTrial theorems). The rule lowers decode steps on byte ties at no cost in size. The released client breaks byte ties by schedule order until its model export adopts this rule. + Given the Uorc.Performance module and the native choice functions in uorc::performance + When the locked SDK verifies the module and the native test runs the native choice over every list of three small trials + Then the choice theorems are kernel-checked and the native choice is least in bytes then steps, has the bytes-only size, and is dominated by no listed trial + + @UC-PERF-09 @build + Scenario: The potential of a codec point is its bytes plus its steps. Consolidating a candidate into an incumbent lowers the potential by exactly the candidate's gain (consolidationSpendsItsGain), which is positive exactly when the candidate dominates, and over any sequence of candidates the potential never rises (potentialNeverRises). The potential is a natural number, so an engine that consolidates only dominating candidates never regresses and consolidates at most as many times as its first potential. + Given the Uorc.Performance module and the native consolidation in uorc::performance + When the locked SDK verifies the module and the native test consolidates every pair and sequence of small trials + Then the potential theorems are kernel-checked and every native consolidation lowers bytes plus steps by exactly its gain diff --git a/model/ids.toml b/model/ids.toml index 10eea1b3..0201e018 100644 --- a/model/ids.toml +++ b/model/ids.toml @@ -176,3 +176,51 @@ id = "UC-WEB-01" level = "build" suite = "pages-client" statement = "The Pages client is generated from and conforms to its Prism product model in Uorc.Page: stakeholders, features with their calls and acceptance cases, journeys, the page's UML state machine, operations, fields, controls, examples, error hints, sections, usage, links and quality measures. The generated page holds exactly the modeled elements, and a real browser walks every journey, takes every modeled transition, checks every control's enabled state in every state it reaches and holds every gated quality measure." + +[[id]] +id = "UC-PERF-02" +level = "build" +suite = "performance-theorems" +statement = "For every input length n, the settled frame of Uorc.Performance is no larger than the raw frame and no larger than a coded kernel candidate, and the raw frame is two length varints of at most 10 bytes each, the n input bytes and 41 fixed bytes, so no frame of one object exceeds n + 61 bytes (archiveBound), and a stream of k such frames is within n + 61 * k bytes; the native client keeps the same rule and the same constants." + +[[id]] +id = "UC-PERF-03" +level = "build" +suite = "performance-theorems" +statement = "For every list of trials, the trial the portfolio keeps (Uorc.Performance best) is no larger in bytes than any coded trial in the list (bestNoLargerThanEvery), so a portfolio archive is no larger than the archive of any strategy it scheduled." + +[[id]] +id = "UC-PERF-04" +level = "build" +suite = "performance-theorems" +statement = "A step is one model input evaluated for one coded bit. For every profile word the input count lies between 3 and 24 (17 context bits, 3 fixed inputs, 2 for each of the short-match and repeat features), a frame of n bytes costs 8 * n * inputs steps, and for every frame kind (raw, reference, ncm, ncm from a named state) decode takes at most 192 steps per modelled byte (decodeStepsBound); the full profile costs 192 steps per byte and the v0.3 profile 160. The measure counts model inputs, not machine time." + +[[id]] +id = "UC-PERF-05" +level = "build" +suite = "performance-theorems" +statement = "A trial carries its defect, the count of bytes at which its decode differs from the input. Admission fails every trial with a nonzero defect, keeping never raises a defect above its operands', and the trial kept from any admitted list has defect 0 (bestOfAdmittedIsExact): whatever codec point or named model state produced a trial, it can change the archive's size and never its meaning." + +[[id]] +id = "UC-PERF-06" +level = "build" +suite = "performance-theorems" +statement = "A candidate dominates an incumbent when it is no larger in bytes and no larger in steps, and its gain is the drop in bytes plus steps. The gain never exceeds the drop in cost (dominanceLowersCost), no trial gains over itself, gains compose (a positive gain of a over b and of b over c gives at least their sum of a over c), and a positive gain implies no growth in bytes or in steps: dominance is a strict partial order, so consolidating winners cannot cycle." + +[[id]] +id = "UC-PERF-07" +level = "build" +suite = "performance-theorems" +statement = "A trial abandoned at a bound is modelled as a trial of at most the bound's bytes. For every list of trials and every raw length, the portfolio of trials abandoned at the raw length settles to the same size as the portfolio of complete trials (boundedPortfolioSettlesTheSame), and a trial no smaller than one already kept changes neither the kept bytes nor the kept steps (skippedTrial theorems): a search that stops a candidate once it cannot win, or skips one known to be no smaller, writes an archive of the same size for fewer compress steps." + +[[id]] +id = "UC-PERF-08" +level = "build" +suite = "performance-theorems" +statement = "Choosing by fewer bytes and then fewer steps, from the raw frame and any list of trials, keeps a trial that is no later in that order than every trial in the list and than the raw frame (chosenIsLeast, chosenIsNoWorseThanRaw), has exactly the size the bytes-only rule settles to (chosenKeepsTheSize), and is dominated by no trial it is no later than (leastIsUndominated); a trial no earlier than the kept one changes nothing (excludedTrial theorems). The rule lowers decode steps on byte ties at no cost in size. The released client breaks byte ties by schedule order until its model export adopts this rule." + +[[id]] +id = "UC-PERF-09" +level = "build" +suite = "performance-theorems" +statement = "The potential of a codec point is its bytes plus its steps. Consolidating a candidate into an incumbent lowers the potential by exactly the candidate's gain (consolidationSpendsItsGain), which is positive exactly when the candidate dominates, and over any sequence of candidates the potential never rises (potentialNeverRises). The potential is a natural number, so an engine that consolidates only dominating candidates never regresses and consolidates at most as many times as its first potential." diff --git a/model/ledger.toml b/model/ledger.toml index df968db3..30df847c 100644 --- a/model/ledger.toml +++ b/model/ledger.toml @@ -236,3 +236,67 @@ statement = "The Pages client is generated from and conforms to its Prism produc evidence_kind = "build_evidence" research_disposition = "not_measured" feature = "features/suites/pages-client.feature" + +[[claim]] +id = "UC-PERF-02" +level = "build" +statement = "For every input length n, the settled frame of Uorc.Performance is no larger than the raw frame and no larger than a coded kernel candidate, and the raw frame is two length varints of at most 10 bytes each, the n input bytes and 41 fixed bytes, so no frame of one object exceeds n + 61 bytes (archiveBound), and a stream of k such frames is within n + 61 * k bytes; the native client keeps the same rule and the same constants." +evidence_kind = "kernel_theorem" +research_disposition = "not_measured" +feature = "features/suites/performance-theorems.feature" + +[[claim]] +id = "UC-PERF-03" +level = "build" +statement = "For every list of trials, the trial the portfolio keeps (Uorc.Performance best) is no larger in bytes than any coded trial in the list (bestNoLargerThanEvery), so a portfolio archive is no larger than the archive of any strategy it scheduled." +evidence_kind = "kernel_theorem" +research_disposition = "not_measured" +feature = "features/suites/performance-theorems.feature" + +[[claim]] +id = "UC-PERF-04" +level = "build" +statement = "A step is one model input evaluated for one coded bit. For every profile word the input count lies between 3 and 24 (17 context bits, 3 fixed inputs, 2 for each of the short-match and repeat features), a frame of n bytes costs 8 * n * inputs steps, and for every frame kind (raw, reference, ncm, ncm from a named state) decode takes at most 192 steps per modelled byte (decodeStepsBound); the full profile costs 192 steps per byte and the v0.3 profile 160. The measure counts model inputs, not machine time." +evidence_kind = "kernel_theorem" +research_disposition = "not_measured" +feature = "features/suites/performance-theorems.feature" + +[[claim]] +id = "UC-PERF-05" +level = "build" +statement = "A trial carries its defect, the count of bytes at which its decode differs from the input. Admission fails every trial with a nonzero defect, keeping never raises a defect above its operands', and the trial kept from any admitted list has defect 0 (bestOfAdmittedIsExact): whatever codec point or named model state produced a trial, it can change the archive's size and never its meaning." +evidence_kind = "kernel_theorem" +research_disposition = "not_measured" +feature = "features/suites/performance-theorems.feature" + +[[claim]] +id = "UC-PERF-06" +level = "build" +statement = "A candidate dominates an incumbent when it is no larger in bytes and no larger in steps, and its gain is the drop in bytes plus steps. The gain never exceeds the drop in cost (dominanceLowersCost), no trial gains over itself, gains compose (a positive gain of a over b and of b over c gives at least their sum of a over c), and a positive gain implies no growth in bytes or in steps: dominance is a strict partial order, so consolidating winners cannot cycle." +evidence_kind = "kernel_theorem" +research_disposition = "not_measured" +feature = "features/suites/performance-theorems.feature" + +[[claim]] +id = "UC-PERF-07" +level = "build" +statement = "A trial abandoned at a bound is modelled as a trial of at most the bound's bytes. For every list of trials and every raw length, the portfolio of trials abandoned at the raw length settles to the same size as the portfolio of complete trials (boundedPortfolioSettlesTheSame), and a trial no smaller than one already kept changes neither the kept bytes nor the kept steps (skippedTrial theorems): a search that stops a candidate once it cannot win, or skips one known to be no smaller, writes an archive of the same size for fewer compress steps." +evidence_kind = "kernel_theorem" +research_disposition = "not_measured" +feature = "features/suites/performance-theorems.feature" + +[[claim]] +id = "UC-PERF-08" +level = "build" +statement = "Choosing by fewer bytes and then fewer steps, from the raw frame and any list of trials, keeps a trial that is no later in that order than every trial in the list and than the raw frame (chosenIsLeast, chosenIsNoWorseThanRaw), has exactly the size the bytes-only rule settles to (chosenKeepsTheSize), and is dominated by no trial it is no later than (leastIsUndominated); a trial no earlier than the kept one changes nothing (excludedTrial theorems). The rule lowers decode steps on byte ties at no cost in size. The released client breaks byte ties by schedule order until its model export adopts this rule." +evidence_kind = "kernel_theorem" +research_disposition = "not_measured" +feature = "features/suites/performance-theorems.feature" + +[[claim]] +id = "UC-PERF-09" +level = "build" +statement = "The potential of a codec point is its bytes plus its steps. Consolidating a candidate into an incumbent lowers the potential by exactly the candidate's gain (consolidationSpendsItsGain), which is positive exactly when the candidate dominates, and over any sequence of candidates the potential never rises (potentialNeverRises). The potential is a natural number, so an engine that consolidates only dominating candidates never regresses and consolidates at most as many times as its first potential." +evidence_kind = "kernel_theorem" +research_disposition = "not_measured" +feature = "features/suites/performance-theorems.feature" diff --git a/src/Uorc/Performance.lex.tex b/src/Uorc/Performance.lex.tex new file mode 100644 index 00000000..5cd973fb --- /dev/null +++ b/src/Uorc/Performance.lex.tex @@ -0,0 +1,1488 @@ +\begin{lexlean}{Uorc.Performance} +\title{Parameters} +\begin{semanticmodule} +definition{name: bitsPerByte, parameters: [], result: Nat, body: 8} + +definition{name: contextBits, parameters: [], result: Nat, body: 17} + +definition{name: fixedInputs, parameters: [], result: Nat, body: 3} + +definition{name: featureInputs, parameters: [], result: Nat, body: 2} + +definition{name: maxInputs, parameters: [], result: Nat, body: 24} + +definition{name: maxStepsPerByte, parameters: [], result: Nat, body: 192} + +definition{name: ulebLimit, parameters: [], result: Nat, body: 10} + +definition{name: rawFixed, parameters: [], result: Nat, body: 41} + +definition{name: rawOverhead, parameters: [], result: Nat, body: 61} + +inductive{ + name: Trial, + type_parameters: [], + parameters: [], + constructors: [{name: failed, fields: []}, {name: coded, fields: [Nat, Nat, Nat]}] +} + +definition{ + name: keep, + parameters: [left : Trial, right : Trial], + result: Trial, + body: (match left + | Trial.failed => right + | Trial.coded lb ls ld => (match right + | Trial.failed => left + | Trial.coded rb rs rd => (ctor Trial.coded (prim subtract lb (prim subtract lb rb : Nat) : Nat) (if (rb (ctor Trial.failed) + | List.cons head tail => (keep head (best tail))), + recursive_argument: trials +} + +definition{ + name: weight, + parameters: [trial : Trial], + result: Nat, + body: (match trial | Trial.failed => 0 | Trial.coded b s d => (b + 1)) +} + +definition{ + name: excess, + parameters: [kept : Nat, candidate : Trial], + result: Nat, + body: (match candidate + | Trial.failed => 0 + | Trial.coded b s d => ((prim subtract 1 kept : Nat) + (prim subtract kept (b + 1) : Nat))) +} + +definition{ + name: exceed, + parameters: [kept : Nat, trials : (List Trial)], + result: Nat, + body: (match trials + | List.nil => 0 + | List.cons head tail => ((excess kept head) + (exceed kept tail))), + recursive_argument: trials +} + +theorem{ + name: keepStaysNoLarger, + parameters: [trials : (List Trial), head : Trial, kept : Trial], + statement: (((exceed (weight kept) trials) = 0) -> ((exceed (weight (keep head kept)) trials) = 0)), + proof: cases{ + branches: [ + { + proof: cases{ + branches: [ + { + proof: induction{ + branches: [ + { + proof: linear_arithmetic{definitions: [exceed, excess, keep, weight]}, + binders: [], + constructor: nil + }, + { + proof: cases{ + branches: [ + { + proof: linear_arithmetic{definitions: [exceed, excess, keep, weight]}, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{definitions: [exceed, excess, keep, weight]}, + binders: [xB, xS, xD], + constructor: coded + } + ], + scrutinee: x + }, + binders: [x, others, ih], + constructor: cons + } + ], + scrutinee: trials + }, + binders: [], + constructor: failed + }, + { + proof: induction{ + branches: [ + { + proof: linear_arithmetic{definitions: [exceed, excess, keep, weight]}, + binders: [], + constructor: nil + }, + { + proof: cases{ + branches: [ + { + proof: linear_arithmetic{definitions: [exceed, excess, keep, weight]}, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{definitions: [exceed, excess, keep, weight]}, + binders: [xB, xS, xD], + constructor: coded + } + ], + scrutinee: x + }, + binders: [x, others, ih], + constructor: cons + } + ], + scrutinee: trials + }, + binders: [keptB, keptS, keptD], + constructor: coded + } + ], + scrutinee: kept + }, + binders: [], + constructor: failed + }, + { + proof: cases{ + branches: [ + { + proof: induction{ + branches: [ + { + proof: linear_arithmetic{definitions: [exceed, excess, keep, weight]}, + binders: [], + constructor: nil + }, + { + proof: cases{ + branches: [ + { + proof: linear_arithmetic{definitions: [exceed, excess, keep, weight]}, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{definitions: [exceed, excess, keep, weight]}, + binders: [xB, xS, xD], + constructor: coded + } + ], + scrutinee: x + }, + binders: [x, others, ih], + constructor: cons + } + ], + scrutinee: trials + }, + binders: [], + constructor: failed + }, + { + proof: induction{ + branches: [ + { + proof: linear_arithmetic{definitions: [exceed, excess, keep, weight]}, + binders: [], + constructor: nil + }, + { + proof: cases{ + branches: [ + { + proof: linear_arithmetic{definitions: [exceed, excess, keep, weight]}, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{definitions: [exceed, excess, keep, weight]}, + binders: [xB, xS, xD], + constructor: coded + } + ], + scrutinee: x + }, + binders: [x, others, ih], + constructor: cons + } + ], + scrutinee: trials + }, + binders: [keptB, keptS, keptD], + constructor: coded + } + ], + scrutinee: kept + }, + binders: [headB, headS, headD], + constructor: coded + } + ], + scrutinee: head + }, + axioms: [Classical.choice, Quot.sound, propext] +} + +theorem{ + name: keepNoLargerThanHead, + parameters: [head : Trial, kept : Trial], + statement: ((excess (weight (keep head kept)) head) = 0), + proof: cases{ + branches: [ + { + proof: cases{ + branches: [ + { + proof: linear_arithmetic{definitions: [excess, keep, weight]}, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{definitions: [excess, keep, weight]}, + binders: [keptB, keptS, keptD], + constructor: coded + } + ], + scrutinee: kept + }, + binders: [], + constructor: failed + }, + { + proof: cases{ + branches: [ + { + proof: linear_arithmetic{definitions: [excess, keep, weight]}, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{definitions: [excess, keep, weight]}, + binders: [keptB, keptS, keptD], + constructor: coded + } + ], + scrutinee: kept + }, + binders: [headB, headS, headD], + constructor: coded + } + ], + scrutinee: head + }, + axioms: [Quot.sound, propext] +} + +theorem{ + name: keepNoLargerThanKept, + parameters: [head : Trial, kept : Trial], + statement: ((excess (weight (keep head kept)) kept) = 0), + proof: cases{ + branches: [ + { + proof: cases{ + branches: [ + { + proof: linear_arithmetic{definitions: [excess, keep, weight]}, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{definitions: [excess, keep, weight]}, + binders: [keptB, keptS, keptD], + constructor: coded + } + ], + scrutinee: kept + }, + binders: [], + constructor: failed + }, + { + proof: cases{ + branches: [ + { + proof: linear_arithmetic{definitions: [excess, keep, weight]}, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{definitions: [excess, keep, weight]}, + binders: [keptB, keptS, keptD], + constructor: coded + } + ], + scrutinee: kept + }, + binders: [headB, headS, headD], + constructor: coded + } + ], + scrutinee: head + }, + axioms: [Quot.sound, propext] +} + +theorem{ + name: bestNoLargerThanEvery, + parameters: [trials : (List Trial)], + statement: ((exceed (weight (best trials)) trials) = 0), + proof: induction{ + branches: [ + {proof: reflexivity{}, binders: [], constructor: nil}, + { + proof: simplify{definitions: [best, exceed, ih, keepNoLargerThanHead, keepStaysNoLarger]}, + binders: [x, others, ih], + constructor: cons + } + ], + scrutinee: trials + }, + axioms: [Classical.choice, Quot.sound, propext] +} + +definition{ + name: defect, + parameters: [trial : Trial], + result: Nat, + body: (match trial | Trial.failed => 0 | Trial.coded b s d => d) +} + +definition{ + name: admitted, + parameters: [trial : Trial], + result: Trial, + body: (match trial + | Trial.failed => (ctor Trial.failed) + | Trial.coded b s d => (match d + | Nat.zero => (ctor Trial.coded b s 0) + | Nat.succ k => (ctor Trial.failed))) +} + +definition{ + name: admitAll, + parameters: [trials : (List Trial)], + result: (List Trial), + body: (match trials + | List.nil => (nil Trial) + | List.cons head tail => (cons (admitted head) (admitAll tail))), + recursive_argument: trials +} + +theorem{ + name: admittedIsExact, + parameters: [trial : Trial], + statement: ((defect (admitted trial)) = 0), + proof: cases{ + branches: [ + {proof: reflexivity{}, binders: [], constructor: failed}, + { + proof: cases{ + branches: [ + {proof: reflexivity{}, binders: [], constructor: zero}, + {proof: reflexivity{}, binders: [k], constructor: succ} + ], + scrutinee: d + }, + binders: [b, s, d], + constructor: coded + } + ], + scrutinee: trial + } +} + +theorem{ + name: keepPreservesExact, + parameters: [left : Trial, right : Trial], + statement: (((defect left) = 0) -> (((defect right) = 0) -> ((defect (keep left right)) = 0))), + proof: cases{ + branches: [ + { + proof: cases{ + branches: [ + { + proof: linear_arithmetic{definitions: [defect, keep]}, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{definitions: [defect, keep]}, + binders: [rightB, rightS, rightD], + constructor: coded + } + ], + scrutinee: right + }, + binders: [], + constructor: failed + }, + { + proof: cases{ + branches: [ + { + proof: linear_arithmetic{definitions: [defect, keep]}, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{definitions: [defect, keep]}, + binders: [rightB, rightS, rightD], + constructor: coded + } + ], + scrutinee: right + }, + binders: [leftB, leftS, leftD], + constructor: coded + } + ], + scrutinee: left + }, + axioms: [Quot.sound, propext] +} + +theorem{ + name: bestOfAdmittedIsExact, + parameters: [trials : (List Trial)], + statement: ((defect (best (admitAll trials))) = 0), + proof: induction{ + branches: [ + {proof: reflexivity{}, binders: [], constructor: nil}, + { + proof: simplify{definitions: [admitAll, admittedIsExact, best, ih, keepPreservesExact]}, + binders: [x, others, ih], + constructor: cons + } + ], + scrutinee: trials + }, + axioms: [Quot.sound, propext] +} + +definition{ + name: ulebLength, + parameters: [n : Nat], + result: Nat, + body: (if (n raw + | Trial.coded b s d => (prim subtract b (prim subtract b raw : Nat) : Nat)) +} + +theorem{ + name: ulebLengthBound, + parameters: [n : Nat], + statement: ((ulebLength n) <= (ulebLimit)), + proof: linear_arithmetic{definitions: [ulebLength, ulebLimit]}, + axioms: [Quot.sound, propext] +} + +theorem{ + name: rawLengthBound, + parameters: [n : Nat], + statement: ((rawLength n) <= (n + (rawOverhead))), + proof: linear_arithmetic{definitions: [rawFixed, rawLength, rawOverhead, ulebLength]}, + axioms: [Quot.sound, propext] +} + +theorem{ + name: settleNoLargerThanRaw, + parameters: [kernel : Trial, raw : Nat], + statement: ((settle kernel raw) <= raw), + proof: cases{ + branches: [ + {proof: linear_arithmetic{definitions: [settle]}, binders: [], constructor: failed}, + {proof: linear_arithmetic{definitions: [settle]}, binders: [b, s, d], constructor: coded} + ], + scrutinee: kernel + }, + axioms: [Quot.sound, propext] +} + +theorem{ + name: settleNoLargerThanKernel, + parameters: [b : Nat, s : Nat, d : Nat, raw : Nat], + statement: ((settle (ctor Trial.coded b s d) raw) <= b), + proof: linear_arithmetic{definitions: [settle]}, + axioms: [Quot.sound, propext] +} + +theorem{ + name: archiveBound, + parameters: [kernel : Trial, n : Nat], + statement: ((settle kernel (rawLength n)) <= (n + (rawOverhead))), + proof: cases{ + branches: [ + { + proof: linear_arithmetic{ + definitions: [rawFixed, rawLength, rawOverhead, settle, ulebLength] + }, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{ + definitions: [rawFixed, rawLength, rawOverhead, settle, ulebLength] + }, + binders: [b, s, d], + constructor: coded + } + ], + scrutinee: kernel + }, + axioms: [Quot.sound, propext] +} + +definition{ + name: pow2, + parameters: [k : Nat], + result: Nat, + body: (match k | Nat.zero => 1 | Nat.succ m => (prim multiply 2 (pow2 m) : Nat)), + recursive_argument: k +} + +definition{ + name: countBits, + parameters: [fuel : Nat, word : Nat], + result: Nat, + body: (match fuel + | Nat.zero => 0 + | Nat.succ m => ((prim remainder (prim quotient word (pow2 m) 0 : Nat) 2 0 : Nat) + (countBits m word))), + recursive_argument: fuel +} + +definition{name: contexts, parameters: [profile : Nat], result: Nat, body: (countBits 17 profile)} + +definition{ + name: inputs, + parameters: [profile : Nat], + result: Nat, + body: ((((contexts profile) + (fixedInputs)) + (prim multiply (featureInputs) (prim remainder (prim quotient profile 131072 0 : Nat) 2 0 : Nat) : Nat)) + (prim multiply (featureInputs) (prim remainder (prim quotient profile 262144 0 : Nat) 2 0 : Nat) : Nat)) +} + +definition{ + name: frameSteps, + parameters: [profile : Nat, n : Nat], + result: Nat, + body: (match n + | Nat.zero => 0 + | Nat.succ k => ((frameSteps profile k) + (prim multiply (bitsPerByte) (inputs profile) : Nat))), + recursive_argument: n +} + +theorem{ + name: countBitsBound, + parameters: [fuel : Nat, word : Nat], + statement: ((countBits fuel word) <= fuel), + proof: induction{ + branches: [ + {proof: linear_arithmetic{definitions: [countBits]}, binders: [], constructor: zero}, + {proof: linear_arithmetic{definitions: [countBits]}, binders: [k, ih], constructor: succ} + ], + scrutinee: fuel + }, + axioms: [Quot.sound, propext] +} + +theorem{ + name: contextsBound, + parameters: [profile : Nat], + statement: ((contexts profile) <= 17), + proof: simplify{definitions: [contexts, countBitsBound]}, + axioms: [Quot.sound, propext] +} + +theorem{ + name: inputsUnder, + parameters: [profile : Nat], + statement: (((contexts profile) <= 17) -> ((inputs profile) <= 24)), + proof: linear_arithmetic{definitions: [featureInputs, fixedInputs, inputs, maxInputs]}, + axioms: [Quot.sound, propext] +} + +theorem{ + name: inputsBound, + parameters: [profile : Nat], + statement: ((inputs profile) <= 24), + proof: simplify{definitions: [contextsBound, inputsUnder]}, + axioms: [Quot.sound, propext] +} + +theorem{ + name: inputsFloor, + parameters: [profile : Nat], + statement: (3 <= (inputs profile)), + proof: linear_arithmetic{definitions: [featureInputs, fixedInputs, inputs, maxInputs]}, + axioms: [Quot.sound, propext] +} + +theorem{ + name: frameStepsUnder, + parameters: [profile : Nat, n : Nat], + statement: (((inputs profile) <= 24) -> ((frameSteps profile n) <= (prim multiply 192 n : Nat))), + proof: induction{ + branches: [ + {proof: linear_arithmetic{definitions: [frameSteps]}, binders: [], constructor: zero}, + { + proof: linear_arithmetic{definitions: [bitsPerByte, frameSteps]}, + binders: [k, ih], + constructor: succ + } + ], + scrutinee: n + }, + axioms: [Classical.choice, Quot.sound, propext] +} + +theorem{ + name: frameStepsBound, + parameters: [profile : Nat, n : Nat], + statement: ((frameSteps profile n) <= (prim multiply 192 n : Nat)), + proof: simplify{definitions: [frameStepsUnder, inputsBound]}, + axioms: [Classical.choice, Quot.sound, propext] +} + +inductive{ + name: Frame, + type_parameters: [], + parameters: [], + constructors: [ + {name: raw, fields: []}, + {name: reference, fields: []}, + {name: ncm, fields: [Nat]}, + {name: warm, fields: [Nat, Nat]} + ] +} + +definition{ + name: decodeSteps, + parameters: [frame : Frame, n : Nat], + result: Nat, + body: (match frame + | Frame.raw => n + | Frame.reference => 0 + | Frame.ncm profile => (frameSteps profile n) + | Frame.warm profile state => (frameSteps profile (n + state))) +} + +definition{ + name: modelled, + parameters: [frame : Frame, n : Nat], + result: Nat, + body: (match frame + | Frame.raw => n + | Frame.reference => n + | Frame.ncm profile => n + | Frame.warm profile state => (n + state)) +} + +theorem{ + name: decodeStepsBound, + parameters: [frame : Frame, n : Nat], + statement: ((decodeSteps frame n) <= (prim multiply 192 (modelled frame n) : Nat)), + proof: cases{ + branches: [ + { + proof: linear_arithmetic{definitions: [decodeSteps, modelled]}, + binders: [], + constructor: raw + }, + { + proof: linear_arithmetic{definitions: [decodeSteps, modelled]}, + binders: [], + constructor: reference + }, + { + proof: simplify{definitions: [decodeSteps, frameStepsBound, modelled]}, + binders: [profile], + constructor: ncm + }, + { + proof: simplify{definitions: [decodeSteps, frameStepsBound, modelled]}, + binders: [profile, state], + constructor: warm + } + ], + scrutinee: frame + }, + axioms: [Classical.choice, Quot.sound, propext] +} + +theorem{ + name: fullModelSteps, + parameters: [], + statement: ((frameSteps 1048575 10) = 1920), + proof: reflexivity{} +} + +theorem{ + name: releasedModelSteps, + parameters: [], + statement: ((frameSteps 131071 10) = 1600), + proof: reflexivity{} +} + +definition{ + name: cost, + parameters: [trial : Trial], + result: Nat, + body: (match trial | Trial.failed => 0 | Trial.coded b s d => (b + s)) +} + +definition{ + name: gainOf, + parameters: [cb : Nat, cs : Nat, ib : Nat, it : Nat], + result: Nat, + body: (if ((cb <=? ib) && (cs <=? it)) then (prim subtract (ib + it) (cb + cs) : Nat) else 0) +} + +definition{ + name: gain, + parameters: [candidate : Trial, incumbent : Trial], + result: Nat, + body: (match candidate + | Trial.failed => 0 + | Trial.coded cb cs cd => (match incumbent + | Trial.failed => 0 + | Trial.coded ib it ix => (gainOf cb cs ib it))) +} + +theorem{ + name: dominanceLowersCost, + parameters: [candidate : Trial, incumbent : Trial], + statement: ((gain candidate incumbent) <= (prim subtract (cost incumbent) (cost candidate) : Nat)), + proof: cases{ + branches: [ + { + proof: cases{ + branches: [ + { + proof: linear_arithmetic{definitions: [cost, gain, gainOf]}, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{definitions: [cost, gain, gainOf]}, + binders: [incumbentB, incumbentS, incumbentD], + constructor: coded + } + ], + scrutinee: incumbent + }, + binders: [], + constructor: failed + }, + { + proof: cases{ + branches: [ + { + proof: linear_arithmetic{definitions: [cost, gain, gainOf]}, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{definitions: [cost, gain, gainOf]}, + binders: [incumbentB, incumbentS, incumbentD], + constructor: coded + } + ], + scrutinee: incumbent + }, + binders: [candidateB, candidateS, candidateD], + constructor: coded + } + ], + scrutinee: candidate + }, + axioms: [Quot.sound, propext] +} + +theorem{ + name: dominanceIsIrreflexive, + parameters: [trial : Trial], + statement: ((gain trial trial) = 0), + proof: cases{ + branches: [ + {proof: linear_arithmetic{definitions: [gain, gainOf]}, binders: [], constructor: failed}, + { + proof: linear_arithmetic{definitions: [gain, gainOf]}, + binders: [trialB, trialS, trialD], + constructor: coded + } + ], + scrutinee: trial + }, + axioms: [Quot.sound, propext] +} + +theorem{ + name: dominanceIsTransitive, + parameters: [ab : Nat, as : Nat, bb : Nat, bs : Nat, cb : Nat, cs : Nat], + statement: (((((gainOf ab as bb bs) =? 0) || ((gainOf bb bs cb cs) =? 0)) || (((gainOf ab as bb bs) + (gainOf bb bs cb cs)) <=? (gainOf ab as cb cs))) = true), + proof: linear_arithmetic{definitions: [gainOf]}, + axioms: [Classical.choice, Quot.sound, propext] +} + +theorem{ + name: dominanceNeverGrows, + parameters: [cb : Nat, cs : Nat, ib : Nat, it : Nat], + statement: ((((gainOf cb cs ib it) =? 0) || ((cb <=? ib) && (cs <=? it))) = true), + proof: linear_arithmetic{definitions: [gainOf]}, + axioms: [Classical.choice, Quot.sound, propext] +} + +definition{ + name: bounded, + parameters: [bound : Nat, trial : Trial], + result: Trial, + body: (match trial + | Trial.failed => (ctor Trial.failed) + | Trial.coded b s d => (ctor Trial.coded (prim subtract b (prim subtract b bound : Nat) : Nat) s d)) +} + +definition{ + name: boundAll, + parameters: [bound : Nat, trials : (List Trial)], + result: (List Trial), + body: (match trials + | List.nil => (nil Trial) + | List.cons head tail => (cons (bounded bound head) (boundAll bound tail))), + recursive_argument: trials +} + +theorem{ + name: boundedSettlesTheSame, + parameters: [trial : Trial, bound : Nat, raw : Nat], + statement: ((raw <= bound) -> ((settle (bounded bound trial) raw) = (settle trial raw))), + proof: cases{ + branches: [ + {proof: linear_arithmetic{definitions: [bounded, settle]}, binders: [], constructor: failed}, + { + proof: linear_arithmetic{definitions: [bounded, settle]}, + binders: [trialB, trialS, trialD], + constructor: coded + } + ], + scrutinee: trial + }, + axioms: [Quot.sound, propext] +} + +theorem{ + name: settleOfKeep, + parameters: [left : Trial, right : Trial, raw : Nat], + statement: ((settle (keep left right) raw) = (settle left (settle right raw))), + proof: cases{ + branches: [ + { + proof: cases{ + branches: [ + { + proof: linear_arithmetic{definitions: [keep, settle]}, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{definitions: [keep, settle]}, + binders: [rightB, rightS, rightD], + constructor: coded + } + ], + scrutinee: right + }, + binders: [], + constructor: failed + }, + { + proof: cases{ + branches: [ + { + proof: linear_arithmetic{definitions: [keep, settle]}, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{definitions: [keep, settle]}, + binders: [rightB, rightS, rightD], + constructor: coded + } + ], + scrutinee: right + }, + binders: [leftB, leftS, leftD], + constructor: coded + } + ], + scrutinee: left + }, + axioms: [Quot.sound, propext] +} + +theorem{ + name: boundedPortfolioSettlesTheSame, + parameters: [trials : (List Trial), raw : Nat], + statement: ((settle (best (boundAll raw trials)) raw) = (settle (best trials) raw)), + proof: induction{ + branches: [ + {proof: reflexivity{}, binders: [], constructor: nil}, + { + proof: simplify{ + definitions: [ + best, + boundAll, + boundedSettlesTheSame, + ih, + settleNoLargerThanRaw, + settleOfKeep + ] + }, + binders: [x, others, ih], + constructor: cons + } + ], + scrutinee: trials + }, + axioms: [Quot.sound, propext] +} + +theorem{ + name: skippedTrialKeepsBytes, + parameters: [lb : Nat, ls : Nat, ld : Nat, rb : Nat, rs : Nat, rd : Nat], + statement: ((lb <= rb) -> ((weight (keep (ctor Trial.coded lb ls ld) (ctor Trial.coded rb rs rd))) = (lb + 1))), + proof: linear_arithmetic{definitions: [cost, keep, weight]}, + axioms: [Quot.sound, propext] +} + +theorem{ + name: skippedTrialKeepsSteps, + parameters: [lb : Nat, ls : Nat, ld : Nat, rb : Nat, rs : Nat, rd : Nat], + statement: ((lb <= rb) -> ((cost (keep (ctor Trial.coded lb ls ld) (ctor Trial.coded rb rs rd))) = (lb + ls))), + proof: linear_arithmetic{definitions: [cost, keep, weight]}, + axioms: [Quot.sound, propext] +} + +definition{ + name: lexGap, + parameters: [ab : Nat, as : Nat, cb : Nat, cs : Nat], + result: Nat, + body: ((prim subtract ab cb : Nat) + (prim subtract (prim subtract (prim subtract as cs : Nat) (prim subtract (prim subtract as cs : Nat) 1 : Nat) : Nat) (prim subtract cb ab : Nat) : Nat)) +} + +definition{ + name: trialGap, + parameters: [kb : Nat, ks : Nat, trial : Trial], + result: Nat, + body: (match trial | Trial.failed => 0 | Trial.coded b s d => (lexGap kb ks b s)) +} + +definition{ + name: gapAll, + parameters: [kb : Nat, ks : Nat, trials : (List Trial)], + result: Nat, + body: (match trials + | List.nil => 0 + | List.cons head tail => ((trialGap kb ks head) + (gapAll kb ks tail))), + recursive_argument: trials +} + +definition{ + name: bytesOf, + parameters: [trial : Trial], + result: Nat, + body: (match trial | Trial.failed => 0 | Trial.coded b s d => b) +} + +definition{ + name: stepsOf, + parameters: [trial : Trial], + result: Nat, + body: (match trial | Trial.failed => 0 | Trial.coded b s d => s) +} + +definition{ + name: pick, + parameters: [head : Trial, kept : Trial], + result: Trial, + body: (match head + | Trial.failed => kept + | Trial.coded b s d => (match kept + | Trial.failed => kept + | Trial.coded kb ks kd => (ctor Trial.coded (if ((b raw | List.cons head tail => (pick head (chosen raw tail))), + recursive_argument: trials +} + +theorem{ + name: pickIsLeastOfKept, + parameters: [head : Trial, kept : Trial], + statement: ((lexGap (bytesOf (pick head kept)) (stepsOf (pick head kept)) (bytesOf kept) (stepsOf kept)) = 0), + proof: cases{ + branches: [ + { + proof: cases{ + branches: [ + { + proof: linear_arithmetic{ + definitions: [bytesOf, lexGap, pick, settle, stepsOf, trialGap] + }, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{ + definitions: [bytesOf, lexGap, pick, settle, stepsOf, trialGap] + }, + binders: [keptB, keptS, keptD], + constructor: coded + } + ], + scrutinee: kept + }, + binders: [], + constructor: failed + }, + { + proof: cases{ + branches: [ + { + proof: linear_arithmetic{ + definitions: [bytesOf, lexGap, pick, settle, stepsOf, trialGap] + }, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{ + definitions: [bytesOf, lexGap, pick, settle, stepsOf, trialGap] + }, + binders: [keptB, keptS, keptD], + constructor: coded + } + ], + scrutinee: kept + }, + binders: [headB, headS, headD], + constructor: coded + } + ], + scrutinee: head + }, + axioms: [Quot.sound, propext] +} + +theorem{ + name: pickIsLeastOfHead, + parameters: [head : Trial, kept : Trial], + statement: ((trialGap (bytesOf (pick head kept)) (stepsOf (pick head kept)) head) = 0), + proof: cases{ + branches: [ + { + proof: cases{ + branches: [ + { + proof: linear_arithmetic{ + definitions: [bytesOf, lexGap, pick, settle, stepsOf, trialGap] + }, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{ + definitions: [bytesOf, lexGap, pick, settle, stepsOf, trialGap] + }, + binders: [keptB, keptS, keptD], + constructor: coded + } + ], + scrutinee: kept + }, + binders: [], + constructor: failed + }, + { + proof: cases{ + branches: [ + { + proof: linear_arithmetic{ + definitions: [bytesOf, lexGap, pick, settle, stepsOf, trialGap] + }, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{ + definitions: [bytesOf, lexGap, pick, settle, stepsOf, trialGap] + }, + binders: [keptB, keptS, keptD], + constructor: coded + } + ], + scrutinee: kept + }, + binders: [headB, headS, headD], + constructor: coded + } + ], + scrutinee: head + }, + axioms: [Classical.choice, Quot.sound, propext] +} + +theorem{ + name: pickBytesAreSettled, + parameters: [head : Trial, kept : Trial], + statement: ((bytesOf (pick head kept)) = (settle head (bytesOf kept))), + proof: cases{ + branches: [ + { + proof: cases{ + branches: [ + { + proof: linear_arithmetic{ + definitions: [bytesOf, lexGap, pick, settle, stepsOf, trialGap] + }, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{ + definitions: [bytesOf, lexGap, pick, settle, stepsOf, trialGap] + }, + binders: [keptB, keptS, keptD], + constructor: coded + } + ], + scrutinee: kept + }, + binders: [], + constructor: failed + }, + { + proof: cases{ + branches: [ + { + proof: linear_arithmetic{ + definitions: [bytesOf, lexGap, pick, settle, stepsOf, trialGap] + }, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{ + definitions: [bytesOf, lexGap, pick, settle, stepsOf, trialGap] + }, + binders: [keptB, keptS, keptD], + constructor: coded + } + ], + scrutinee: kept + }, + binders: [headB, headS, headD], + constructor: coded + } + ], + scrutinee: head + }, + axioms: [Quot.sound, propext] +} + +theorem{ + name: pickStaysLeast, + parameters: [trials : (List Trial), head : Trial, kept : Trial], + statement: (((lexGap (bytesOf (pick head kept)) (stepsOf (pick head kept)) (bytesOf kept) (stepsOf kept)) = 0) -> (((gapAll (bytesOf kept) (stepsOf kept) trials) = 0) -> ((gapAll (bytesOf (pick head kept)) (stepsOf (pick head kept)) trials) = 0))), + proof: induction{ + branches: [ + { + proof: linear_arithmetic{definitions: [gapAll, lexGap, trialGap]}, + binders: [], + constructor: nil + }, + { + proof: cases{ + branches: [ + { + proof: linear_arithmetic{definitions: [gapAll, lexGap, trialGap]}, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{definitions: [gapAll, lexGap, trialGap]}, + binders: [xB, xS, xD], + constructor: coded + } + ], + scrutinee: x + }, + binders: [x, others, ih], + constructor: cons + } + ], + scrutinee: trials + }, + axioms: [Classical.choice, Quot.sound, propext] +} + +theorem{ + name: chosenIsLeast, + parameters: [trials : (List Trial), raw : Trial], + statement: ((gapAll (bytesOf (chosen raw trials)) (stepsOf (chosen raw trials)) trials) = 0), + proof: induction{ + branches: [ + {proof: reflexivity{}, binders: [], constructor: nil}, + { + proof: simplify{ + definitions: [chosen, gapAll, ih, pickIsLeastOfHead, pickIsLeastOfKept, pickStaysLeast] + }, + binders: [x, others, ih], + constructor: cons + } + ], + scrutinee: trials + }, + axioms: [Classical.choice, Quot.sound, propext] +} + +theorem{ + name: pickStaysUnderRaw, + parameters: [head : Trial, kept : Trial, raw : Trial], + statement: (((lexGap (bytesOf (pick head kept)) (stepsOf (pick head kept)) (bytesOf kept) (stepsOf kept)) = 0) -> (((lexGap (bytesOf kept) (stepsOf kept) (bytesOf raw) (stepsOf raw)) = 0) -> ((lexGap (bytesOf (pick head kept)) (stepsOf (pick head kept)) (bytesOf raw) (stepsOf raw)) = 0))), + proof: linear_arithmetic{definitions: [lexGap]}, + axioms: [Quot.sound, propext] +} + +theorem{ + name: chosenIsNoWorseThanRaw, + parameters: [trials : (List Trial), raw : Trial], + statement: ((lexGap (bytesOf (chosen raw trials)) (stepsOf (chosen raw trials)) (bytesOf raw) (stepsOf raw)) = 0), + proof: induction{ + branches: [ + {proof: linear_arithmetic{definitions: [chosen, lexGap]}, binders: [], constructor: nil}, + { + proof: simplify{definitions: [chosen, ih, pickIsLeastOfKept, pickStaysUnderRaw]}, + binders: [x, others, ih], + constructor: cons + } + ], + scrutinee: trials + }, + axioms: [Quot.sound, propext] +} + +theorem{ + name: chosenKeepsTheSize, + parameters: [trials : (List Trial), raw : Trial], + statement: ((bytesOf (chosen raw trials)) = (settle (best trials) (bytesOf raw))), + proof: induction{ + branches: [ + { + proof: linear_arithmetic{definitions: [best, chosen, settle]}, + binders: [], + constructor: nil + }, + { + proof: simplify{definitions: [best, chosen, ih, pickBytesAreSettled, settleOfKeep]}, + binders: [x, others, ih], + constructor: cons + } + ], + scrutinee: trials + }, + axioms: [Quot.sound, propext] +} + +theorem{ + name: leastIsUndominated, + parameters: [ab : Nat, as : Nat, cb : Nat, cs : Nat], + statement: (((0 ((bytesOf (pick (ctor Trial.coded b s d) (ctor Trial.coded kb ks kd))) = kb)), + proof: linear_arithmetic{definitions: [bytesOf, lexGap, pick]}, + axioms: [Quot.sound, propext] +} + +theorem{ + name: excludedTrialKeepsSteps, + parameters: [b : Nat, s : Nat, d : Nat, kb : Nat, ks : Nat, kd : Nat], + statement: (((lexGap kb ks b s) = 0) -> ((stepsOf (pick (ctor Trial.coded b s d) (ctor Trial.coded kb ks kd))) = ks)), + proof: linear_arithmetic{definitions: [lexGap, pick, stepsOf]}, + axioms: [Quot.sound, propext] +} + +definition{ + name: consolidate, + parameters: [candidate : Trial, incumbent : Trial], + result: Trial, + body: (match candidate + | Trial.failed => incumbent + | Trial.coded cb cs cd => (match incumbent + | Trial.failed => incumbent + | Trial.coded ib it ix => (ctor Trial.coded (if (0 ((cost (consolidate candidate incumbent)) <= bound)), + proof: cases{ + branches: [ + { + proof: cases{ + branches: [ + { + proof: linear_arithmetic{definitions: [consolidate, cost, gain, gainOf]}, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{definitions: [consolidate, cost, gain, gainOf]}, + binders: [incumbentB, incumbentS, incumbentD], + constructor: coded + } + ], + scrutinee: incumbent + }, + binders: [], + constructor: failed + }, + { + proof: cases{ + branches: [ + { + proof: linear_arithmetic{definitions: [consolidate, cost, gain, gainOf]}, + binders: [], + constructor: failed + }, + { + proof: linear_arithmetic{definitions: [consolidate, cost, gain, gainOf]}, + binders: [incumbentB, incumbentS, incumbentD], + constructor: coded + } + ], + scrutinee: incumbent + }, + binders: [candidateB, candidateS, candidateD], + constructor: coded + } + ], + scrutinee: candidate + }, + axioms: [Quot.sound, propext] +} + +definition{ + name: consolidated, + parameters: [incumbent : Trial, candidates : (List Trial)], + result: Trial, + body: (match candidates + | List.nil => incumbent + | List.cons head tail => (consolidate head (consolidated incumbent tail))), + recursive_argument: candidates +} + +theorem{ + name: potentialNeverRises, + parameters: [candidates : (List Trial), incumbent : Trial], + statement: ((cost (consolidated incumbent candidates)) <= (cost incumbent)), + proof: induction{ + branches: [ + {proof: linear_arithmetic{definitions: [consolidated]}, binders: [], constructor: nil}, + { + proof: simplify{definitions: [consolidated, consolidationStaysUnder, ih]}, + binders: [x, others, ih], + constructor: cons + } + ], + scrutinee: candidates + }, + axioms: [Quot.sound, propext] +} +\end{semanticmodule} +\end{lexlean} diff --git a/src/Uorc/Registry.lex.tex b/src/Uorc/Registry.lex.tex index feb75dd1..93e27a53 100644 --- a/src/Uorc/Registry.lex.tex +++ b/src/Uorc/Registry.lex.tex @@ -222,5 +222,61 @@ result: ConformanceRow, body: (record ConformanceRow {id := "UC-WEB-01", level := "build", suite := "pages-client", statement := "The Pages client is generated from and conforms to its Prism product model in Uorc.Page: stakeholders, features with their calls and acceptance cases, journeys, the page's UML state machine, operations, fields, controls, examples, error hints, sections, usage, links and quality measures. The generated page holds exactly the modeled elements, and a real browser walks every journey, takes every modeled transition, checks every control's enabled state in every state it reaches and holds every gated quality measure.", given := "the Uorc.Page module, the generated web/index.html and the site built from the release wasm", when := "the model gate checks and renders the model and the browser acceptance drives the built site in headless Chromium", expected := "every Prism check holds, the committed page equals the rendered model, every acceptance case passes, every transition is taken and every gated measure is within its threshold", evidenceKind := "build_evidence", researchDisposition := "not_measured"}) } + +definition{ + name: performanceSizeBound, + parameters: [], + result: ConformanceRow, + body: (record ConformanceRow {id := "UC-PERF-02", level := "build", suite := "performance-theorems", statement := "For every input length n, the settled frame of Uorc.Performance is no larger than the raw frame and no larger than a coded kernel candidate, and the raw frame is two length varints of at most 10 bytes each, the n input bytes and 41 fixed bytes, so no frame of one object exceeds n + 61 bytes (archiveBound), and a stream of k such frames is within n + 61 * k bytes; the native client keeps the same rule and the same constants.", given := "the Uorc.Performance module and the native client's frame writer", when := "the locked SDK verifies the module and the native test compresses inputs of several lengths and kinds, including incompressible ones", expected := "archiveBound and its lemmas are kernel-checked, every native raw frame has the model's length, and every native frame is within n + 61 bytes", evidenceKind := "kernel_theorem", researchDisposition := "not_measured"}) +} + +definition{ + name: performancePortfolio, + parameters: [], + result: ConformanceRow, + body: (record ConformanceRow {id := "UC-PERF-03", level := "build", suite := "performance-theorems", statement := "For every list of trials, the trial the portfolio keeps (Uorc.Performance best) is no larger in bytes than any coded trial in the list (bestNoLargerThanEvery), so a portfolio archive is no larger than the archive of any strategy it scheduled.", given := "the Uorc.Performance module and the native client's strategy portfolio", when := "the locked SDK verifies the module and the native test codes sample frames under each scheduled strategy and under the portfolio", expected := "bestNoLargerThanEvery is kernel-checked and the native portfolio frame is no larger than the frame of every strategy it scheduled", evidenceKind := "kernel_theorem", researchDisposition := "not_measured"}) +} + +definition{ + name: performanceDecodeSteps, + parameters: [], + result: ConformanceRow, + body: (record ConformanceRow {id := "UC-PERF-04", level := "build", suite := "performance-theorems", statement := "A step is one model input evaluated for one coded bit. For every profile word the input count lies between 3 and 24 (17 context bits, 3 fixed inputs, 2 for each of the short-match and repeat features), a frame of n bytes costs 8 * n * inputs steps, and for every frame kind (raw, reference, ncm, ncm from a named state) decode takes at most 192 steps per modelled byte (decodeStepsBound); the full profile costs 192 steps per byte and the v0.3 profile 160. The measure counts model inputs, not machine time.", given := "the Uorc.Performance module and the native step measure in uorc::performance", when := "the locked SDK verifies the module and the native test compares the native measure with the model's constants and closed vectors for sample profiles", expected := "the step bound theorems are kernel-checked, every native constant equals the model's, and the native step count of every sampled frame is within 192 steps per byte", evidenceKind := "kernel_theorem", researchDisposition := "not_measured"}) +} + +definition{ + name: performanceMeaning, + parameters: [], + result: ConformanceRow, + body: (record ConformanceRow {id := "UC-PERF-05", level := "build", suite := "performance-theorems", statement := "A trial carries its defect, the count of bytes at which its decode differs from the input. Admission fails every trial with a nonzero defect, keeping never raises a defect above its operands', and the trial kept from any admitted list has defect 0 (bestOfAdmittedIsExact): whatever codec point or named model state produced a trial, it can change the archive's size and never its meaning.", given := "the Uorc.Performance module and the native client's candidate admission", when := "the locked SDK verifies the module and the native test decodes every frame it produced under each strategy", expected := "bestOfAdmittedIsExact and its lemmas are kernel-checked and every native frame decodes to its input", evidenceKind := "kernel_theorem", researchDisposition := "not_measured"}) +} + +definition{ + name: performanceDominance, + parameters: [], + result: ConformanceRow, + body: (record ConformanceRow {id := "UC-PERF-06", level := "build", suite := "performance-theorems", statement := "A candidate dominates an incumbent when it is no larger in bytes and no larger in steps, and its gain is the drop in bytes plus steps. The gain never exceeds the drop in cost (dominanceLowersCost), no trial gains over itself, gains compose (a positive gain of a over b and of b over c gives at least their sum of a over c), and a positive gain implies no growth in bytes or in steps: dominance is a strict partial order, so consolidating winners cannot cycle.", given := "the Uorc.Performance module", when := "the locked SDK verifies the module and the native test reads the module's theorem inventory", expected := "the four dominance theorems are kernel-checked and present", evidenceKind := "kernel_theorem", researchDisposition := "not_measured"}) +} + +definition{ + name: performanceBoundedSearch, + parameters: [], + result: ConformanceRow, + body: (record ConformanceRow {id := "UC-PERF-07", level := "build", suite := "performance-theorems", statement := "A trial abandoned at a bound is modelled as a trial of at most the bound's bytes. For every list of trials and every raw length, the portfolio of trials abandoned at the raw length settles to the same size as the portfolio of complete trials (boundedPortfolioSettlesTheSame), and a trial no smaller than one already kept changes neither the kept bytes nor the kept steps (skippedTrial theorems): a search that stops a candidate once it cannot win, or skips one known to be no smaller, writes an archive of the same size for fewer compress steps.", given := "the Uorc.Performance module and the native encoder's bound", when := "the locked SDK verifies the module and the native test abandons each scheduled strategy at several bounds", expected := "the bounded search theorems are kernel-checked, a native payload abandoned at a bound is the complete payload or is absent only when the complete payload reaches the bound, and the native frame is no larger than any complete scheduled frame or the raw frame", evidenceKind := "kernel_theorem", researchDisposition := "not_measured"}) +} + +definition{ + name: performanceUndominatedChoice, + parameters: [], + result: ConformanceRow, + body: (record ConformanceRow {id := "UC-PERF-08", level := "build", suite := "performance-theorems", statement := "Choosing by fewer bytes and then fewer steps, from the raw frame and any list of trials, keeps a trial that is no later in that order than every trial in the list and than the raw frame (chosenIsLeast, chosenIsNoWorseThanRaw), has exactly the size the bytes-only rule settles to (chosenKeepsTheSize), and is dominated by no trial it is no later than (leastIsUndominated); a trial no earlier than the kept one changes nothing (excludedTrial theorems). The rule lowers decode steps on byte ties at no cost in size. The released client breaks byte ties by schedule order until its model export adopts this rule.", given := "the Uorc.Performance module and the native choice functions in uorc::performance", when := "the locked SDK verifies the module and the native test runs the native choice over every list of three small trials", expected := "the choice theorems are kernel-checked and the native choice is least in bytes then steps, has the bytes-only size, and is dominated by no listed trial", evidenceKind := "kernel_theorem", researchDisposition := "not_measured"}) +} + +definition{ + name: performancePotential, + parameters: [], + result: ConformanceRow, + body: (record ConformanceRow {id := "UC-PERF-09", level := "build", suite := "performance-theorems", statement := "The potential of a codec point is its bytes plus its steps. Consolidating a candidate into an incumbent lowers the potential by exactly the candidate's gain (consolidationSpendsItsGain), which is positive exactly when the candidate dominates, and over any sequence of candidates the potential never rises (potentialNeverRises). The potential is a natural number, so an engine that consolidates only dominating candidates never regresses and consolidates at most as many times as its first potential.", given := "the Uorc.Performance module and the native consolidation in uorc::performance", when := "the locked SDK verifies the module and the native test consolidates every pair and sequence of small trials", expected := "the potential theorems are kernel-checked and every native consolidation lowers bytes plus steps by exactly its gain", evidenceKind := "kernel_theorem", researchDisposition := "not_measured"}) +} \end{semanticmodule} \end{lexlean}