From 1944ebe01feb2b11b5197c7b16f4ae1e9d26ccf3 Mon Sep 17 00:00:00 2001 From: stefan-gorules <127550877+stefan-gorules@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:06:29 +0100 Subject: [PATCH] fix: table analysis memory (#570) * fix(engine): keep decision table analysis memory and time in proportion to the table Schema queries no longer run table verification; graph table checks are deferred to diagnostics. Gap search and unreachable-rule cover run on per-dimension bitsets when the table is small enough to index densely, and on the set-based path otherwise. Missing cases are merged on interned ids and rendered lazily. Compression works on borrowed rows and interned cell ids, assigned once per round. Small string sets are held inline or as a sorted list instead of a tree. Findings are unchanged: the previous implementations stay as test-only references and are compared on generated tables, and tests/table_scaling.rs bounds peak memory with a counting allocator. * fix(nodejs): accept bytes and JSON text in Workspace setDocument, setPolicy and enhanceGraphTrace Documents with more than one million JSON values were rejected by the object conversion limit, which a two-column decision table reaches at 250,000 rows. Buffers and strings are parsed directly, and objects are converted without that limit. * ci: pin Rust to 1.99.0 Rust 1.100 passes one -L dependency directory per dependency, which pushes the rustc command for zen-engine past the Windows command-line limit when sccache spawns it (os error 206). Every workflow that installed stable now installs 1.99.0; miri stays on nightly. * ci: pin the UniFFI native build to Rust 1.99.0 actions-rust-cross installs its own toolchain and defaults to stable, so the Windows and macOS UniFFI builds were still on 1.100. --- .github/workflows/benchmark.yaml | 12 +- .github/workflows/go.yaml | 2 +- .github/workflows/node.yaml | 4 +- .github/workflows/python.yaml | 1 + .github/workflows/release-please.yaml | 2 +- .github/workflows/rust.yaml | 12 +- .github/workflows/uniffi.yaml | 19 +- bindings/nodejs/src/policy.rs | 43 +- bindings/nodejs/test/workspace-large.spec.ts | 55 ++ core/engine/src/analysis/table/cover.rs | 201 ++++++ core/engine/src/analysis/table/gaps.rs | 665 ++++++++++++++++++ core/engine/src/analysis/table/index.rs | 62 +- core/engine/src/analysis/table/intern.rs | 122 ++++ core/engine/src/analysis/table/merge.rs | 347 ++++++--- .../src/analysis/table/merge_reference.rs | 474 +++++++++++++ core/engine/src/analysis/table/missing.rs | 640 +++++++++-------- core/engine/src/analysis/table/mod.rs | 64 +- core/engine/src/analysis/table/partition.rs | 51 +- core/engine/src/analysis/table/sets.rs | 245 +++++++ core/engine/src/analysis/table/tests.rs | 315 +++++++++ core/engine/src/analysis/table/verify.rs | 315 +++++++-- core/engine/src/workspace/db.rs | 6 +- core/engine/src/workspace/graph/analysis.rs | 33 +- core/engine/src/workspace/graph/queries.rs | 52 +- core/engine/tests/table_scaling.rs | 602 ++++++++++++++++ .../expression/src/intellisense/values/mod.rs | 1 + .../src/intellisense/values/strings.rs | 343 +++++++++ .../src/intellisense/values/value_set.rs | 38 +- 28 files changed, 4179 insertions(+), 547 deletions(-) create mode 100644 bindings/nodejs/test/workspace-large.spec.ts create mode 100644 core/engine/src/analysis/table/cover.rs create mode 100644 core/engine/src/analysis/table/gaps.rs create mode 100644 core/engine/src/analysis/table/intern.rs create mode 100644 core/engine/src/analysis/table/merge_reference.rs create mode 100644 core/engine/src/analysis/table/sets.rs create mode 100644 core/engine/src/analysis/table/tests.rs create mode 100644 core/engine/tests/table_scaling.rs create mode 100644 core/expression/src/intellisense/values/strings.rs diff --git a/.github/workflows/benchmark.yaml b/.github/workflows/benchmark.yaml index 08783270..04126ace 100644 --- a/.github/workflows/benchmark.yaml +++ b/.github/workflows/benchmark.yaml @@ -20,7 +20,9 @@ jobs: steps: - uses: actions/checkout@v3 - name: Install Rust - run: rustup update stable + run: | + rustup toolchain install 1.99.0 --profile minimal + rustup default 1.99.0 - uses: ./.github/actions/setup-rust with: shared-key: benchmark-rust @@ -48,9 +50,9 @@ jobs: cache: yarn cache-dependency-path: 'bindings/nodejs/yarn.lock' - name: Install Rust - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@1.99.0 with: - toolchain: stable + toolchain: 1.99.0 targets: x86_64-unknown-linux-gnu - uses: ./.github/actions/setup-rust with: @@ -75,7 +77,9 @@ jobs: with: python-version: '3.13' - name: Install Rust - run: rustup update stable + run: | + rustup toolchain install 1.99.0 --profile minimal + rustup default 1.99.0 - uses: ./.github/actions/setup-rust with: shared-key: benchmark-python diff --git a/.github/workflows/go.yaml b/.github/workflows/go.yaml index 4ce1e83f..c6ce5e38 100644 --- a/.github/workflows/go.yaml +++ b/.github/workflows/go.yaml @@ -45,7 +45,7 @@ jobs: - uses: actions-rs/toolchain@v1 with: - toolchain: stable + toolchain: 1.99.0 override: true target: ${{ matrix.settings.target }} - uses: ./.github/actions/setup-rust diff --git a/.github/workflows/node.yaml b/.github/workflows/node.yaml index 713443b7..026bbfe9 100644 --- a/.github/workflows/node.yaml +++ b/.github/workflows/node.yaml @@ -122,9 +122,9 @@ jobs: cache-dependency-path: 'bindings/nodejs/yarn.lock' - name: Install - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@1.99.0 with: - toolchain: stable + toolchain: 1.99.0 targets: ${{ matrix.settings.target }} - name: Rust cache + sccache (+ zig for linux legs) diff --git a/.github/workflows/python.yaml b/.github/workflows/python.yaml index f448b413..e557013f 100644 --- a/.github/workflows/python.yaml +++ b/.github/workflows/python.yaml @@ -62,6 +62,7 @@ jobs: args: ${{ matrix.args }} manylinux: ${{ matrix.manylinux || 'auto' }} sccache: 'true' + rust-toolchain: 1.99.0 - name: Upload wheels uses: actions/upload-artifact@v4 diff --git a/.github/workflows/release-please.yaml b/.github/workflows/release-please.yaml index 952bc3ea..e2599388 100644 --- a/.github/workflows/release-please.yaml +++ b/.github/workflows/release-please.yaml @@ -71,7 +71,7 @@ jobs: ref: ${{ steps.release.outputs.pr-branch }} token: ${{ secrets.PAT }} - - uses: dtolnay/rust-toolchain@stable + - uses: dtolnay/rust-toolchain@1.99.0 if: steps.release.outputs.pr-branch - name: Update Cargo.lock on release PR diff --git a/.github/workflows/rust.yaml b/.github/workflows/rust.yaml index da7c2a6b..02850478 100644 --- a/.github/workflows/rust.yaml +++ b/.github/workflows/rust.yaml @@ -41,7 +41,9 @@ jobs: steps: - uses: actions/checkout@v3 - name: Install Rust - run: rustup update stable + run: | + rustup toolchain install 1.99.0 --profile minimal + rustup default 1.99.0 - uses: ./.github/actions/setup-rust with: shared-key: rust-test-${{ matrix.os }} @@ -58,7 +60,9 @@ jobs: steps: - uses: actions/checkout@v3 - name: Install Rust - run: rustup update stable + run: | + rustup toolchain install 1.99.0 --profile minimal --component rustfmt + rustup default 1.99.0 - run: cargo fmt --all -- --check release: @@ -73,7 +77,9 @@ jobs: - uses: actions/checkout@v3 - name: Install Rust - run: rustup update stable + run: | + rustup toolchain install 1.99.0 --profile minimal + rustup default 1.99.0 - name: Login to Crates.IO run: cargo login ${{ secrets.CRATES_TOKEN }} diff --git a/.github/workflows/uniffi.yaml b/.github/workflows/uniffi.yaml index 3f62610d..1caa8a9f 100644 --- a/.github/workflows/uniffi.yaml +++ b/.github/workflows/uniffi.yaml @@ -68,7 +68,7 @@ jobs: - uses: actions/checkout@v3 - name: Setup Rust Toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@1.99.0 with: target: ${{ matrix.settings.target }} @@ -97,6 +97,7 @@ jobs: with: working-directory: ${{ env.UNIFFI_DIRECTORY }} target: ${{ matrix.settings.target }} + toolchain: 1.99.0 args: '--lib --release --locked ${{ matrix.settings.extra_args }}' - name: Verify max glibc requirement @@ -156,7 +157,7 @@ jobs: dotnet-version: '8.0.x' - name: Setup Rust Toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@1.99.0 - uses: ./.github/actions/setup-rust with: @@ -234,7 +235,7 @@ jobs: - uses: actions/checkout@v3 - name: Setup Rust Toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@1.99.0 - uses: ./.github/actions/setup-rust with: @@ -287,7 +288,7 @@ jobs: - uses: actions/checkout@v3 - name: Setup Rust Toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@1.99.0 - uses: ./.github/actions/setup-rust with: @@ -332,7 +333,7 @@ jobs: distribution: 'temurin' - name: Setup Rust Toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@1.99.0 - uses: ./.github/actions/setup-rust with: @@ -408,7 +409,7 @@ jobs: dotnet-version: '8.0.x' - name: Setup Rust Toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@1.99.0 - uses: ./.github/actions/setup-rust with: @@ -501,7 +502,7 @@ jobs: - uses: actions/checkout@v3 - name: Setup Rust Toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@1.99.0 with: target: ${{ matrix.settings.target }} @@ -537,7 +538,7 @@ jobs: - uses: actions/checkout@v3 - name: Setup Rust Toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@1.99.0 - uses: ./.github/actions/setup-rust with: @@ -717,7 +718,7 @@ jobs: - uses: actions/checkout@v3 - name: Setup Rust Toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@1.99.0 - uses: ./.github/actions/setup-rust with: diff --git a/bindings/nodejs/src/policy.rs b/bindings/nodejs/src/policy.rs index 5d3dc156..16873ffb 100644 --- a/bindings/nodejs/src/policy.rs +++ b/bindings/nodejs/src/policy.rs @@ -2,9 +2,10 @@ use std::collections::HashMap; use std::sync::Arc; use napi::anyhow::anyhow; -use napi::bindgen_prelude::{FnArgs, FunctionRef}; +use napi::bindgen_prelude::{Either3, FnArgs, FunctionRef, Object, Uint8Array}; use napi::Env; use napi_derive::napi; +use serde::de::DeserializeOwned; use serde_json::Value; use zen_engine::policy::PolicyDocument; @@ -12,6 +13,19 @@ use zen_engine::workspace; type ResolverRef = FunctionRef, Option>; +type JsonInput<'env> = Either3>; + +fn parse_json_input(env: &Env, input: JsonInput) -> Result { + match input { + Either3::A(bytes) => serde_json::from_slice(bytes.as_ref()).map_err(|e| e.to_string()), + Either3::B(text) => serde_json::from_str(&text).map_err(|e| e.to_string()), + Either3::C(object) => { + let value: Value = env.from_js_value(object).map_err(|e| e.to_string())?; + serde_json::from_value(value).map_err(|e| e.to_string()) + } + } +} + #[napi(object)] pub struct PolicyChanges { pub cursor: i64, @@ -593,16 +607,26 @@ impl Workspace { } #[napi] - pub fn set_document(&mut self, path: String, document: Value) -> napi::Result<()> { + pub fn set_document( + &mut self, + env: Env, + path: String, + #[napi(ts_arg_type = "Uint8Array | string | object")] document: JsonInput, + ) -> napi::Result<()> { let doc: zen_engine::model::DecisionContent = - serde_json::from_value(document).map_err(|e| anyhow!("Invalid document: {e}"))?; + parse_json_input(&env, document).map_err(|e| anyhow!("Invalid document: {e}"))?; self.inner.set_document(path, doc); Ok(()) } #[napi] - pub fn set_policy(&mut self, path: String, document: Value) -> napi::Result<()> { - let doc: PolicyDocument = serde_json::from_value(document) + pub fn set_policy( + &mut self, + env: Env, + path: String, + #[napi(ts_arg_type = "Uint8Array | string | object")] document: JsonInput, + ) -> napi::Result<()> { + let doc: PolicyDocument = parse_json_input(&env, document) .map_err(|e| anyhow!("Invalid policy document: {e}"))?; self.inner.set_policy(path, doc); Ok(()) @@ -981,9 +1005,14 @@ impl Workspace { } #[napi(ts_return_type = "PolicyTrace")] - pub fn enhance_graph_trace(&self, path: String, trace: Value) -> napi::Result { + pub fn enhance_graph_trace( + &self, + env: Env, + path: String, + #[napi(ts_arg_type = "Uint8Array | string | object")] trace: JsonInput, + ) -> napi::Result { let trace_map: workspace::GraphTraceMap = - serde_json::from_value(trace).map_err(|e| napi::Error::from_reason(e.to_string()))?; + parse_json_input(&env, trace).map_err(napi::Error::from_reason)?; let result = self .inner .enhance_graph_trace(&Arc::from(path.as_str()), &trace_map) diff --git a/bindings/nodejs/test/workspace-large.spec.ts b/bindings/nodejs/test/workspace-large.spec.ts new file mode 100644 index 00000000..a44c81ae --- /dev/null +++ b/bindings/nodejs/test/workspace-large.spec.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from '@jest/globals'; + +const { Workspace } = require('../index.js'); + +const lookupTable = (rows: number) => ({ + nodes: [ + { id: 'in', name: 'request', type: 'inputNode', content: { schema: '' }, position: { x: 0, y: 0 } }, + { + id: 'table', + name: 'lookup', + type: 'decisionTableNode', + position: { x: 300, y: 0 }, + content: { + hitPolicy: 'first', + inputs: [{ id: 'code', name: 'Code', field: 'code' }], + outputs: [{ id: 'rate', name: 'Rate', field: 'rate' }], + rules: Array.from({ length: rows }, (_, row) => ({ + _id: `r${row}`, + code: `"C${row}"`, + rate: String(row), + })), + passThrough: true, + }, + }, + { id: 'out', name: 'response', type: 'outputNode', content: { schema: '' }, position: { x: 600, y: 0 } }, + ], + edges: [ + { id: 'e1', type: 'edge', sourceId: 'in', targetId: 'table' }, + { id: 'e2', type: 'edge', sourceId: 'table', targetId: 'out' }, + ], +}); + +describe('Workspace large documents', () => { + const rows = 300_000; + const content = lookupTable(rows); + const text = JSON.stringify(content); + + it.each<[string, () => unknown]>([ + ['an object', () => content], + ['a JSON string', () => text], + ['a Buffer', () => Buffer.from(text)], + ['a Uint8Array', () => new TextEncoder().encode(text)], + ])('loads more than a million JSON values from %s', (_, document) => { + const ws = new Workspace(); + ws.setDocument('lookup', document()); + expect(ws.isGraph('lookup')).toBe(true); + expect(ws.paths()).toEqual(['lookup']); + expect(ws.inputs({ policyPath: 'lookup' }).map((input: any) => input.path)).toEqual(['code']); + }); + + it('reports invalid JSON text', () => { + const ws = new Workspace(); + expect(() => ws.setDocument('broken', '{ "nodes": ')).toThrow(/Invalid document/); + }); +}); diff --git a/core/engine/src/analysis/table/cover.rs b/core/engine/src/analysis/table/cover.rs new file mode 100644 index 00000000..0f0d563e --- /dev/null +++ b/core/engine/src/analysis/table/cover.rs @@ -0,0 +1,201 @@ +use std::rc::Rc; + +use ahash::HashMap; + +use super::cell::CellConstraint; +use super::gaps::{Bits, Dense, Space}; +use super::partition::Partition; +use super::value_set::ValueSet; +use super::verify::{Budget, MAX_FRAGMENTS, MAX_MINIMIZE}; + +pub(super) struct Coverage { + space: Space, + columns: usize, + bits: Vec, + opaque: Vec, + coverable: Vec, + remaining: Vec, + next: Vec, + prefix: Vec, +} + +impl Coverage { + pub(super) fn new(cells: &[Vec], columns: usize) -> Option { + let mut set_of: Vec>> = Vec::with_capacity(columns); + let mut sets_of: Vec> = Vec::with_capacity(columns); + let everything = ValueSet::all(); + for column in 0..columns { + let mut index: HashMap<&ValueSet, u32> = HashMap::default(); + let mut distinct: Vec<&ValueSet> = Vec::new(); + let ids: Vec> = cells + .iter() + .map(|row| match &row[column] { + CellConstraint::Known(set) => Some(*index.entry(set).or_insert_with(|| { + distinct.push(set); + distinct.len() as u32 - 1 + })), + _ => None, + }) + .collect(); + set_of.push(ids); + sets_of.push(distinct); + } + let atoms = sets_of + .iter() + .map(|sets| Dense::atoms(sets.iter().copied())); + if !Dense::fits(cells.len(), atoms) { + return None; + } + let mut partitions: Vec = Vec::with_capacity(columns); + let mut atoms_of: Vec>> = Vec::with_capacity(columns); + for distinct in sets_of { + let owned: Vec = distinct.into_iter().cloned().collect(); + let partition = Partition::new(&everything, &owned); + atoms_of.push(owned.iter().map(|set| partition.touching(set)).collect()); + partitions.push(partition); + } + let layouts: Vec<_> = partitions.iter().map(Partition::layout).collect(); + let widths: Vec = layouts.iter().map(|layout| layout.atoms).collect(); + let space = Space::new(layouts); + let stride = space.stride(); + + let mut opaque_ids: HashMap, u32> = HashMap::default(); + let mut bits = vec![0u64; cells.len() * stride]; + let mut opaque = vec![0u32; cells.len() * columns]; + let mut coverable = vec![true; cells.len()]; + for (row, row_cells) in cells.iter().enumerate() { + let words = &mut bits[row * stride..(row + 1) * stride]; + for (column, (axis, cell)) in space.axes().iter().zip(row_cells).enumerate() { + let words = &mut words[axis.range()]; + match (cell, set_of[column][row]) { + (CellConstraint::Known(set), Some(id)) => { + coverable[row] &= !set.is_empty(); + atoms_of[column][id as usize] + .iter() + .for_each(|&atom| Bits::set(words, atom)); + } + (cell, _) => { + (0..widths[column]).for_each(|atom| Bits::set(words, atom)); + if let CellConstraint::Opaque(atom) = cell { + let next = opaque_ids.len() as u32 + 1; + opaque[row * columns + column] = + *opaque_ids.entry(atom.clone()).or_insert(next); + } + } + } + } + } + Some(Self { + space, + columns, + bits, + opaque, + coverable, + remaining: Vec::new(), + next: Vec::new(), + prefix: Vec::new(), + }) + } + + fn projects(&self, earlier: usize, row: usize) -> bool { + let columns = self.columns; + self.coverable[earlier] + && self.opaque[earlier * columns..(earlier + 1) * columns] + .iter() + .zip(&self.opaque[row * columns..(row + 1) * columns]) + .all(|(&theirs, &own)| theirs == 0 || theirs == own) + } + + pub(super) fn covered_by( + &mut self, + row: usize, + requirements: &[Vec], + budget: &mut Budget, + ) -> Option>> { + let mut cited: Vec = Vec::new(); + for earlier in requirements { + let coverers: Vec = earlier + .iter() + .copied() + .filter(|&e| self.projects(e, row)) + .collect(); + let Some(used) = self.cover(row, &coverers, budget)? else { + return Some(None); + }; + cited.extend(self.minimize(row, used, budget)?); + } + cited.sort_unstable(); + cited.dedup(); + Some(Some(cited)) + } + + fn cover( + &mut self, + row: usize, + coverers: &[usize], + budget: &mut Budget, + ) -> Option>> { + let Self { + space, + columns, + bits, + remaining, + next, + prefix, + .. + } = self; + let stride = space.stride(); + remaining.clear(); + remaining.extend_from_slice(&bits[row * stride..(row + 1) * stride]); + let mut used = Vec::new(); + for &earlier in coverers { + let cut = &bits[earlier * stride..(earlier + 1) * stride]; + next.clear(); + let mut touched = false; + for fragment in remaining.chunks_exact(stride) { + budget.spend(*columns)?; + match space.subtract(fragment, cut, prefix, next) { + true => touched = true, + false => next.extend_from_slice(fragment), + } + } + if next.len() / stride > MAX_FRAGMENTS { + return None; + } + if touched { + used.push(earlier); + } + std::mem::swap(remaining, next); + if remaining.is_empty() { + return Some(Some(used)); + } + } + Some(None) + } + + fn minimize( + &mut self, + row: usize, + used: Vec, + budget: &mut Budget, + ) -> Option> { + if used.len() > MAX_MINIMIZE { + return Some(used); + } + let mut kept = used; + let mut i = kept.len(); + while i > 0 { + i -= 1; + let candidate: Vec = kept + .iter() + .enumerate() + .filter(|(j, _)| *j != i) + .map(|(_, &earlier)| earlier) + .collect(); + if self.cover(row, &candidate, budget)?.is_some() { + kept.remove(i); + } + } + Some(kept) + } +} diff --git a/core/engine/src/analysis/table/gaps.rs b/core/engine/src/analysis/table/gaps.rs new file mode 100644 index 00000000..fff453bc --- /dev/null +++ b/core/engine/src/analysis/table/gaps.rs @@ -0,0 +1,665 @@ +use std::ops::Range; +use std::rc::Rc; + +use ahash::{HashMap, HashSet}; +use rust_decimal::Decimal; + +use super::intern::Interner; +use super::partition::Layout; +use super::value_set::{Bound, StringSet, ValueSet}; +use super::verify::MAX_FRAGMENTS; + +const DIRECT_ROWS: usize = 8; +const WORD: usize = u64::BITS as usize; + +pub(super) struct Dense; + +impl Dense { + const REGION_WORDS: usize = 128; + const TABLE_WORDS: usize = 16 << 20; + + pub(super) fn atoms<'s>(sets: impl IntoIterator) -> usize { + let mut strings: HashSet<&Rc> = HashSet::default(); + let mut points: HashSet = HashSet::default(); + for set in sets { + match &set.strings { + StringSet::Finite(keys) | StringSet::CoFinite(keys) => strings.extend(keys), + } + for interval in set.numbers.intervals() { + for bound in [interval.lo, interval.hi] { + if let Bound::Inclusive(point) | Bound::Exclusive(point) = bound { + points.insert(point); + } + } + } + } + strings.len() + 2 * points.len() + 6 + } + + pub(super) fn fits(rows: usize, atoms: impl Iterator) -> bool { + let stride: usize = atoms.map(Bits::words).sum(); + stride <= Self::REGION_WORDS && rows.saturating_mul(stride) <= Self::TABLE_WORDS + } +} + +pub(super) struct Bits; + +impl Bits { + pub(super) fn words(atoms: usize) -> usize { + atoms.div_ceil(WORD).max(1) + } + + pub(super) fn has(words: &[u64], atom: usize) -> bool { + words[atom / WORD] >> (atom % WORD) & 1 == 1 + } + + pub(super) fn set(words: &mut [u64], atom: usize) { + words[atom / WORD] |= 1 << (atom % WORD); + } + + pub(super) fn ones(words: &[u64]) -> impl Iterator + '_ { + words.iter().enumerate().flat_map(|(index, &word)| { + let mut rest = word; + std::iter::from_fn(move || { + (rest != 0).then(|| { + let atom = index * WORD + rest.trailing_zeros() as usize; + rest &= rest - 1; + atom + }) + }) + }) + } +} + +pub(super) struct Axis { + offset: usize, + words: usize, + atoms: usize, + strings: usize, + rest: Option, + numbers: Range, + piece_of: Vec, + last_piece: u32, + string_mask: Vec, + number_mask: Vec, + tail_mask: Vec, + consecutive: Vec, +} + +impl Axis { + fn new(layout: Layout, offset: usize) -> Self { + let words = Bits::words(layout.atoms); + let mut string_mask = vec![0u64; words]; + let mut number_mask = vec![0u64; words]; + let mut tail_mask = vec![0u64; words]; + let mut consecutive = vec![0u64; words]; + (0..layout.strings).for_each(|atom| Bits::set(&mut string_mask, atom)); + layout + .numbers + .clone() + .for_each(|atom| Bits::set(&mut number_mask, atom)); + (layout.numbers.end..layout.atoms).for_each(|atom| Bits::set(&mut tail_mask, atom)); + for (index, pair) in layout.piece_of.windows(2).enumerate() { + if pair[1] == pair[0] + 1 { + Bits::set(&mut consecutive, layout.numbers.start + index); + } + } + Self { + offset, + words, + atoms: layout.atoms, + strings: layout.strings, + rest: layout.rest, + numbers: layout.numbers, + piece_of: layout.piece_of, + last_piece: layout.last_piece, + string_mask, + number_mask, + tail_mask, + consecutive, + } + } + + pub(super) fn range(&self) -> Range { + self.offset..self.offset + self.words + } + + fn piece(&self, atom: usize) -> u32 { + self.piece_of[atom - self.numbers.start] + } + + fn localize(&self, bounds: &[u64], scratch: &mut Scratch) -> usize { + let words = self.words; + let distinct = scratch.sets.len() as u32; + for buffer in [ + &mut scratch.mentioned, + &mut scratch.starts, + &mut scratch.ends, + &mut scratch.count_mask, + ] { + buffer.clear(); + buffer.resize(words, 0); + } + for id in 0..distinct { + let set = scratch.sets.get(id); + let flip = match self.rest { + Some(rest) if Bits::has(set, rest) => u64::MAX, + _ => 0, + }; + for index in 0..words { + scratch.mentioned[index] |= (set[index] ^ flip) & self.string_mask[index]; + let numbers = set[index] & self.number_mask[index]; + let after = match set.get(index + 1) { + Some(next) => (next & self.number_mask[index + 1]) << (WORD - 1), + None => 0, + }; + let before = match index { + 0 => 0, + _ => { + (set[index - 1] & self.number_mask[index - 1] & self.consecutive[index - 1]) + >> (WORD - 1) + } + }; + let continues = numbers & self.consecutive[index] & ((numbers >> 1) | after); + let continued = numbers & (((numbers & self.consecutive[index]) << 1) | before); + scratch.ends[index] |= numbers & !continues; + scratch.starts[index] |= numbers & !continued; + } + } + + scratch.marks.clear(); + for atom in Bits::ones(&scratch.ends) { + let piece = self.piece(atom); + if piece < self.last_piece { + scratch.marks.push(piece / 2); + } + } + for atom in Bits::ones(&scratch.starts) { + let piece = self.piece(atom); + if piece >= 1 { + scratch.marks.push((piece - 1) / 2); + } + } + scratch.marks.sort_unstable(); + scratch.marks.dedup(); + + scratch.order.clear(); + let mut lump: Option = None; + for index in 0..words { + let strings = bounds[index] & self.string_mask[index]; + scratch.mentioned[index] &= strings; + let unlisted = strings & !scratch.mentioned[index]; + if lump.is_none() && unlisted != 0 { + lump = Some(index * WORD + unlisted.trailing_zeros() as usize); + } + } + scratch + .order + .extend(Bits::ones(&scratch.mentioned).map(|a| a as u32)); + let lump = lump.or(self.rest.filter(|&rest| Bits::has(bounds, rest))); + scratch.lump = lump.map(|atom| atom as u32); + scratch.order.extend(scratch.lump); + + let mut below = 0usize; + let mut previous: Option = None; + for index in 0..words { + let mut numbers = bounds[index] & self.number_mask[index]; + while numbers != 0 { + let atom = index * WORD + numbers.trailing_zeros() as usize; + numbers &= numbers - 1; + let piece = self.piece(atom); + let point = piece / 2; + while scratch.marks.get(below).is_some_and(|&mark| mark < point) { + below += 1; + } + let marked = piece % 2 == 1 && scratch.marks.get(below) == Some(&point); + let local = 2 * below as u32 + u32::from(marked); + if previous != Some(local) { + previous = Some(local); + scratch.order.push(atom as u32); + } + } + } + for index in 0..words { + let mut tail = bounds[index] & self.tail_mask[index]; + while tail != 0 { + scratch + .order + .push((index * WORD + tail.trailing_zeros() as usize) as u32); + tail &= tail - 1; + } + } + + if scratch.slot_of.len() < self.atoms { + scratch.slot_of.resize(self.atoms, 0); + } + for (slot, &atom) in scratch.order.iter().enumerate() { + scratch.slot_of[atom as usize] = slot as u32; + Bits::set(&mut scratch.count_mask, atom as usize); + } + + (0..distinct) + .map(|id| { + scratch + .sets + .get(id) + .iter() + .zip(&scratch.count_mask) + .map(|(set, mask)| (set & mask).count_ones() as usize) + .sum::() + }) + .sum() + } + + fn group(&self, scratch: &mut Scratch) { + let slots = scratch.order.len(); + if scratch.touched.len() < slots { + scratch.touched.resize_with(slots, Vec::new); + } + scratch.touched[..slots].iter_mut().for_each(Vec::clear); + for id in 0..scratch.sets.len() as u32 { + let set = scratch.sets.get(id); + for index in 0..self.words { + let mut local = set[index] & scratch.count_mask[index]; + while local != 0 { + let atom = index * WORD + local.trailing_zeros() as usize; + local &= local - 1; + scratch.touched[scratch.slot_of[atom] as usize].push(id); + } + } + } + + scratch.lookup.clear(); + scratch.group_of.clear(); + scratch.leader.clear(); + for slot in 0..slots { + let ids = &scratch.touched[slot]; + let hash = ids.iter().fold(0x9E37_79B9_7F4A_7C15u64, |hash, &id| { + (hash ^ u64::from(id)).wrapping_mul(0xA24B_AED4_963E_E407) + }); + let mut probe = 0u32; + let group = loop { + match scratch.lookup.get(&(hash, ids.len(), probe)) { + Some(&group) + if scratch.touched[scratch.leader[group as usize] as usize] == *ids => + { + break group; + } + Some(_) => probe += 1, + None => { + let group = scratch.leader.len() as u32; + scratch.lookup.insert((hash, ids.len(), probe), group); + scratch.leader.push(slot as u32); + break group; + } + } + }; + scratch.group_of.push(group); + } + } + + fn masks(&self, bounds: &[u64], scratch: &Scratch) -> Vec { + let mut masks = vec![0u64; scratch.leader.len() * self.words]; + let lump = scratch.lump.map(|atom| scratch.slot_of[atom as usize]); + let mut piece_slot = 0u32; + for atom in Bits::ones(bounds) { + let own = || scratch.slot_of[atom]; + let slot = if atom < self.strings { + match Bits::has(&scratch.mentioned, atom) { + true => Some(own()), + false => lump, + } + } else if Some(atom) == self.rest { + lump + } else if self.numbers.contains(&atom) { + if Bits::has(&scratch.count_mask, atom) { + piece_slot = own(); + } + Some(piece_slot) + } else { + Some(own()) + }; + let Some(slot) = slot else { + continue; + }; + let group = scratch.group_of[slot as usize] as usize; + Bits::set( + &mut masks[group * self.words..(group + 1) * self.words], + atom, + ); + } + masks + } +} + +pub(super) struct Space { + axes: Vec, + stride: usize, +} + +impl Space { + pub(super) fn new(layouts: Vec) -> Self { + let mut stride = 0; + let axes = layouts + .into_iter() + .map(|layout| { + let axis = Axis::new(layout, stride); + stride += axis.words; + axis + }) + .collect(); + Self { axes, stride } + } + + pub(super) fn stride(&self) -> usize { + self.stride + } + + pub(super) fn axes(&self) -> &[Axis] { + &self.axes + } + + fn full(&self) -> Vec { + let mut region = vec![0u64; self.stride]; + for axis in &self.axes { + (0..axis.atoms).for_each(|atom| Bits::set(&mut region[axis.range()], atom)); + } + region + } + + fn meets(&self, cut: &[u64], region: &[u64]) -> bool { + self.axes + .iter() + .all(|axis| axis.range().any(|index| cut[index] & region[index] != 0)) + } + + fn within(region: &[u64], cut: &[u64]) -> bool { + region.iter().zip(cut).all(|(set, cut)| set & !cut == 0) + } + + pub(super) fn subtract( + &self, + fragment: &[u64], + cut: &[u64], + prefix: &mut Vec, + out: &mut Vec, + ) -> bool { + if !self.meets(cut, fragment) { + return false; + } + prefix.clear(); + prefix.extend_from_slice(fragment); + for axis in &self.axes { + let range = axis.range(); + if range.clone().any(|index| prefix[index] & !cut[index] != 0) { + let start = out.len(); + out.extend_from_slice(prefix); + for index in range.clone() { + out[start + index] = prefix[index] & !cut[index]; + } + } + for index in range { + prefix[index] &= cut[index]; + } + } + true + } +} + +#[derive(Default)] +struct Scratch { + sets: Interner, + of_row: Vec, + key: Vec, + mentioned: Vec, + starts: Vec, + ends: Vec, + count_mask: Vec, + marks: Vec, + order: Vec, + lump: Option, + slot_of: Vec, + touched: Vec>, + lookup: HashMap<(u64, usize, u32), u32>, + group_of: Vec, + leader: Vec, + counts: Vec, +} + +struct Best { + axis: usize, + score: usize, + masks: Vec, + ids: Vec>, + of_row: Vec, + distinct: usize, +} + +struct Piece { + bits: Vec, + rows: Vec, +} + +struct Split { + axis: usize, + pieces: Vec, +} + +pub(super) struct Found { + pub(super) patterns: Vec>, + pub(super) fragments: Vec, +} + +pub(super) struct Gaps<'c> { + space: &'c Space, + cuts: &'c [u64], + work: usize, + patterns: Vec>, + fragments: Vec, + scratch: Scratch, +} + +impl<'c> Gaps<'c> { + pub(super) fn new(space: &'c Space, cuts: &'c [u64], work: usize) -> Self { + Self { + space, + cuts, + work, + patterns: space + .axes + .iter() + .map(|axis| Interner::new(axis.words)) + .collect(), + fragments: Vec::new(), + scratch: Scratch::default(), + } + } + + pub(super) fn run(mut self, rows: usize) -> Option { + let region = self.space.full(); + self.uncovered(region, (0..rows as u32).collect())?; + Some(Found { + patterns: self.patterns, + fragments: self.fragments, + }) + } + + fn spend(&mut self, amount: usize) -> Option<()> { + self.work = self.work.checked_sub(amount.max(1))?; + Some(()) + } + + fn cut(&self, row: u32) -> &'c [u64] { + let cuts: &'c [u64] = self.cuts; + let start = row as usize * self.space.stride; + &cuts[start..start + self.space.stride] + } + + fn emit(&mut self, region: &[u64]) { + for (axis, patterns) in self.space.axes.iter().zip(self.patterns.iter_mut()) { + self.fragments.push(patterns.intern(®ion[axis.range()])); + } + } + + fn uncovered(&mut self, region: Vec, rows: Vec) -> Option<()> { + let space = self.space; + self.spend(rows.len() * space.axes.len())?; + let rows: Vec = rows + .into_iter() + .filter(|&row| space.meets(self.cut(row), ®ion)) + .collect(); + if rows.is_empty() { + self.emit(®ion); + return Some(()); + } + if rows + .iter() + .any(|&row| Space::within(®ion, self.cut(row))) + { + return Some(()); + } + if rows.len() > DIRECT_ROWS { + if let Some(split) = self.split(®ion, &rows) { + let range = space.axes[split.axis].range(); + for piece in split.pieces { + let mut narrowed = region.clone(); + narrowed[range.clone()].copy_from_slice(&piece.bits); + self.uncovered(narrowed, piece.rows)?; + } + return Some(()); + } + } + self.subtract_all(region, &rows) + } + + fn subtract_all(&mut self, region: Vec, rows: &[u32]) -> Option<()> { + let space = self.space; + let stride = space.stride; + let dims = space.axes.len(); + let mut remaining = region; + let mut next: Vec = Vec::new(); + let mut prefix: Vec = Vec::with_capacity(stride); + for &row in rows { + let cut = self.cut(row); + next.clear(); + for fragment in remaining.chunks_exact(stride) { + self.spend(dims)?; + if !space.subtract(fragment, cut, &mut prefix, &mut next) { + next.extend_from_slice(fragment); + } + } + if next.len() / stride > MAX_FRAGMENTS { + return None; + } + std::mem::swap(&mut remaining, &mut next); + if remaining.is_empty() { + return Some(()); + } + } + for fragment in remaining.chunks_exact(stride) { + self.emit(fragment); + } + Some(()) + } + + fn split(&mut self, region: &[u64], rows: &[u32]) -> Option { + let space = self.space; + let scratch = &mut self.scratch; + let mut best: Option = None; + for (index, axis) in space.axes.iter().enumerate() { + let bounds = ®ion[axis.range()]; + scratch.sets.reset(axis.words); + scratch.of_row.clear(); + for &row in rows { + let start = row as usize * space.stride + axis.offset; + let cut = &self.cuts[start..start + axis.words]; + scratch.key.clear(); + scratch + .key + .extend(cut.iter().zip(bounds).map(|(cut, bound)| cut & bound)); + scratch.of_row.push(scratch.sets.intern(&scratch.key)); + } + let distinct = scratch.sets.len(); + if distinct == 1 && scratch.sets.get(0) == bounds { + continue; + } + if axis.localize(bounds, scratch) > self.work { + return None; + } + axis.group(scratch); + let groups = scratch.leader.len(); + if groups < 2 { + continue; + } + scratch.counts.clear(); + scratch.counts.resize(distinct, 0); + for &id in &scratch.of_row { + scratch.counts[id as usize] += 1; + } + let score: usize = scratch + .leader + .iter() + .map(|&slot| { + scratch.touched[slot as usize] + .iter() + .map(|&id| scratch.counts[id as usize]) + .sum::() + }) + .sum(); + self.work = self.work.checked_sub((score + groups).max(1))?; + if best.as_ref().is_none_or(|best| score < best.score) { + best = Some(Best { + axis: index, + score, + masks: axis.masks(bounds, scratch), + ids: scratch + .leader + .iter() + .map(|&slot| scratch.touched[slot as usize].clone()) + .collect(), + of_row: scratch.of_row.clone(), + distinct, + }); + } + } + let best = best?; + let words = space.axes[best.axis].words; + let mut starts = vec![0u32; best.distinct + 1]; + for &id in &best.of_row { + starts[id as usize + 1] += 1; + } + for id in 0..best.distinct { + starts[id + 1] += starts[id]; + } + let mut cursor = starts.clone(); + let mut by_set = vec![0u32; rows.len()]; + for (&row, &id) in rows.iter().zip(&best.of_row) { + by_set[cursor[id as usize] as usize] = row; + cursor[id as usize] += 1; + } + let pieces = best + .ids + .iter() + .zip(best.masks.chunks_exact(words)) + .map(|(ids, mask)| { + let mut piece_rows: Vec = ids + .iter() + .flat_map(|&id| { + by_set[starts[id as usize] as usize..starts[id as usize + 1] as usize] + .iter() + .copied() + }) + .collect(); + piece_rows.sort_unstable(); + Piece { + bits: mask.to_vec(), + rows: piece_rows, + } + }) + .collect(); + Some(Split { + axis: best.axis, + pieces, + }) + } +} diff --git a/core/engine/src/analysis/table/index.rs b/core/engine/src/analysis/table/index.rs index 983bf4ee..752fbc23 100644 --- a/core/engine/src/analysis/table/index.rs +++ b/core/engine/src/analysis/table/index.rs @@ -3,6 +3,7 @@ use std::rc::Rc; use ahash::HashMap; use super::cell::CellConstraint; +use super::merge::CellKeys; use super::partition::Points; use rust_decimal::Decimal; @@ -107,6 +108,7 @@ pub(super) struct RowIndex { stamp: Vec, query: usize, blocking: bool, + overlaps: HashMap<(u32, u32, u32), bool>, } enum Keys<'a> { @@ -139,6 +141,7 @@ impl RowIndex { stamp: vec![0; cells.len()], query: 0, blocking: false, + overlaps: HashMap::default(), } } @@ -224,7 +227,24 @@ impl RowIndex { } } - pub(super) fn candidates(&mut self, cells: &[Vec], row: usize) -> Vec { + fn may_overlap(cell: &CellConstraint, earlier: &CellConstraint) -> bool { + match (Self::keys(cell), earlier) { + (Keys::Exact(_) | Keys::Numbers(_), CellConstraint::Opaque(_)) => false, + (Keys::Exact(set), CellConstraint::Known(earlier)) => earlier.intersects(set), + (Keys::Numbers(_), CellConstraint::Known(earlier)) => { + cell.known_set().is_some_and(|own| earlier.intersects(&own)) + } + _ => true, + } + } + + pub(super) fn candidates( + &mut self, + cells: &[Vec], + keys: &CellKeys<'_>, + row: usize, + ) -> Vec { + const REMEMBERED: usize = 1 << 20; let row_cells = &cells[row]; let driver = row_cells .iter() @@ -237,42 +257,52 @@ impl RowIndex { }; let mut out: Vec = Vec::new(); self.drive(driver, Self::keys(&row_cells[driver]), row, |e| out.push(e)); + let own = keys.row(row); + let overlaps = &mut self.overlaps; out.retain(|&e| { + let theirs = keys.row(e); row_cells.iter().enumerate().all(|(col, cell)| { - col == driver - || match (Self::keys(cell), &cells[e][col]) { - (Keys::Exact(_) | Keys::Numbers(_), CellConstraint::Opaque(_)) => false, - (Keys::Exact(set), CellConstraint::Known(earlier)) => { - earlier.intersects(set) - } - (Keys::Numbers(_), CellConstraint::Known(earlier)) => { - cell.known_set().is_some_and(|own| earlier.intersects(&own)) - } - _ => true, - } + if col == driver { + return true; + } + let pair = (col as u32, own[col], theirs[col]); + if let Some(&known) = overlaps.get(&pair) { + debug_assert_eq!(known, Self::may_overlap(cell, &cells[e][col])); + return known; + } + let found = Self::may_overlap(cell, &cells[e][col]); + if overlaps.len() < REMEMBERED { + overlaps.insert(pair, found); + } + found }) }); out.sort_unstable(); out } - pub(super) fn overlapping( + pub(super) fn overlapping>( &mut self, - region: &[ValueSet], + region: &[S], limit: usize, visit: impl FnMut(usize), ) -> bool { let driver = region .iter() .enumerate() - .filter_map(|(col, set)| Some((col, self.estimate(col, Self::set_keys(set))?))) + .filter_map(|(col, set)| Some((col, self.estimate(col, Self::set_keys(set.borrow()))?))) .min_by_key(|(_, size)| *size) .filter(|(_, size)| *size < limit) .map(|(col, _)| col); let Some(driver) = driver else { return false; }; - self.drive(driver, Self::set_keys(®ion[driver]), usize::MAX, visit); + self.drive( + driver, + Self::set_keys(region[driver].borrow()), + usize::MAX, + visit, + ); true } diff --git a/core/engine/src/analysis/table/intern.rs b/core/engine/src/analysis/table/intern.rs new file mode 100644 index 00000000..344ca3b7 --- /dev/null +++ b/core/engine/src/analysis/table/intern.rs @@ -0,0 +1,122 @@ +pub(super) struct Interner { + stride: usize, + data: Vec, + slots: Vec, + len: usize, +} + +impl> Default for Interner { + fn default() -> Self { + Self::new(0) + } +} + +impl> Interner { + const INITIAL_SLOTS: usize = 16; + + pub(super) fn new(stride: usize) -> Self { + Self { + stride, + data: Vec::new(), + slots: vec![0; Self::INITIAL_SLOTS], + len: 0, + } + } + + pub(super) fn reset(&mut self, stride: usize) { + self.stride = stride; + self.data.clear(); + self.slots.iter_mut().for_each(|slot| *slot = 0); + self.len = 0; + } + + pub(super) fn len(&self) -> usize { + self.len + } + + pub(super) fn stride(&self) -> usize { + self.stride + } + + pub(super) fn get(&self, id: u32) -> &[T] { + let start = id as usize * self.stride; + &self.data[start..start + self.stride] + } + + pub(super) fn intern(&mut self, key: &[T]) -> u32 { + debug_assert_eq!(key.len(), self.stride); + if (self.len + 1) * 2 > self.slots.len() { + self.grow(); + } + let mask = self.slots.len() - 1; + let mut slot = Self::hash(key) as usize & mask; + loop { + match self.slots[slot] { + 0 => { + let id = self.len as u32; + self.slots[slot] = id + 1; + self.data.extend_from_slice(key); + self.len += 1; + return id; + } + taken if self.get(taken - 1) == key => return taken - 1, + _ => slot = (slot + 1) & mask, + } + } + } + + fn grow(&mut self) { + let mask = self.slots.len() * 2 - 1; + let mut slots = vec![0u32; mask + 1]; + for id in 0..self.len as u32 { + let mut slot = Self::hash(self.get(id)) as usize & mask; + while slots[slot] != 0 { + slot = (slot + 1) & mask; + } + slots[slot] = id + 1; + } + self.slots = slots; + } + + fn hash(key: &[T]) -> u64 { + let mut hash: u64 = 0x9E37_79B9_7F4A_7C15; + for &part in key { + hash = (hash ^ part.into()).wrapping_mul(0xA24B_AED4_963E_E407); + hash ^= hash >> 29; + } + hash + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn interns_equal_keys_once_and_keeps_insertion_order() { + let mut interner: Interner = Interner::new(2); + let ids: Vec = (0..500u64) + .map(|i| interner.intern(&[i % 97, i % 3])) + .collect(); + assert_eq!(interner.len(), 97 * 3); + assert_eq!(ids[0], 0); + assert_eq!(ids[1], 1); + for (i, id) in ids.iter().enumerate() { + let i = i as u64; + assert_eq!(interner.get(*id), &[i % 97, i % 3]); + } + interner.reset(1); + assert_eq!(interner.len(), 0); + assert_eq!(interner.intern(&[7]), 0); + assert_eq!(interner.intern(&[7]), 0); + assert_eq!(interner.intern(&[8]), 1); + } + + #[test] + fn empty_keys_share_one_id() { + let mut interner: Interner = Interner::new(0); + assert_eq!(interner.intern(&[]), 0); + assert_eq!(interner.intern(&[]), 0); + assert_eq!(interner.len(), 1); + } +} diff --git a/core/engine/src/analysis/table/merge.rs b/core/engine/src/analysis/table/merge.rs index 74496cd1..bdee7e3a 100644 --- a/core/engine/src/analysis/table/merge.rs +++ b/core/engine/src/analysis/table/merge.rs @@ -1,22 +1,22 @@ -use std::collections::BTreeSet; -use std::rc::Rc; +use std::borrow::Cow; use std::sync::Arc; use ahash::HashMap; use super::cell::CellConstraint; use super::index::RowIndex; +use super::intern::Interner; use super::print::CellText; -use super::value_set::{StringSet, ValueSet}; +use super::value_set::{StringSet, Strings, ValueSet}; use super::verify::{Finding, HitMode, VerifyTable}; const COMPRESS_BUDGET: usize = 50_000_000; const MAX_ROUNDS: usize = 8; -#[derive(Clone)] -struct Row { - rule: HashMap, Arc>, - cells: Vec, +struct Row<'a> { + rule: Cow<'a, HashMap, Arc>>, + cells: Cow<'a, [CellConstraint]>, + output: u32, fixed: bool, barrier: bool, stale: Vec, @@ -41,26 +41,123 @@ impl Work { } } +pub(super) struct CellKeys<'c> { + columns: usize, + given: HashMap<&'c CellConstraint, u32>, + made: HashMap, + of: Vec, + pending: Vec, +} + +impl<'c> CellKeys<'c> { + const ANY: u32 = 0; + const PENDING: u32 = u32::MAX; + + pub(super) fn new(cells: &'c [Vec], columns: usize) -> Self { + let mut given: HashMap<&'c CellConstraint, u32> = HashMap::default(); + let mut of = Vec::with_capacity(cells.len() * columns); + for row in cells { + for cell in row { + of.push(match cell { + CellConstraint::Any => Self::ANY, + CellConstraint::Known(set) if set.is_all() => Self::ANY, + other => { + let next = given.len() as u32 + 1; + *given.entry(other).or_insert(next) + } + }); + } + } + Self { + columns, + given, + made: HashMap::default(), + of, + pending: Vec::new(), + } + } + + fn id(&mut self, cell: &CellConstraint) -> u32 { + match cell { + CellConstraint::Any => Self::ANY, + CellConstraint::Known(set) if set.is_all() => Self::ANY, + other => match self.given.get(other).or_else(|| self.made.get(other)) { + Some(&id) => id, + None => { + let id = (self.given.len() + self.made.len()) as u32 + 1; + self.made.insert(other.clone(), id); + id + } + }, + } + } + + pub(super) fn row(&self, row: usize) -> &[u32] { + &self.of[row * self.columns..(row + 1) * self.columns] + } + + fn touch(&mut self, row: usize, col: usize) { + let slot = row * self.columns + col; + if self.of[slot] != Self::PENDING { + self.of[slot] = Self::PENDING; + self.pending.push(slot); + } + } + + fn settle(&mut self, rows: &[Option]) { + for slot in std::mem::take(&mut self.pending) { + let (row, col) = (slot / self.columns, slot % self.columns); + self.of[slot] = match &rows[row] { + Some(row) => self.id(&row.cells[col]), + None => Self::ANY, + }; + } + } +} + impl VerifyTable<'_> { pub(super) fn compress( &self, cells: &[Vec], satisfiable: &[bool], warned: &[bool], + keys: CellKeys<'_>, + outputs: &[u32], + ) -> Option { + let found = self.compressed(cells, satisfiable, warned, keys, outputs); + #[cfg(test)] + assert_eq!( + found, + super::merge_reference::Legacy(self).compress(cells, satisfiable, warned), + "table compression diverged from the reference implementation" + ); + found + } + + fn compressed( + &self, + cells: &[Vec], + satisfiable: &[bool], + warned: &[bool], + mut keys: CellKeys, + outputs: &[u32], ) -> Option { if self.rules.len() < 2 { return None; } + let all = ValueSet::all(); let mut rows: Vec> = self .rules .iter() .zip(cells) .zip(satisfiable) .zip(warned) - .map(|(((rule, cells), satisfiable), warned)| { + .zip(outputs) + .map(|((((rule, cells), satisfiable), warned), &output)| { Some(Row { - rule: rule.clone(), - cells: cells.clone(), + rule: Cow::Borrowed(rule), + cells: Cow::Borrowed(cells.as_slice()), + output, fixed: !satisfiable || *warned, barrier: *warned, stale: Vec::new(), @@ -75,44 +172,37 @@ impl VerifyTable<'_> { for _ in 0..MAX_ROUNDS { let mut changed = false; if self.mode != HitMode::Collect { - changed |= self.drop_shadowed(&mut rows, &mut work, &mut index); - changed |= self.absorb(&mut rows, &mut work, &mut index); + changed |= self.drop_shadowed(&mut rows, &mut work, &mut index, &all); + changed |= self.absorb(&mut rows, &mut work, &mut index, &all); } for col in 0..self.inputs.len() { - changed |= self.merge_column(&mut rows, col, &mut work, &mut index); + changed |= + self.merge_column(&mut rows, col, &mut work, &mut index, &mut keys, &all); } if !changed || work.remaining == 0 { break; } } + if rows.iter().flatten().count() >= before { + return None; + } let rules: Vec<_> = rows .into_iter() .flatten() .map(|mut row| { for &col in &row.stale { if let CellConstraint::Known(set) = &row.cells[col] { - if let Some(text) = self.cell_text(col, set, &ValueSet::all(), false) { + if let Some(text) = self.cell_text(col, set, &all, false) { row.rule + .to_mut() .insert(self.inputs[col].id.clone(), Arc::from(text.as_str())); } } } - row.rule + row.rule.into_owned() }) .collect(); - (rules.len() < before).then_some(Finding::CompressibleTable { before, rules }) - } - - fn output_key(&self, row: &Row) -> Vec { - self.outputs - .iter() - .map(|col| { - row.rule - .get(&col.id) - .map(|c| c.trim().to_string()) - .unwrap_or_default() - }) - .collect() + Some(Finding::CompressibleTable { before, rules }) } fn collects(&self, row: &Row) -> bool { @@ -121,21 +211,17 @@ impl VerifyTable<'_> { .any(|col| col.collect && row.rule.get(&col.id).is_some_and(|c| !c.trim().is_empty())) } - fn cell_key(cell: &CellConstraint) -> CellConstraint { - match cell { - CellConstraint::Known(set) if set.is_all() => CellConstraint::Any, - other => other.clone(), - } - } - - fn region(row: &Row) -> Vec { + fn region<'r>(row: &'r Row, all: &'r ValueSet) -> Vec<&'r ValueSet> { row.cells .iter() - .map(|cell| cell.known_set().unwrap_or_else(ValueSet::all)) + .map(|cell| match cell { + CellConstraint::Known(set) => set, + _ => all, + }) .collect() } - fn catches(row: &Row, region: &[ValueSet]) -> bool { + fn catches(row: &Row, region: &[&ValueSet]) -> bool { row.cells .iter() .zip(region) @@ -149,7 +235,7 @@ impl VerifyTable<'_> { inner .cells .iter() - .zip(&outer.cells) + .zip(outer.cells.iter()) .all(|(a, b)| match (a, b) { (_, CellConstraint::Any) => true, (CellConstraint::Opaque(x), CellConstraint::Opaque(y)) => x == y, @@ -163,7 +249,7 @@ impl VerifyTable<'_> { rows: &[Option], from: usize, to: usize, - region: &[ValueSet], + region: &[&ValueSet], work: &mut Work, index: &mut RowIndex, ) -> bool { @@ -207,6 +293,7 @@ impl VerifyTable<'_> { rows: &mut [Option], work: &mut Work, index: &mut RowIndex, + all: &ValueSet, ) -> bool { if self.mode != HitMode::RowFirst { return false; @@ -225,7 +312,7 @@ impl VerifyTable<'_> { { continue; } - let region = Self::region(inner_row); + let region = Self::region(inner_row, all); let mut earlier: Vec = Vec::new(); let indexed = index.overlapping(®ion, inner, |e| { if e < inner { @@ -252,11 +339,17 @@ impl VerifyTable<'_> { changed } - fn absorb(&self, rows: &mut [Option], work: &mut Work, index: &mut RowIndex) -> bool { - let mut buckets: HashMap, Vec> = HashMap::default(); + fn absorb( + &self, + rows: &mut [Option], + work: &mut Work, + index: &mut RowIndex, + all: &ValueSet, + ) -> bool { + let mut buckets: HashMap> = HashMap::default(); for (idx, row) in rows.iter().enumerate() { if let Some(row) = row.as_ref().filter(|r| !r.fixed && !self.collects(r)) { - buckets.entry(self.output_key(row)).or_default().push(idx); + buckets.entry(row.output).or_default().push(idx); } } let mut changed = false; @@ -270,42 +363,45 @@ impl VerifyTable<'_> { } for (id, group) in groups.iter().enumerate() { for &inner in group { - let Some(inner_row) = rows[inner].as_ref() else { - continue; - }; - let region = Self::region(inner_row); - let mut outers: Vec = Vec::new(); - let indexed = index.overlapping(®ion, group.len(), |e| { - if group_of[e] == id { - outers.push(e); - } - }); - if indexed { - outers.sort_unstable(); - } else { - outers = group.clone(); - } - let mut absorbed = false; - for outer in outers { - if outer == inner { - continue; - } - if !work.spend(inner_row.cells.len()) { - return changed; - } - let Some(outer_row) = rows[outer].as_ref() else { + let absorbed = { + let Some(inner_row) = rows[inner].as_ref() else { continue; }; - if !Self::within(inner_row, outer_row) { - continue; + let region = Self::region(inner_row, all); + let mut outers: Vec = Vec::new(); + let indexed = index.overlapping(®ion, group.len(), |e| { + if group_of[e] == id { + outers.push(e); + } + }); + if indexed { + outers.sort_unstable(); + } else { + outers = group.clone(); } - if outer < inner - || Self::clear_between(rows, inner, outer, ®ion, work, index) - { - absorbed = true; - break; + let mut absorbed = false; + for outer in outers { + if outer == inner { + continue; + } + if !work.spend(inner_row.cells.len()) { + return changed; + } + let Some(outer_row) = rows[outer].as_ref() else { + continue; + }; + if !Self::within(inner_row, outer_row) { + continue; + } + if outer < inner + || Self::clear_between(rows, inner, outer, ®ion, work, index) + { + absorbed = true; + break; + } } - } + absorbed + }; if absorbed { rows[inner] = None; changed = true; @@ -315,44 +411,64 @@ impl VerifyTable<'_> { changed } + #[allow(clippy::too_many_arguments)] fn merge_column( &self, rows: &mut [Option], col: usize, work: &mut Work, index: &mut RowIndex, + keys: &mut CellKeys, + all: &ValueSet, ) -> bool { - let mut buckets: HashMap<(Vec, Vec), Vec> = - HashMap::default(); + let columns = self.inputs.len(); + keys.settle(rows); + let mut buckets: Interner = Interner::new(columns); + let mut key: Vec = Vec::with_capacity(columns); + let mut members: Vec<(u32, usize)> = Vec::new(); for (idx, row) in rows.iter().enumerate() { let Some(row) = row.as_ref().filter(|r| !r.fixed) else { continue; }; - if row.cells[col].known_set().is_none() { + if matches!(row.cells[col], CellConstraint::Opaque(_)) { continue; } if !work.spend(row.cells.len()) { return false; } - let others: Vec = row - .cells - .iter() - .enumerate() - .filter(|(i, _)| *i != col) - .map(|(_, cell)| Self::cell_key(cell)) - .collect(); - buckets - .entry((self.output_key(row), others)) - .or_default() - .push(idx); + key.clear(); + key.push(row.output); + key.extend( + keys.row(idx) + .iter() + .enumerate() + .filter(|(i, _)| *i != col) + .map(|(_, &id)| id), + ); + members.push((buckets.intern(&key), idx)); + } + let mut starts = vec![0usize; buckets.len() + 1]; + for &(bucket, _) in &members { + starts[bucket as usize + 1] += 1; + } + for bucket in 0..buckets.len() { + starts[bucket + 1] += starts[bucket]; + } + let mut cursor = starts.clone(); + let mut grouped = vec![0usize; members.len()]; + for &(bucket, idx) in &members { + grouped[cursor[bucket as usize]] = idx; + cursor[bucket as usize] += 1; } let mut changed = false; - let mut groups: Vec> = buckets.into_values().filter(|g| g.len() > 1).collect(); - groups.sort_unstable_by_key(|g| g[0]); - for group in groups { + for bucket in 0..buckets.len() { + let group = &grouped[starts[bucket]..starts[bucket + 1]]; + if group.len() < 2 { + continue; + } let mut keep = group[0]; for &next in &group[1..] { - if self.merge_into(rows, keep, next, col, work, index) { + if self.merge_into(rows, keep, next, col, work, index, keys, all) { changed = true; } else { keep = next; @@ -365,6 +481,7 @@ impl VerifyTable<'_> { changed } + #[allow(clippy::too_many_arguments)] fn merge_into( &self, rows: &mut [Option], @@ -373,6 +490,8 @@ impl VerifyTable<'_> { col: usize, work: &mut Work, index: &mut RowIndex, + keys: &mut CellKeys, + all: &ValueSet, ) -> bool { let (Some(keep_row), Some(next_row)) = (rows[keep].as_ref(), rows[next].as_ref()) else { return false; @@ -387,30 +506,31 @@ impl VerifyTable<'_> { { return false; } - let fresh: BTreeSet> = - b.iter().filter(|key| !a.contains(*key)).cloned().collect(); + let fresh: Strings = b.iter().filter(|key| !a.contains(key)).cloned().collect(); if fresh.iter().any(|key| CellText::string(key).is_none()) { return false; } - let mut moved = Self::region(next_row); - moved[col] = ValueSet { + let added = ValueSet { strings: StringSet::Finite(fresh.clone()), ..ValueSet::empty() }; + let mut moved = Self::region(next_row, all); + moved[col] = &added; if !Self::clear_between(rows, keep, next, &moved, work, index) { return false; } if let Some(row) = rows[keep].as_mut() { if let CellConstraint::Known(ValueSet { - strings: StringSet::Finite(keys), + strings: StringSet::Finite(members), .. - }) = &mut row.cells[col] + }) = &mut row.cells.to_mut()[col] { - keys.extend(fresh.iter().cloned()); + members.extend(fresh.iter().cloned()); } if !row.stale.contains(&col) { row.stale.push(col); } + keys.touch(keep, col); index.insert_strings(col, &fresh, keep); } rows[next] = None; @@ -425,35 +545,33 @@ impl VerifyTable<'_> { if (self.mode == HitMode::Collect || self.collects(keep_row)) && a.intersects(&b) { return false; } - let moved: Vec = Self::region(next_row) - .into_iter() - .enumerate() - .map(|(idx, set)| if idx == col { set.difference(&a) } else { set }) - .collect(); + let outside = b.difference(&a); + let mut moved = Self::region(next_row, all); + moved[col] = &outside; if !Self::clear_between(rows, keep, next, &moved, work, index) { return false; } let union = a.union(&b); - let Some(text) = self.cell_text(col, &union, &ValueSet::all(), self.inputs[col].dated) - else { + let Some(text) = self.cell_text(col, &union, all, self.inputs[col].dated) else { return false; }; let id = self.inputs[col].id.clone(); if let Some(row) = rows[keep].as_mut() { - row.rule.insert(id, Arc::from(text.as_str())); + row.rule.to_mut().insert(id, Arc::from(text.as_str())); row.stale.retain(|&stale| stale != col); - row.cells[col] = if text.is_empty() { + row.cells.to_mut()[col] = if text.is_empty() { CellConstraint::Any } else { CellConstraint::Known(union) }; + keys.touch(keep, col); index.insert(&row.cells, keep); } rows[next] = None; true } - fn plain(cell: &CellConstraint) -> Option<&BTreeSet>> { + fn plain(cell: &CellConstraint) -> Option<&Strings> { match cell { CellConstraint::Known(set) if set.numbers.is_empty() && set.bools == 0 && !set.null && !set.other => @@ -481,7 +599,12 @@ impl VerifyTable<'_> { let (CellConstraint::Known(set), Some(domain)) = (cell, &col.domain) else { continue; }; - if !domain.is_empty() && domain.difference(set).is_empty() { + debug_assert_eq!( + domain.is_subset(set), + domain.difference(set).is_empty(), + "subset check disagrees with the difference for {set:?}" + ); + if !domain.is_empty() && domain.is_subset(set) { findings.push(Finding::CellCoversDomain { row, col: col.id.clone(), diff --git a/core/engine/src/analysis/table/merge_reference.rs b/core/engine/src/analysis/table/merge_reference.rs new file mode 100644 index 00000000..61889af0 --- /dev/null +++ b/core/engine/src/analysis/table/merge_reference.rs @@ -0,0 +1,474 @@ +use std::sync::Arc; + +use ahash::HashMap; + +use super::cell::CellConstraint; +use super::index::RowIndex; +use super::print::CellText; +use super::value_set::{StringSet, Strings, ValueSet}; +use super::verify::{Finding, HitMode, VerifyTable}; + +const COMPRESS_BUDGET: usize = 50_000_000; +const MAX_ROUNDS: usize = 8; + +#[derive(Clone)] +struct Row { + rule: HashMap, Arc>, + cells: Vec, + fixed: bool, + barrier: bool, + stale: Vec, +} + +struct Work { + remaining: usize, +} + +impl Work { + fn spend(&mut self, amount: usize) -> bool { + match self.remaining.checked_sub(amount.max(1)) { + Some(left) => { + self.remaining = left; + true + } + None => { + self.remaining = 0; + false + } + } + } +} + +pub(super) struct Legacy<'t, 'r>(pub(super) &'t VerifyTable<'r>); + +impl Legacy<'_, '_> { + pub(super) fn compress( + &self, + cells: &[Vec], + satisfiable: &[bool], + warned: &[bool], + ) -> Option { + if self.0.rules.len() < 2 { + return None; + } + let mut rows: Vec> = self + .0 + .rules + .iter() + .zip(cells) + .zip(satisfiable) + .zip(warned) + .map(|(((rule, cells), satisfiable), warned)| { + Some(Row { + rule: rule.clone(), + cells: cells.clone(), + fixed: !satisfiable || *warned, + barrier: *warned, + stale: Vec::new(), + }) + }) + .collect(); + let before = rows.len(); + let mut work = Work { + remaining: COMPRESS_BUDGET, + }; + let mut index = RowIndex::blocking(cells, self.0.inputs.len()); + for _ in 0..MAX_ROUNDS { + let mut changed = false; + if self.0.mode != HitMode::Collect { + changed |= self.drop_shadowed(&mut rows, &mut work, &mut index); + changed |= self.absorb(&mut rows, &mut work, &mut index); + } + for col in 0..self.0.inputs.len() { + changed |= self.merge_column(&mut rows, col, &mut work, &mut index); + } + if !changed || work.remaining == 0 { + break; + } + } + let rules: Vec<_> = rows + .into_iter() + .flatten() + .map(|mut row| { + for &col in &row.stale { + if let CellConstraint::Known(set) = &row.cells[col] { + if let Some(text) = self.0.cell_text(col, set, &ValueSet::all(), false) { + row.rule + .insert(self.0.inputs[col].id.clone(), Arc::from(text.as_str())); + } + } + } + row.rule + }) + .collect(); + (rules.len() < before).then_some(Finding::CompressibleTable { before, rules }) + } + + fn output_key(&self, row: &Row) -> Vec { + self.0 + .outputs + .iter() + .map(|col| { + row.rule + .get(&col.id) + .map(|c| c.trim().to_string()) + .unwrap_or_default() + }) + .collect() + } + + fn collects(&self, row: &Row) -> bool { + self.0 + .outputs + .iter() + .any(|col| col.collect && row.rule.get(&col.id).is_some_and(|c| !c.trim().is_empty())) + } + + fn cell_key(cell: &CellConstraint) -> CellConstraint { + match cell { + CellConstraint::Known(set) if set.is_all() => CellConstraint::Any, + other => other.clone(), + } + } + + fn region(row: &Row) -> Vec { + row.cells + .iter() + .map(|cell| cell.known_set().unwrap_or_else(ValueSet::all)) + .collect() + } + + fn catches(row: &Row, region: &[ValueSet]) -> bool { + row.cells + .iter() + .zip(region) + .all(|(cell, wanted)| match cell { + CellConstraint::Known(set) => set.intersects(wanted), + _ => !wanted.is_empty(), + }) + } + + fn within(inner: &Row, outer: &Row) -> bool { + inner + .cells + .iter() + .zip(&outer.cells) + .all(|(a, b)| match (a, b) { + (_, CellConstraint::Any) => true, + (CellConstraint::Opaque(x), CellConstraint::Opaque(y)) => x == y, + (CellConstraint::Opaque(_), _) | (_, CellConstraint::Opaque(_)) => false, + (CellConstraint::Known(a), CellConstraint::Known(b)) => a.is_subset(b), + (CellConstraint::Any, CellConstraint::Known(b)) => b.is_all(), + }) + } + + fn clear_between( + rows: &[Option], + from: usize, + to: usize, + region: &[ValueSet], + work: &mut Work, + index: &mut RowIndex, + ) -> bool { + let (low, high) = (from.min(to), from.max(to)); + if !work.spend(high - low) + || rows[low + 1..high] + .iter() + .flatten() + .any(|between| between.barrier) + { + return false; + } + let mut visited = 0usize; + let mut clear = true; + let indexed = index.overlapping(region, to.saturating_sub(from), |e| { + visited += 1; + if clear && from < e && e < to { + if let Some(between) = &rows[e] { + clear = !Self::catches(between, region); + } + } + }); + if indexed { + return work.spend(visited) && clear; + } + if !work.spend(to.saturating_sub(from)) { + return false; + } + rows[from + 1..to] + .iter() + .flatten() + .all(|between| !Self::catches(between, region)) + } + + fn fills(row: &Row, id: &Arc) -> bool { + row.rule.get(id).is_some_and(|c| !c.trim().is_empty()) + } + + fn drop_shadowed( + &self, + rows: &mut [Option], + work: &mut Work, + index: &mut RowIndex, + ) -> bool { + if self.0.mode != HitMode::RowFirst { + return false; + } + let mut changed = false; + for inner in 1..rows.len() { + let shadowed = { + let Some(inner_row) = rows[inner].as_ref() else { + continue; + }; + if inner_row.fixed + || self + .0 + .outputs + .iter() + .any(|col| Self::fills(inner_row, &col.id)) + { + continue; + } + let region = Self::region(inner_row); + let mut earlier: Vec = Vec::new(); + let indexed = index.overlapping(®ion, inner, |e| { + if e < inner { + earlier.push(e); + } + }); + if !indexed { + earlier = (0..inner).collect(); + } + if !work.spend(earlier.len()) { + return changed; + } + earlier.iter().any(|&e| { + rows[e] + .as_ref() + .is_some_and(|outer| !outer.fixed && Self::within(inner_row, outer)) + }) + }; + if shadowed { + rows[inner] = None; + changed = true; + } + } + changed + } + + fn absorb(&self, rows: &mut [Option], work: &mut Work, index: &mut RowIndex) -> bool { + let mut buckets: HashMap, Vec> = HashMap::default(); + for (idx, row) in rows.iter().enumerate() { + if let Some(row) = row.as_ref().filter(|r| !r.fixed && !self.collects(r)) { + buckets.entry(self.output_key(row)).or_default().push(idx); + } + } + let mut changed = false; + let mut groups: Vec> = buckets.into_values().filter(|g| g.len() > 1).collect(); + groups.sort_unstable_by_key(|g| g[0]); + let mut group_of: Vec = vec![usize::MAX; rows.len()]; + for (id, group) in groups.iter().enumerate() { + for &row in group { + group_of[row] = id; + } + } + for (id, group) in groups.iter().enumerate() { + for &inner in group { + let Some(inner_row) = rows[inner].as_ref() else { + continue; + }; + let region = Self::region(inner_row); + let mut outers: Vec = Vec::new(); + let indexed = index.overlapping(®ion, group.len(), |e| { + if group_of[e] == id { + outers.push(e); + } + }); + if indexed { + outers.sort_unstable(); + } else { + outers = group.clone(); + } + let mut absorbed = false; + for outer in outers { + if outer == inner { + continue; + } + if !work.spend(inner_row.cells.len()) { + return changed; + } + let Some(outer_row) = rows[outer].as_ref() else { + continue; + }; + if !Self::within(inner_row, outer_row) { + continue; + } + if outer < inner + || Self::clear_between(rows, inner, outer, ®ion, work, index) + { + absorbed = true; + break; + } + } + if absorbed { + rows[inner] = None; + changed = true; + } + } + } + changed + } + + fn merge_column( + &self, + rows: &mut [Option], + col: usize, + work: &mut Work, + index: &mut RowIndex, + ) -> bool { + let mut buckets: HashMap<(Vec, Vec), Vec> = + HashMap::default(); + for (idx, row) in rows.iter().enumerate() { + let Some(row) = row.as_ref().filter(|r| !r.fixed) else { + continue; + }; + if row.cells[col].known_set().is_none() { + continue; + } + if !work.spend(row.cells.len()) { + return false; + } + let others: Vec = row + .cells + .iter() + .enumerate() + .filter(|(i, _)| *i != col) + .map(|(_, cell)| Self::cell_key(cell)) + .collect(); + buckets + .entry((self.output_key(row), others)) + .or_default() + .push(idx); + } + let mut changed = false; + let mut groups: Vec> = buckets.into_values().filter(|g| g.len() > 1).collect(); + groups.sort_unstable_by_key(|g| g[0]); + for group in groups { + let mut keep = group[0]; + for &next in &group[1..] { + if self.merge_into(rows, keep, next, col, work, index) { + changed = true; + } else { + keep = next; + } + if work.remaining == 0 { + return changed; + } + } + } + changed + } + + fn merge_into( + &self, + rows: &mut [Option], + keep: usize, + next: usize, + col: usize, + work: &mut Work, + index: &mut RowIndex, + ) -> bool { + let (Some(keep_row), Some(next_row)) = (rows[keep].as_ref(), rows[next].as_ref()) else { + return false; + }; + if let (false, Some(a), Some(b)) = ( + self.0.inputs[col].dated, + Self::plain(&keep_row.cells[col]), + Self::plain(&next_row.cells[col]), + ) { + if (self.0.mode == HitMode::Collect || self.collects(keep_row)) + && b.iter().any(|key| a.contains(key)) + { + return false; + } + let fresh: Strings = b.iter().filter(|key| !a.contains(key)).cloned().collect(); + if fresh.iter().any(|key| CellText::string(key).is_none()) { + return false; + } + let mut moved = Self::region(next_row); + moved[col] = ValueSet { + strings: StringSet::Finite(fresh.clone()), + ..ValueSet::empty() + }; + if !Self::clear_between(rows, keep, next, &moved, work, index) { + return false; + } + if let Some(row) = rows[keep].as_mut() { + if let CellConstraint::Known(ValueSet { + strings: StringSet::Finite(keys), + .. + }) = &mut row.cells[col] + { + keys.extend(fresh.iter().cloned()); + } + if !row.stale.contains(&col) { + row.stale.push(col); + } + index.insert_strings(col, &fresh, keep); + } + rows[next] = None; + return true; + } + let (Some(a), Some(b)) = ( + keep_row.cells[col].known_set(), + next_row.cells[col].known_set(), + ) else { + return false; + }; + if (self.0.mode == HitMode::Collect || self.collects(keep_row)) && a.intersects(&b) { + return false; + } + let moved: Vec = Self::region(next_row) + .into_iter() + .enumerate() + .map(|(idx, set)| if idx == col { set.difference(&a) } else { set }) + .collect(); + if !Self::clear_between(rows, keep, next, &moved, work, index) { + return false; + } + let union = a.union(&b); + let Some(text) = self + .0 + .cell_text(col, &union, &ValueSet::all(), self.0.inputs[col].dated) + else { + return false; + }; + let id = self.0.inputs[col].id.clone(); + if let Some(row) = rows[keep].as_mut() { + row.rule.insert(id, Arc::from(text.as_str())); + row.stale.retain(|&stale| stale != col); + row.cells[col] = if text.is_empty() { + CellConstraint::Any + } else { + CellConstraint::Known(union) + }; + index.insert(&row.cells, keep); + } + rows[next] = None; + true + } + + fn plain(cell: &CellConstraint) -> Option<&Strings> { + match cell { + CellConstraint::Known(set) + if set.numbers.is_empty() && set.bools == 0 && !set.null && !set.other => + { + match &set.strings { + StringSet::Finite(keys) if !keys.is_empty() => Some(keys), + _ => None, + } + } + _ => None, + } + } +} diff --git a/core/engine/src/analysis/table/missing.rs b/core/engine/src/analysis/table/missing.rs index 2dbbd537..00c35111 100644 --- a/core/engine/src/analysis/table/missing.rs +++ b/core/engine/src/analysis/table/missing.rs @@ -2,29 +2,28 @@ use std::sync::Arc; use std::rc::Rc; -use ahash::HashMap; -use serde_json::{Map, Value}; +use ahash::{HashMap, RandomState}; use zen_expression::intellisense::values::cell::FieldPath; use zen_expression::intellisense::{IntelliSense, ReadDependency}; use super::cell::CellConstraint; +use super::gaps::{Bits, Dense, Gaps, Space}; +use super::intern::Interner; use super::partition::Partition; -use super::print::{CellText, DateDay}; use super::value_set::{NumberSet, StringSet, ValueKind, ValueSet}; -use super::verify::{Finding, GapCase, Region, VerifyTable, MAX_FRAGMENTS}; +use super::verify::{Finding, GapAxis, GapTable, GapValues, VerifyTable}; const GAP_BUDGET: usize = 10_000_000; -const DIRECT_ROWS: usize = 8; -struct Dimension { - columns: Vec, - domain: ValueSet, - path: Option>, - label: Arc, - prefer: Option, - dated: bool, - integer: bool, - input: bool, +pub(super) struct Dimension { + pub(super) columns: Vec, + pub(super) domain: ValueSet, + pub(super) path: Option>, + pub(super) label: Arc, + pub(super) prefer: Option, + pub(super) dated: bool, + pub(super) integer: bool, + pub(super) input: bool, } struct Field { @@ -64,6 +63,127 @@ impl Field { } } +pub(super) enum Pool { + Patterns { + patterns: Interner, + unions: HashMap<(u32, u32), u32>, + joined: Vec, + }, + Sets { + sets: Vec, + index: HashMap<(u64, u32), u32>, + unions: HashMap<(u32, u32), u32>, + }, +} + +impl Pool { + pub(super) fn sets(sets: Vec, index: HashMap<(u64, u32), u32>) -> Self { + Pool::Sets { + sets, + index, + unions: HashMap::default(), + } + } + + fn patterns(patterns: Interner) -> Self { + Pool::Patterns { + patterns, + unions: HashMap::default(), + joined: Vec::new(), + } + } + + fn len(&self) -> usize { + match self { + Pool::Patterns { patterns, .. } => patterns.len(), + Pool::Sets { sets, .. } => sets.len(), + } + } + + fn is_empty(&self, value: u32) -> bool { + match self { + Pool::Patterns { .. } => false, + Pool::Sets { sets, .. } => sets[value as usize].is_empty(), + } + } + + pub(super) fn intern( + sets: &mut Vec, + index: &mut HashMap<(u64, u32), u32>, + set: ValueSet, + ) -> u32 { + let hash = RandomState::with_seeds(11, 13, 17, 19).hash_one(&set); + let mut probe = 0u32; + loop { + match index.get(&(hash, probe)) { + Some(&id) if sets[id as usize] == set => return id, + Some(_) => probe += 1, + None => { + let id = sets.len() as u32; + index.insert((hash, probe), id); + sets.push(set); + return id; + } + } + } + } + + fn union(&mut self, a: u32, b: u32) -> u32 { + match self { + Pool::Patterns { + patterns, + unions, + joined, + } => { + if let Some(&id) = unions.get(&(a, b)) { + return id; + } + joined.clear(); + joined.extend( + patterns + .get(a) + .iter() + .zip(patterns.get(b)) + .map(|(left, right)| left | right), + ); + let id = patterns.intern(joined); + unions.insert((a, b), id); + id + } + Pool::Sets { + sets, + index, + unions, + } => { + if let Some(&id) = unions.get(&(a, b)) { + return id; + } + let joined = sets[a as usize].union(&sets[b as usize]); + let id = Self::intern(sets, index, joined); + unions.insert((a, b), id); + id + } + } + } + + fn keep(self, used: &[u32]) -> GapValues { + match self { + Pool::Patterns { patterns, .. } => GapValues::Patterns { + words: patterns.stride(), + data: used + .iter() + .flat_map(|&value| patterns.get(value).iter().copied()) + .collect(), + }, + Pool::Sets { mut sets, .. } => GapValues::Sets( + used.iter() + .map(|&value| std::mem::take(&mut sets[value as usize])) + .collect(), + ), + } + } +} + impl VerifyTable<'_> { pub(super) fn missing( &self, @@ -78,60 +198,226 @@ impl VerifyTable<'_> { if dims.is_empty() || dims.iter().any(|d| d.domain.is_empty()) { return Some(None); } - let cuts: Vec = cells + match self.missing_dense(dims, cells, satisfiable) { + Err(dims) => self.missing_sets(dims, cells, satisfiable), + Ok(found) => { + #[cfg(test)] + { + let cases = |found: &Option>| match found { + Some(Some(Finding::MissingCases { cases, total })) => { + Some(Some((cases.cases().collect::>(), *total))) + } + Some(_) => Some(None), + None => None, + }; + let expected = + self.missing_sets(self.dimensions(is, cells), cells, satisfiable); + assert_eq!( + cases(&found), + cases(&expected), + "gap analysis diverged between the dense and set-based paths" + ); + } + found + } + } + } + + fn gap_axis(&self, dim: Dimension, atoms: Vec, values: GapValues) -> GapAxis { + let first = dim.columns.first().map(|&first| &self.inputs[first]); + GapAxis { + label: dim.label, + column: first.map(|input| input.id.clone()), + subject: first + .and_then(|input| input.subject.as_ref()) + .map(|subject| subject.join(".")), + path: dim.path, + input: dim.input, + dated: dim.dated, + prefer: dim.prefer, + domain: dim.domain, + atoms, + values, + } + } + + fn missing_dense( + &self, + dims: Vec, + cells: &[Vec], + satisfiable: &[bool], + ) -> Result>, Vec> { + let rows: Vec<&Vec> = cells .iter() .zip(satisfiable) .filter(|(_, satisfiable)| **satisfiable) - .map(|(row_cells, _)| { - dims.iter() - .map(|d| { - d.columns - .iter() - .fold(ValueSet::all(), |acc, &col| match &row_cells[col] { + .map(|(row_cells, _)| row_cells) + .collect(); + + let atoms = dims.iter().map(|dim| { + let mentioned = rows.iter().flat_map(|row_cells| { + dim.columns.iter().filter_map(|&col| match &row_cells[col] { + CellConstraint::Known(set) => Some(set), + _ => None, + }) + }); + Dense::atoms(mentioned.chain(std::iter::once(&dim.domain))) + }); + if !Dense::fits(rows.len(), atoms) { + return Err(dims); + } + + let mut cut_of_row: Vec> = Vec::with_capacity(dims.len()); + let mut cut_sets: Vec> = Vec::with_capacity(dims.len()); + for dim in &dims { + let mut index: HashMap = HashMap::default(); + let mut distinct: Vec = Vec::new(); + let of_row: Vec = rows + .iter() + .map(|row_cells| { + let cut = + dim.columns.iter().fold(ValueSet::all(), |acc, &col| { + match &row_cells[col] { CellConstraint::Known(set) => acc.intersect(set), _ => acc, - }) - }) - .collect() - }) - .collect(); - let mut gaps = Gaps { - cuts: &cuts, - work: GAP_BUDGET, - out: Vec::new(), - }; - gaps.uncovered( - dims.iter().map(|d| d.domain.clone()).collect(), - (0..cuts.len()).collect(), - )?; - let remaining: Vec = gaps - .out - .into_iter() - .filter_map(|mut fragment| { - for (dim, set) in dims.iter().zip(fragment.iter_mut()) { - if dim.integer { - set.numbers = set.numbers.integral(); + } + }); + match index.get(&cut) { + Some(&id) => id, + None => { + let id = distinct.len() as u32; + index.insert(cut.clone(), id); + distinct.push(cut); + id + } } - } - fragment - .iter() - .all(|set| !set.is_empty()) - .then_some(fragment) - }) - .collect(); - if remaining.is_empty() { - return Some(None); + }) + .collect(); + distinct.push(dim.domain.clone()); + cut_of_row.push(of_row); + cut_sets.push(distinct); } - let remaining = Self::merge(remaining); - let total = remaining.len(); - let cases = remaining - .iter() - .map(|fragment| self.case(&dims, fragment)) - .collect(); - Some(Some(Finding::MissingCases { cases, total })) + let mut partitions: Vec = Vec::with_capacity(dims.len()); + let mut cut_atoms: Vec>> = Vec::with_capacity(dims.len()); + for (dim, sets) in dims.iter().zip(&cut_sets) { + let partition = Partition::new(&dim.domain, sets); + cut_atoms.push( + sets[..sets.len() - 1] + .iter() + .map(|cut| partition.touching(cut)) + .collect(), + ); + partitions.push(partition); + } + drop(cut_sets); + + let space = Space::new(partitions.iter().map(Partition::layout).collect()); + let stride = space.stride(); + let mut cuts = vec![0u64; rows.len() * stride]; + for ((axis, of_row), atoms) in space.axes().iter().zip(&cut_of_row).zip(&cut_atoms) { + for (row, &id) in of_row.iter().enumerate() { + let start = row * stride; + let words = &mut cuts[start..start + stride][axis.range()]; + atoms[id as usize] + .iter() + .for_each(|&atom| Bits::set(words, atom)); + } + } + drop(cut_of_row); + drop(cut_atoms); + + let Some(found) = Gaps::new(&space, &cuts, GAP_BUDGET).run(rows.len()) else { + return Ok(None); + }; + drop(cuts); + + let width = dims.len(); + let mut pools: Vec = Vec::with_capacity(width); + let mut value_of: Vec>> = Vec::with_capacity(width); + for ((dim, partition), patterns) in dims.iter().zip(&partitions).zip(found.patterns) { + if !dim.integer { + pools.push(Pool::patterns(patterns)); + value_of.push(None); + continue; + } + let mut sets: Vec = Vec::new(); + let mut index: HashMap<(u64, u32), u32> = HashMap::default(); + let atoms = partition.atoms(); + let values = (0..patterns.len() as u32) + .map(|pattern| { + let mut set = Partition::union( + Bits::ones(patterns.get(pattern)).map(|atom| &atoms[atom]), + ); + set.numbers = set.numbers.integral(); + Pool::intern(&mut sets, &mut index, set) + }) + .collect(); + pools.push(Pool::sets(sets, index)); + value_of.push(Some(values)); + } + + let mut remaining: Vec = Vec::with_capacity(found.fragments.len()); + for fragment in found.fragments.chunks_exact(width) { + let start = remaining.len(); + remaining.extend(fragment.iter().zip(&value_of).map( + |(&pattern, values)| match values { + Some(values) => values[pattern as usize], + None => pattern, + }, + )); + let empty = remaining[start..] + .iter() + .zip(&pools) + .any(|(&value, pool)| pool.is_empty(value)); + if empty { + remaining.truncate(start); + } + } + drop(found.fragments); + drop(value_of); + if remaining.is_empty() { + return Ok(Some(None)); + } + + let atoms = partitions.into_iter().map(Partition::into_atoms).collect(); + Ok(Some(Some( + self.missing_cases_of(dims, atoms, pools, remaining), + ))) } - fn dimensions(&self, is: &mut IntelliSense, cells: &[Vec]) -> Vec { + pub(super) fn missing_cases_of( + &self, + dims: Vec, + atoms: Vec>, + mut pools: Vec, + remaining: Vec, + ) -> Finding { + let width = dims.len(); + let mut rows = Self::merge(remaining, &mut pools); + let total = rows.len() / width; + let mut axes: Vec = Vec::with_capacity(width); + for (index, ((dim, atoms), pool)) in dims.into_iter().zip(atoms).zip(pools).enumerate() { + let mut renamed = vec![u32::MAX; pool.len()]; + let mut used: Vec = Vec::new(); + for row in rows.chunks_exact_mut(width) { + let value = row[index] as usize; + if renamed[value] == u32::MAX { + renamed[value] = used.len() as u32; + used.push(value as u32); + } + row[index] = renamed[value]; + } + axes.push(self.gap_axis(dim, atoms, pool.keep(&used))); + } + let cases = Rc::new(GapTable { axes, rows }); + Finding::MissingCases { cases, total } + } + + pub(super) fn dimensions( + &self, + is: &mut IntelliSense, + cells: &[Vec], + ) -> Vec { let fields: Vec> = self .inputs .iter() @@ -214,30 +500,28 @@ impl VerifyTable<'_> { (!domain.is_empty()).then_some(domain) } - fn merge(mut fragments: Vec) -> Vec { - let dims = fragments.first().map_or(0, Vec::len); + fn merge(mut fragments: Vec, pools: &mut [Pool]) -> Vec { + let width = pools.len(); + let mut keys: Interner = Interner::new(width - 1); + let mut key: Vec = Vec::with_capacity(width); loop { let mut changed = false; - for dim in (0..dims).rev() { - let mut buckets: HashMap, usize> = HashMap::default(); - let mut merged: Vec = Vec::with_capacity(fragments.len()); - for fragment in fragments.drain(..) { - let key: Vec = fragment - .iter() - .enumerate() - .filter(|(idx, _)| *idx != dim) - .map(|(_, set)| set.clone()) - .collect(); - match buckets.get(&key) { - Some(&idx) => { - merged[idx][dim] = merged[idx][dim].union(&fragment[dim]); - changed = true; - } - None => { - buckets.insert(key, merged.len()); - merged.push(fragment); - } + for dim in (0..width).rev() { + keys.reset(width - 1); + let mut merged: Vec = Vec::with_capacity(fragments.len()); + for fragment in fragments.chunks_exact(width) { + key.clear(); + key.extend_from_slice(&fragment[..dim]); + key.extend_from_slice(&fragment[dim + 1..]); + let known = keys.len() as u32; + let slot = keys.intern(&key) as usize; + if slot as u32 == known { + merged.extend_from_slice(fragment); + continue; } + let at = slot * width + dim; + merged[at] = pools[dim].union(merged[at], fragment[dim]); + changed = true; } fragments = merged; } @@ -246,200 +530,4 @@ impl VerifyTable<'_> { } } } - - fn case(&self, dims: &[Dimension], fragment: &Region) -> GapCase { - let mut parts = Vec::new(); - let mut cells = Some(Vec::new()); - let mut example = Some(Map::new()); - for (dim, set) in dims.iter().zip(fragment) { - match CellText::of(set, &dim.domain, dim.dated) { - Some(text) if text.is_empty() => continue, - Some(text) => { - if !dim.input { - example = None; - } - if let (Some(list), Some(&first)) = (cells.as_mut(), dim.columns.first()) { - match self.cell_text(first, set, &dim.domain, dim.dated) { - Some(cell) => list.push((self.inputs[first].id.clone(), cell)), - None => cells = None, - } - } - parts.push((dim.label.clone(), text)); - } - None => { - cells = None; - parts.push((dim.label.clone(), "…".to_string())); - } - } - let value = match dim.dated { - true => DateDay::example(set), - false => set.example(dim.prefer), - }; - match (&dim.path, value, example.as_mut()) { - (Some(path), Some(value), Some(root)) => Self::insert(root, path, value), - _ => example = None, - } - } - GapCase { - parts, - cells, - example: example.filter(|root| !root.is_empty()).map(Value::Object), - } - } -} - -type Atoms = Vec<(ValueSet, Vec)>; - -struct Split { - dim: usize, - score: usize, - groups: Atoms, - of_row: Vec, - distinct: usize, -} - -struct Gaps<'c> { - cuts: &'c [Region], - work: usize, - out: Vec, -} - -impl Gaps<'_> { - fn spend(&mut self, amount: usize) -> Option<()> { - self.work = self.work.checked_sub(amount.max(1))?; - Some(()) - } - - fn uncovered(&mut self, region: Region, rows: Vec) -> Option<()> { - self.spend(rows.len() * region.len())?; - let rows: Vec = rows - .into_iter() - .filter(|&row| { - self.cuts[row] - .iter() - .zip(®ion) - .all(|(cut, set)| cut.intersects(set)) - }) - .collect(); - if rows.is_empty() { - self.out.push(region); - return Some(()); - } - let covered = rows.iter().any(|&row| { - region - .iter() - .zip(&self.cuts[row]) - .all(|(set, cut)| set.is_subset(cut)) - }); - if covered { - return Some(()); - } - if rows.len() > DIRECT_ROWS { - if let Some((dim, atoms)) = self.split(®ion, &rows) { - for (atom, atom_rows) in atoms { - let mut piece = region.clone(); - piece[dim] = atom; - self.uncovered(piece, atom_rows)?; - } - return Some(()); - } - } - self.subtract_all(region, &rows) - } - - fn subtract_all(&mut self, region: Region, rows: &[usize]) -> Option<()> { - let mut remaining = vec![region]; - let cuts = self.cuts; - for &row in rows { - let cut: Vec<&ValueSet> = cuts[row].iter().collect(); - let mut next = Vec::with_capacity(remaining.len()); - for fragment in remaining { - self.spend(fragment.len())?; - match VerifyTable::subtract(&fragment, &cut) { - Some(pieces) => next.extend(pieces), - None => next.push(fragment), - } - } - if next.len() > MAX_FRAGMENTS { - return None; - } - remaining = next; - if remaining.is_empty() { - return Some(()); - } - } - self.out.extend(remaining); - Some(()) - } - - fn split(&mut self, region: &Region, rows: &[usize]) -> Option<(usize, Atoms)> { - let mut best: Option = None; - for (dim, bounds) in region.iter().enumerate() { - let mut sets: Vec = Vec::new(); - let mut index: HashMap = HashMap::default(); - let mut of_row: Vec = Vec::with_capacity(rows.len()); - for &row in rows { - let set = self.cuts[row][dim].intersect(bounds); - let next = sets.len(); - let slot = *index.entry(set.clone()).or_insert(next); - if slot == next { - sets.push(set); - } - of_row.push(slot); - } - if sets.iter().all(|set| set == bounds) { - continue; - } - let partition = Partition::new(bounds, &sets); - if partition.touches(&sets) > self.work { - return None; - } - let groups = partition.groups(&sets); - if groups.len() < 2 { - continue; - } - let mut count = vec![0usize; sets.len()]; - for &slot in &of_row { - count[slot] += 1; - } - let score: usize = groups - .iter() - .map(|(_, ids)| ids.iter().map(|&id| count[id]).sum::()) - .sum(); - self.spend(score + groups.len())?; - if best.as_ref().is_none_or(|split| score < split.score) { - best = Some(Split { - dim, - score, - groups, - of_row, - distinct: sets.len(), - }); - } - } - let Split { - dim, - groups, - of_row, - distinct, - .. - } = best?; - let split = groups - .into_iter() - .map(|(atom, ids)| { - let mut touching = vec![false; distinct]; - for id in ids { - touching[id] = true; - } - let atom_rows = rows - .iter() - .zip(&of_row) - .filter(|(_, slot)| touching[**slot]) - .map(|(&row, _)| row) - .collect(); - (atom, atom_rows) - }) - .collect(); - Some((dim, split)) - } } diff --git a/core/engine/src/analysis/table/mod.rs b/core/engine/src/analysis/table/mod.rs index 984c411d..57f781b0 100644 --- a/core/engine/src/analysis/table/mod.rs +++ b/core/engine/src/analysis/table/mod.rs @@ -1,9 +1,17 @@ mod cache; mod constraints; +mod cover; +mod gaps; mod index; +mod intern; mod merge; +#[cfg(test)] +mod merge_reference; mod missing; mod partition; +mod sets; +#[cfg(test)] +mod tests; mod verify; mod witness; @@ -26,8 +34,11 @@ use serde_json::{Map, Value}; pub(crate) use value_set::ValueSet; use print::CellText; +use std::fmt::Write as _; +use std::rc::Rc; use value_set::StringSet; -use verify::{Finding, GapCase}; + +use verify::{Finding, GapCase, GapTable}; pub(crate) struct TableColumn; @@ -412,7 +423,7 @@ impl VerifyTable<'_> { } fn missing_cases( - cases: Vec, + cases: Rc, total: usize, location: &impl Fn(Option>) -> DiagnosticLocation, ) -> Diagnostic { @@ -426,40 +437,45 @@ impl VerifyTable<'_> { .collect::>() .join(" and ") }; - let descriptions: Vec = cases.iter().map(describe).collect(); - let shown: Vec = descriptions.iter().take(5).cloned().collect(); + let mut shown: Vec = Vec::with_capacity(5); + let mut json_cases = String::from("["); + for (index, case) in cases.cases().enumerate() { + let description = describe(&case); + if index < 5 { + shown.push(description.clone()); + } + let mut entry = Map::new(); + entry.insert("description".into(), Value::String(description)); + if let Some(cells) = case.cells { + let cells: Map = cells + .into_iter() + .map(|(col, text)| (col.to_string(), Value::String(text))) + .collect(); + entry.insert("cells".into(), Value::Object(cells)); + } + if let Some(example) = case.example { + entry.insert("example".into(), example); + } + if index > 0 { + json_cases.push(','); + } + let _ = write!(json_cases, "{}", Value::Object(entry)); + } + json_cases.push(']'); + json_cases.shrink_to_fit(); let more = total.saturating_sub(shown.len()); let noun = if total == 1 { "case" } else { "cases" }; let mut message = format!("no row matches {total} input {noun}: {}", shown.join("; ")); if more > 0 { message.push_str(&format!("; and {more} more")); } - let json_cases: Vec = cases - .iter() - .zip(&descriptions) - .map(|(case, description)| { - let mut entry = Map::new(); - entry.insert("description".into(), Value::String(description.clone())); - if let Some(cells) = &case.cells { - let cells: Map = cells - .iter() - .map(|(col, text)| (col.to_string(), Value::String(text.clone()))) - .collect(); - entry.insert("cells".into(), Value::Object(cells)); - } - if let Some(example) = &case.example { - entry.insert("example".into(), example.clone()); - } - Value::Object(entry) - }) - .collect(); let mut diagnostic = Diagnostic::hint(DiagnosticCode::MissingCases, location(None), message); diagnostic.args = DiagnosticArgs::from([ ("count", total.to_string()), ("shown", shown.join("; ")), ("more", more.to_string()), - ("cases", Value::Array(json_cases).to_string()), + ("cases", json_cases), ]); diagnostic } diff --git a/core/engine/src/analysis/table/partition.rs b/core/engine/src/analysis/table/partition.rs index d2e5bdd4..ac1166bb 100644 --- a/core/engine/src/analysis/table/partition.rs +++ b/core/engine/src/analysis/table/partition.rs @@ -4,7 +4,7 @@ use std::rc::Rc; use ahash::HashMap; use rust_decimal::Decimal; -use super::value_set::{Bound, Interval, NumberSet, StringSet, ValueSet}; +use super::value_set::{Bound, Interval, NumberSet, StringSet, Strings, ValueSet}; pub(super) struct Points(Vec); @@ -93,7 +93,44 @@ pub(super) struct Partition { other: Option, } +pub(super) struct Layout { + pub(super) atoms: usize, + pub(super) strings: usize, + pub(super) rest: Option, + pub(super) numbers: std::ops::Range, + pub(super) piece_of: Vec, + pub(super) last_piece: u32, +} + impl Partition { + pub(super) fn layout(&self) -> Layout { + let piece_of: Vec = self + .pieces + .iter() + .enumerate() + .filter(|(_, atom)| atom.is_some()) + .map(|(piece, _)| piece as u32) + .collect(); + let strings = self.strings.len(); + let start = strings + usize::from(self.string_rest.is_some()); + Layout { + atoms: self.atoms.len(), + strings, + rest: self.string_rest, + numbers: start..start + piece_of.len(), + piece_of, + last_piece: self.pieces.len().saturating_sub(1) as u32, + } + } + + pub(super) fn atoms(&self) -> &[ValueSet] { + &self.atoms + } + + pub(super) fn into_atoms(self) -> Vec { + self.atoms + } + pub(super) fn touches(&self, sets: &[ValueSet]) -> usize { let mut present = Vec::with_capacity(self.pieces.len() + 1); present.push(0usize); @@ -179,7 +216,7 @@ impl Partition { } } for key in keys { - let single = StringSet::Finite(BTreeSet::from([key.clone()])); + let single = StringSet::Finite(Strings::one(key.clone())); if !region.strings.intersect(&single).is_empty() { partition.strings.insert(key, partition.atoms.len()); partition.atoms.push(ValueSet { @@ -231,7 +268,7 @@ impl Partition { partition } - fn touching(&self, set: &ValueSet) -> Vec { + pub(super) fn touching(&self, set: &ValueSet) -> Vec { let mut out = Vec::new(); match &set.strings { StringSet::Finite(keys) => out.extend(keys.iter().filter_map(|k| self.strings.get(k))), @@ -239,7 +276,7 @@ impl Partition { out.extend( self.strings .iter() - .filter(|(k, _)| !excluded.contains(*k)) + .filter(|(k, _)| !excluded.contains(k)) .map(|(_, &a)| a), ); out.extend(self.string_rest); @@ -264,7 +301,7 @@ impl Partition { out } - fn union<'a>(atoms: impl Iterator) -> ValueSet { + pub(super) fn union<'a>(atoms: impl Iterator) -> ValueSet { let mut strings: BTreeSet> = BTreeSet::new(); let mut rest: Option = None; let mut intervals: Vec = Vec::new(); @@ -280,8 +317,8 @@ impl Partition { out.other |= atom.other; } out.strings = match rest { - Some(rest) => rest.union(&StringSet::Finite(strings)), - None => StringSet::Finite(strings), + Some(rest) => rest.union(&StringSet::Finite(strings.into())), + None => StringSet::Finite(strings.into()), }; out.numbers = NumberSet::from_intervals(intervals); out diff --git a/core/engine/src/analysis/table/sets.rs b/core/engine/src/analysis/table/sets.rs new file mode 100644 index 00000000..4463f0d5 --- /dev/null +++ b/core/engine/src/analysis/table/sets.rs @@ -0,0 +1,245 @@ +use ahash::HashMap; + +use super::cell::CellConstraint; +use super::missing::{Dimension, Pool}; +use super::partition::Partition; +use super::value_set::ValueSet; +use super::verify::{Finding, Region, VerifyTable, MAX_FRAGMENTS}; + +const GAP_BUDGET: usize = 10_000_000; +const DIRECT_ROWS: usize = 8; + +impl VerifyTable<'_> { + pub(super) fn missing_sets( + &self, + dims: Vec, + cells: &[Vec], + satisfiable: &[bool], + ) -> Option> { + let cuts: Vec = cells + .iter() + .zip(satisfiable) + .filter(|(_, satisfiable)| **satisfiable) + .map(|(row_cells, _)| { + dims.iter() + .map(|d| { + d.columns + .iter() + .fold(ValueSet::all(), |acc, &col| match &row_cells[col] { + CellConstraint::Known(set) => acc.intersect(set), + _ => acc, + }) + }) + .collect() + }) + .collect(); + let mut gaps = Gaps { + cuts: &cuts, + work: GAP_BUDGET, + out: Vec::new(), + }; + gaps.uncovered( + dims.iter().map(|d| d.domain.clone()).collect(), + (0..cuts.len()).collect(), + )?; + let remaining: Vec = gaps + .out + .into_iter() + .filter_map(|mut fragment| { + for (dim, set) in dims.iter().zip(fragment.iter_mut()) { + if dim.integer { + set.numbers = set.numbers.integral(); + } + } + fragment + .iter() + .all(|set| !set.is_empty()) + .then_some(fragment) + }) + .collect(); + drop(cuts); + if remaining.is_empty() { + return Some(None); + } + let mut values: Vec> = dims.iter().map(|_| Vec::new()).collect(); + let mut indexes: Vec> = + dims.iter().map(|_| HashMap::default()).collect(); + let mut rows: Vec = Vec::with_capacity(remaining.len() * dims.len()); + for fragment in remaining { + for ((set, sets), index) in fragment.into_iter().zip(&mut values).zip(&mut indexes) { + rows.push(Pool::intern(sets, index, set)); + } + } + let atoms = dims.iter().map(|_| Vec::new()).collect(); + let pools = values + .into_iter() + .zip(indexes) + .map(|(sets, index)| Pool::sets(sets, index)) + .collect(); + Some(Some(self.missing_cases_of(dims, atoms, pools, rows))) + } +} + +type Atoms = Vec<(ValueSet, Vec)>; + +struct Split { + dim: usize, + score: usize, + groups: Atoms, + of_row: Vec, + distinct: usize, +} + +struct Gaps<'c> { + cuts: &'c [Region], + work: usize, + out: Vec, +} + +impl Gaps<'_> { + fn spend(&mut self, amount: usize) -> Option<()> { + self.work = self.work.checked_sub(amount.max(1))?; + Some(()) + } + + fn uncovered(&mut self, region: Region, rows: Vec) -> Option<()> { + self.spend(rows.len() * region.len())?; + let rows: Vec = rows + .into_iter() + .filter(|&row| { + self.cuts[row] + .iter() + .zip(®ion) + .all(|(cut, set)| cut.intersects(set)) + }) + .collect(); + if rows.is_empty() { + self.out.push(region); + return Some(()); + } + let covered = rows.iter().any(|&row| { + region + .iter() + .zip(&self.cuts[row]) + .all(|(set, cut)| set.is_subset(cut)) + }); + if covered { + return Some(()); + } + if rows.len() > DIRECT_ROWS { + if let Some((dim, atoms)) = self.split(®ion, &rows) { + for (atom, atom_rows) in atoms { + let mut piece = region.clone(); + piece[dim] = atom; + self.uncovered(piece, atom_rows)?; + } + return Some(()); + } + } + self.subtract_all(region, &rows) + } + + fn subtract_all(&mut self, region: Region, rows: &[usize]) -> Option<()> { + let mut remaining = vec![region]; + let cuts = self.cuts; + for &row in rows { + let cut: Vec<&ValueSet> = cuts[row].iter().collect(); + let mut next = Vec::with_capacity(remaining.len()); + for fragment in remaining { + self.spend(fragment.len())?; + match VerifyTable::subtract(&fragment, &cut) { + Some(pieces) => next.extend(pieces), + None => next.push(fragment), + } + } + if next.len() > MAX_FRAGMENTS { + return None; + } + remaining = next; + if remaining.is_empty() { + return Some(()); + } + } + self.out.extend(remaining); + Some(()) + } + + fn split(&mut self, region: &Region, rows: &[usize]) -> Option<(usize, Atoms)> { + let mut best: Option = None; + for (dim, bounds) in region.iter().enumerate() { + let mut sets: Vec = Vec::new(); + let mut index: HashMap = HashMap::default(); + let mut of_row: Vec = Vec::with_capacity(rows.len()); + for &row in rows { + let set = self.cuts[row][dim].intersect(bounds); + let next = sets.len(); + let slot = *index.entry(set.clone()).or_insert(next); + if slot == next { + sets.push(set); + } + of_row.push(slot); + } + if sets.iter().all(|set| set == bounds) { + continue; + } + let partition = Partition::new(bounds, &sets); + if partition.touches(&sets) > self.work { + return None; + } + let groups = partition.groups(&sets); + if groups.len() < 2 { + continue; + } + let mut count = vec![0usize; sets.len()]; + for &slot in &of_row { + count[slot] += 1; + } + let score: usize = groups + .iter() + .map(|(_, ids)| ids.iter().map(|&id| count[id]).sum::()) + .sum(); + self.spend(score + groups.len())?; + if best.as_ref().is_none_or(|split| score < split.score) { + best = Some(Split { + dim, + score, + groups, + of_row, + distinct: sets.len(), + }); + } + } + let Split { + dim, + groups, + of_row, + distinct, + .. + } = best?; + let mut starts = vec![0usize; distinct + 1]; + for &slot in &of_row { + starts[slot + 1] += 1; + } + for slot in 0..distinct { + starts[slot + 1] += starts[slot]; + } + let mut cursor = starts.clone(); + let mut by_slot = vec![0usize; rows.len()]; + for (&row, &slot) in rows.iter().zip(&of_row) { + by_slot[cursor[slot]] = row; + cursor[slot] += 1; + } + let split = groups + .into_iter() + .map(|(atom, ids)| { + let mut atom_rows: Vec = ids + .into_iter() + .flat_map(|id| by_slot[starts[id]..starts[id + 1]].iter().copied()) + .collect(); + atom_rows.sort_unstable(); + (atom, atom_rows) + }) + .collect(); + Some((dim, split)) + } +} diff --git a/core/engine/src/analysis/table/tests.rs b/core/engine/src/analysis/table/tests.rs new file mode 100644 index 00000000..c24b497e --- /dev/null +++ b/core/engine/src/analysis/table/tests.rs @@ -0,0 +1,315 @@ +use serde_json::{json, Map, Value}; + +use crate::model::DecisionContent; +use crate::policy::{DiagnosticCode, Workspace}; + +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn below(&mut self, bound: usize) -> usize { + (self.next() % bound as u64) as usize + } + + fn chance(&mut self, percent: usize) -> bool { + self.below(100) < percent + } + + fn pick<'a, T>(&mut self, items: &'a [T]) -> &'a T { + &items[self.below(items.len())] + } +} + +#[derive(Clone, Copy, PartialEq)] +enum Kind { + Number, + Integer, + Text, + Choice, + Flag, + Untyped, +} + +const KINDS: [Kind; 6] = [ + Kind::Number, + Kind::Integer, + Kind::Text, + Kind::Choice, + Kind::Flag, + Kind::Untyped, +]; +const WORDS: [&str; 6] = ["red", "green", "blue", "amber", "teal", "plum"]; +const POINTS: [&str; 9] = ["0", "5", "10", "12.5", "20", "25", "40", "60", "100"]; + +fn number_cell(rng: &mut Rng) -> String { + let a = *rng.pick(&POINTS); + let b = *rng.pick(&POINTS); + match rng.below(16) { + 0 | 1 => String::new(), + 2 => format!("> {a}"), + 3 => format!(">= {a}"), + 4 => format!("< {a}"), + 5 => format!("<= {a}"), + 6 => format!("[{a}..{b}]"), + 7 => format!("[{a}..{b})"), + 8 => format!("({a}..{b}]"), + 9 => a.to_string(), + 10 => format!("{a}, {b}"), + 11 => format!("< {a}, > {b}"), + 12 => format!("!= {a}"), + 13 => format!(">= {a} and < {b}"), + 14 => format!("not in [{a}, {b}]"), + _ => "null".to_string(), + } +} + +fn text_cell(rng: &mut Rng) -> String { + let a = *rng.pick(&WORDS); + let b = *rng.pick(&WORDS); + match rng.below(9) { + 0 | 1 => String::new(), + 2 | 3 => format!("\"{a}\""), + 4 => format!("\"{a}\", \"{b}\""), + 5 => format!("not in [\"{a}\", \"{b}\"]"), + 6 => format!("!= \"{a}\""), + 7 => "null".to_string(), + _ => "len($) > 3".to_string(), + } +} + +fn flag_cell(rng: &mut Rng) -> String { + match rng.below(5) { + 0 => String::new(), + 1 | 2 => "true".to_string(), + 3 => "false".to_string(), + _ => "true, false".to_string(), + } +} + +fn cell(rng: &mut Rng, kind: Kind) -> String { + match kind { + Kind::Number | Kind::Integer => number_cell(rng), + Kind::Text | Kind::Choice => text_cell(rng), + Kind::Flag => flag_cell(rng), + Kind::Untyped => match rng.below(3) { + 0 => number_cell(rng), + 1 => text_cell(rng), + _ => flag_cell(rng), + }, + } +} + +fn schema_of(kind: Kind, nullable: bool) -> Option { + let typed = |name: &str| match nullable { + true => json!({ "type": [name, "null"] }), + false => json!({ "type": name }), + }; + match kind { + Kind::Number => Some(typed("number")), + Kind::Integer => Some(typed("integer")), + Kind::Text => Some(typed("string")), + Kind::Choice => Some(json!({ "enum": WORDS[..4] })), + Kind::Flag => Some(typed("boolean")), + Kind::Untyped => None, + } +} + +fn random_graph(rng: &mut Rng, rows: usize, columns: usize) -> DecisionContent { + let kinds: Vec = (0..columns).map(|_| *rng.pick(&KINDS)).collect(); + let shared = columns > 1 && rng.chance(15); + let mut properties = Map::new(); + let mut required = Vec::new(); + let mut inputs = Vec::new(); + for (index, kind) in kinds.iter().enumerate() { + let field = match shared && index == columns - 1 { + true => "f0".to_string(), + false => format!("f{index}"), + }; + let kind = match shared && index == columns - 1 { + true => kinds[0], + false => *kind, + }; + if let Some(schema) = schema_of(kind, rng.chance(20)) { + properties.entry(field.clone()).or_insert(schema); + if rng.chance(80) && !required.contains(&json!(field)) { + required.push(json!(field)); + } + } + inputs.push( + json!({ "id": format!("c{index}"), "name": format!("Column {index}"), "field": field }), + ); + } + let schema = json!({ "type": "object", "properties": properties, "required": required }); + let collect = rng.chance(15); + let rules: Vec = (0..rows) + .map(|row| { + let mut rule = Map::new(); + rule.insert("_id".into(), json!(format!("r{row}"))); + for (index, kind) in kinds.iter().enumerate() { + let kind = match shared && index == columns - 1 { + true => kinds[0], + false => *kind, + }; + rule.insert(format!("c{index}"), json!(cell(rng, kind))); + } + rule.insert("o".into(), json!(format!("{}", rng.below(4)))); + Value::Object(rule) + }) + .collect(); + serde_json::from_value(json!({ + "nodes": [ + { "id": "in", "name": "request", "type": "inputNode", "content": { "schema": schema.to_string() } }, + { "id": "dt", "name": "table", "type": "decisionTableNode", "content": { + "hitPolicy": if collect { "collect" } else { "first" }, + "inputs": inputs, + "outputs": [ { "id": "o", "name": "Out", "field": "out" } ], + "rules": rules, + "passThrough": true + } }, + { "id": "out", "name": "out", "type": "outputNode", "content": {} } + ], + "edges": [ + { "id": "e1", "sourceId": "in", "targetId": "dt" }, + { "id": "e2", "sourceId": "dt", "targetId": "out" } + ] + })) + .expect("graph") +} + +struct Reported { + missing: bool, + incomplete: bool, + compressible: bool, + unreachable: bool, +} + +fn reported(content: DecisionContent) -> Reported { + let mut workspace = Workspace::new(); + workspace.set_document("g", content); + let diagnostics = workspace.diagnostics("g"); + let has = |code: DiagnosticCode| diagnostics.iter().any(|d| d.code == code); + Reported { + missing: has(DiagnosticCode::MissingCases), + incomplete: has(DiagnosticCode::TableChecksIncomplete), + compressible: has(DiagnosticCode::CompressibleTable), + unreachable: has(DiagnosticCode::UnreachableRule), + } +} + +#[test] +fn table_checks_match_the_reference_on_random_tables() { + let mut rng = Rng(0x5EED_1234_ABCD_0001); + let mut with_gaps = 0; + let mut compressible = 0; + let mut unreachable = 0; + let mut split = 0; + for round in 0..1500 { + let rows = match round % 10 { + 0 => 1 + rng.below(8), + 9 => 60 + rng.below(240), + _ => 9 + rng.below(50), + }; + let columns = 1 + rng.below(5); + let found = reported(random_graph(&mut rng, rows, columns)); + with_gaps += usize::from(found.missing); + compressible += usize::from(found.compressible); + unreachable += usize::from(found.unreachable); + split += usize::from(rows > 8); + } + assert!(with_gaps > 300, "only {with_gaps} tables reported gaps"); + assert!( + compressible > 200, + "only {compressible} tables were compressible" + ); + assert!( + unreachable > 200, + "only {unreachable} tables had unreachable rows" + ); + assert!(split > 1000, "only {split} tables reached the split path"); +} + +fn range_heavy(rng: &mut Rng, rows: usize, columns: usize) -> DecisionContent { + let mut properties = Map::new(); + let inputs: Vec = (0..columns) + .map(|index| { + properties.insert(format!("n{index}"), json!({ "type": "number" })); + json!({ "id": format!("c{index}"), "name": format!("N{index}"), "field": format!("n{index}") }) + }) + .collect(); + let required: Vec = properties.keys().cloned().collect(); + let schema = json!({ "type": "object", "properties": properties, "required": required }); + let rules: Vec = (0..rows) + .map(|row| { + let mut rule = Map::new(); + rule.insert("_id".into(), json!(format!("r{row}"))); + for index in 0..columns { + let step = [1usize, 5, 10, 50, 100, 500][index % 6]; + let low = rng.below(60) * step; + let high = low + (1 + rng.below(6)) * step; + let cell = match rng.below(5) { + 0 => format!("[{low}..{high})"), + 1 => format!(">= {low} and < {high}"), + 2 => format!("> {low}"), + 3 => format!("<= {high}"), + _ => String::new(), + }; + rule.insert(format!("c{index}"), json!(cell)); + } + rule.insert("o".into(), json!(format!("{}", rng.below(9)))); + Value::Object(rule) + }) + .collect(); + serde_json::from_value(json!({ + "nodes": [ + { "id": "in", "name": "request", "type": "inputNode", "content": { "schema": schema.to_string() } }, + { "id": "dt", "name": "table", "type": "decisionTableNode", "content": { + "hitPolicy": "first", + "inputs": inputs, + "outputs": [ { "id": "o", "name": "Out", "field": "out" } ], + "rules": rules, + "passThrough": true + } }, + { "id": "out", "name": "out", "type": "outputNode", "content": {} } + ], + "edges": [ + { "id": "e1", "sourceId": "in", "targetId": "dt" }, + { "id": "e2", "sourceId": "dt", "targetId": "out" } + ] + })) + .expect("graph") +} + +#[test] +fn table_checks_match_the_reference_on_range_heavy_tables() { + let mut rng = Rng(0x0BAD_CAFE_F00D_0002); + let mut with_gaps = 0; + let mut incomplete = 0; + for (rows, columns) in [(40, 3), (80, 4), (120, 6), (200, 5), (300, 6)] { + let found = reported(range_heavy(&mut rng, rows, columns)); + with_gaps += usize::from(found.missing); + incomplete += usize::from(found.incomplete); + } + assert!(with_gaps >= 2, "only {with_gaps} tables reported gaps"); + assert_eq!(with_gaps + incomplete, 5); +} + +#[test] +#[ignore] +fn table_checks_match_the_reference_when_the_budget_runs_out() { + let mut rng = Rng(0x0DDB_A11C_0FFE_0003); + let mut incomplete = 0; + let mut complete = 0; + for (rows, columns) in [(300, 3), (1000, 6), (2000, 6), (4000, 6), (4000, 9)] { + let found = reported(range_heavy(&mut rng, rows, columns)); + incomplete += usize::from(found.incomplete); + complete += usize::from(!found.incomplete); + } + assert!(incomplete >= 1, "no table exhausted the budget"); + assert!(complete >= 1, "no table finished inside the budget"); +} diff --git a/core/engine/src/analysis/table/verify.rs b/core/engine/src/analysis/table/verify.rs index 7e592485..6a91ef9d 100644 --- a/core/engine/src/analysis/table/verify.rs +++ b/core/engine/src/analysis/table/verify.rs @@ -6,14 +6,19 @@ use serde_json::{Map, Value}; use zen_expression::intellisense::IntelliSense; use super::cell::CellConstraint; +use super::cover::Coverage; +use super::gaps::Bits; use super::index::RowIndex; +use super::intern::Interner; +use super::merge::CellKeys; +use super::partition::Partition; use super::print::{CellText, DateDay}; use super::value_set::{ValueKind, ValueSet}; pub(crate) const MAX_INPUTS: usize = 30; pub(super) const MAX_FRAGMENTS: usize = 100_000; const TOTAL_BUDGET: usize = 20_000_000; -const MAX_MINIMIZE: usize = 12; +pub(super) const MAX_MINIMIZE: usize = 12; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub(crate) enum HitMode { @@ -74,7 +79,7 @@ pub(crate) enum Finding { redundant: bool, }, MissingCases { - cases: Vec, + cases: Rc, total: usize, }, CompressibleTable { @@ -103,10 +108,138 @@ pub(crate) struct GapCase { pub(crate) example: Option, } +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum GapValues { + Patterns { words: usize, data: Vec }, + Sets(Vec), +} + +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct GapAxis { + pub(super) label: Arc, + pub(super) column: Option>, + pub(super) subject: Option, + pub(super) path: Option>, + pub(super) input: bool, + pub(super) dated: bool, + pub(super) prefer: Option, + pub(super) domain: ValueSet, + pub(super) atoms: Vec, + pub(super) values: GapValues, +} + +struct GapValue { + text: Option, + cell: Option, + example: Option, +} + +impl GapAxis { + fn len(&self) -> usize { + match &self.values { + GapValues::Patterns { words, data } => data.len() / words, + GapValues::Sets(sets) => sets.len(), + } + } + + fn set(&self, value: usize) -> ValueSet { + match &self.values { + GapValues::Sets(sets) => sets[value].clone(), + GapValues::Patterns { words, data } => Partition::union( + Bits::ones(&data[value * words..(value + 1) * words]).map(|atom| &self.atoms[atom]), + ), + } + } + + fn describe(&self, value: usize) -> GapValue { + let set = self.set(value); + let text = CellText::of(&set, &self.domain, self.dated); + let skipped = text.as_ref().is_some_and(String::is_empty); + let cell = match (&text, &self.subject) { + _ if skipped => None, + (None, _) => None, + (Some(_), Some(subject)) => CellText::standard(&set, &self.domain, self.dated, subject), + (Some(text), None) => Some(text.clone()), + }; + let example = match (skipped, self.dated) { + (true, _) => None, + (false, true) => DateDay::example(&set), + (false, false) => set.example(self.prefer), + }; + GapValue { + text, + cell, + example, + } + } +} + +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct GapTable { + pub(super) axes: Vec, + pub(super) rows: Vec, +} + +impl GapTable { + pub(crate) fn cases(&self) -> impl Iterator + '_ { + let mut described: Vec>> = self + .axes + .iter() + .map(|axis| (0..axis.len()).map(|_| None).collect()) + .collect(); + self.rows + .chunks_exact(self.axes.len().max(1)) + .map(move |row| self.case(row, &mut described)) + } + + fn case(&self, row: &[u32], described: &mut [Vec>]) -> GapCase { + let mut parts = Vec::new(); + let mut cells = Some(Vec::new()); + let mut example = Some(Map::new()); + for ((axis, described), &value) in self.axes.iter().zip(described.iter_mut()).zip(row) { + let value = match &mut described[value as usize] { + Some(value) => value, + slot => slot.insert(axis.describe(value as usize)), + }; + match &value.text { + Some(text) if text.is_empty() => continue, + Some(text) => { + if !axis.input { + example = None; + } + if let (Some(list), Some(column)) = (cells.as_mut(), &axis.column) { + match &value.cell { + Some(cell) => list.push((column.clone(), cell.clone())), + None => cells = None, + } + } + parts.push((axis.label.clone(), text.clone())); + } + None => { + cells = None; + parts.push((axis.label.clone(), "…".to_string())); + } + } + match (&axis.path, &value.example, example.as_mut()) { + (Some(path), Some(value), Some(root)) => { + VerifyTable::insert(root, path, value.clone()) + } + _ => example = None, + } + } + GapCase { + parts, + cells, + example: example.filter(|root| !root.is_empty()).map(Value::Object), + } + } +} + pub(super) type Region = Vec; type Coverer<'c> = (usize, Vec<&'c ValueSet>); +#[cfg_attr(test, derive(Clone))] pub(super) struct Budget { pub(super) remaining: usize, } @@ -193,30 +326,29 @@ impl<'a> VerifyTable<'a> { if self.inputs.is_empty() { return findings; } - let cells: Vec> = self - .rules - .iter() - .map(|rule| { - self.inputs - .iter() - .map(|col| { - let source = rule.get(&col.id).map(|c| c.as_ref()).unwrap_or(""); - match &col.subject { - Some(subject) => { - CellConstraint::parse_subject(is, source, subject, col.dated) - } - None => CellConstraint::parse( - is, - source, - col.unary, - col.analyzable, - col.dated, - ), - } - }) - .collect() - }) - .collect(); + let mut parsed: Vec> = + self.inputs.iter().map(|_| HashMap::default()).collect(); + let mut cells: Vec> = Vec::with_capacity(self.rules.len()); + for (row, rule) in self.rules.iter().enumerate() { + let mut row_cells = Vec::with_capacity(self.inputs.len()); + for (index, (col, known)) in self.inputs.iter().zip(parsed.iter_mut()).enumerate() { + let source = rule.get(&col.id).map(|c| c.as_ref()).unwrap_or(""); + if let Some(&first) = known.get(source) { + row_cells.push(cells[first][index].clone()); + continue; + } + let cell = match &col.subject { + Some(subject) => CellConstraint::parse_subject(is, source, subject, col.dated), + None => CellConstraint::parse(is, source, col.unary, col.analyzable, col.dated), + }; + if !matches!(cell, CellConstraint::Opaque(_)) { + known.insert(source, row); + } + row_cells.push(cell); + } + cells.push(row_cells); + } + drop(parsed); let mut satisfiable = vec![true; self.rules.len()]; for (row, row_cells) in cells.iter().enumerate() { @@ -239,9 +371,18 @@ impl<'a> VerifyTable<'a> { }; let mut index = (self.mode != HitMode::Collect).then(|| RowIndex::new(&cells, self.inputs.len())); + let mut regions = index + .as_ref() + .and_then(|_| Coverage::new(&cells, self.inputs.len())); let mut reported: Vec = satisfiable.iter().map(|s| !s).collect(); let mut warned: Vec = vec![false; self.rules.len()]; - let mut seen: HashMap<(Vec, Vec), usize> = HashMap::default(); + let keys = CellKeys::new(&cells, self.inputs.len()); + let outputs = self.output_ids(); + let mut seen: Interner = Interner::new(self.inputs.len() + 1); + let mut first_with: Vec = Vec::new(); + let mut signature: Vec = Vec::with_capacity(self.inputs.len() + 1); + #[cfg(test)] + let mut seen_sets: HashMap<(Vec, Vec), usize> = HashMap::default(); let mut blocked_by: HashMap = HashMap::default(); for row in 0..self.rules.len() { if let Some(index) = index.as_mut().filter(|_| row > 0) { @@ -252,29 +393,46 @@ impl<'a> VerifyTable<'a> { if !satisfiable[row] { continue; } - match seen.entry(self.row_signature(&cells[row], row)) { - std::collections::hash_map::Entry::Occupied(first) => { - let of = *first.get(); - reported[row] = true; - let redundant = self.mode != HitMode::Collect && !self.contributes_collect(row); - findings.push(Finding::DuplicateRule { row, of, redundant }); - continue; - } - std::collections::hash_map::Entry::Vacant(slot) => { - slot.insert(row); - } + signature.clear(); + signature.extend_from_slice(keys.row(row)); + signature.push(outputs[row]); + let fresh = seen.len(); + let slot = seen.intern(&signature) as usize; + #[cfg(test)] + assert_eq!( + *seen_sets + .entry(self.row_signature(&cells[row], row)) + .or_insert(row), + first_with.get(slot).copied().unwrap_or(row), + "duplicate detection diverged from the reference at row {row}" + ); + if slot < fresh { + let of = first_with[slot]; + reported[row] = true; + let redundant = self.mode != HitMode::Collect && !self.contributes_collect(row); + findings.push(Finding::DuplicateRule { row, of, redundant }); + continue; } + first_with.push(row); if coverage_incomplete { continue; } let Some(index) = index.as_mut() else { continue; }; - let Some(requirements) = self.requirements(row, || index.candidates(&cells, row)) + let Some(requirements) = + self.requirements(row, || index.candidates(&cells, &keys, row)) else { continue; }; - match self.dead(&cells, row, &requirements, &mut budget, index) { + match self.dead( + &cells, + row, + &requirements, + &mut budget, + index, + regions.as_mut(), + ) { Some(Some(covered_by)) => { reported[row] = true; let redundant = self.blank_outputs(row) @@ -284,8 +442,16 @@ impl<'a> VerifyTable<'a> { warned[row] = !redundant; let same_conditions = !redundant && covered_by.len() == 1 - && self.row_signature(&cells[row], row).0 - == self.row_signature(&cells[covered_by[0]], covered_by[0]).0; + && keys.row(row) == keys.row(covered_by[0]); + #[cfg(test)] + assert_eq!( + same_conditions, + !redundant + && covered_by.len() == 1 + && self.row_signature(&cells[row], row).0 + == self.row_signature(&cells[covered_by[0]], covered_by[0]).0, + "row conditions comparison diverged from the reference at row {row}" + ); let blocker = match covered_by.as_slice() { [only] if !same_conditions || self.catch_all_row(*only) => Some(*only), _ => None, @@ -326,7 +492,7 @@ impl<'a> VerifyTable<'a> { None => gaps_incomplete = true, } } - findings.extend(self.compress(&cells, &satisfiable, &warned)); + findings.extend(self.compress(&cells, &satisfiable, &warned, keys, &outputs)); findings.extend(self.covering_cells(&cells, &satisfiable)); findings.extend(self.unproduced(is, &reported)); if coverage_incomplete || gaps_incomplete { @@ -407,6 +573,22 @@ impl<'a> VerifyTable<'a> { self.rules[row].get(id).map(|c| c.trim()).unwrap_or("") } + fn output_ids(&self) -> Vec { + let mut ids: HashMap, u32> = HashMap::default(); + (0..self.rules.len()) + .map(|row| { + let key: Vec<&str> = self + .outputs + .iter() + .map(|col| self.text(row, &col.id)) + .collect(); + let next = ids.len() as u32; + *ids.entry(key).or_insert(next) + }) + .collect() + } + + #[cfg(test)] fn row_signature( &self, cells: &[CellConstraint], @@ -473,6 +655,53 @@ impl<'a> VerifyTable<'a> { requirements: &[Vec], budget: &mut Budget, index: &RowIndex, + coverage: Option<&mut Coverage>, + ) -> Option>> { + let Some(coverage) = coverage else { + return Self::dead_sets(cells, row, requirements, budget, index); + }; + #[cfg(test)] + let mut shadow = budget.clone(); + let found = Self::covered(cells, row, requirements, budget, index, coverage); + #[cfg(test)] + { + let expected = Self::dead_sets(cells, row, requirements, &mut shadow, index); + assert_eq!( + (&found, budget.remaining), + (&expected, shadow.remaining), + "row coverage diverged between the dense and set-based paths at row {row}" + ); + } + found + } + + fn covered( + cells: &[Vec], + row: usize, + requirements: &[Vec], + budget: &mut Budget, + index: &RowIndex, + coverage: &mut Coverage, + ) -> Option>> { + let region: Region = cells[row] + .iter() + .map(|cell| cell.known_set().unwrap_or_else(ValueSet::all)) + .collect(); + for earlier in requirements { + budget.spend(earlier.len())?; + if Self::escapes(cells, row, ®ion, earlier, index) { + return Some(None); + } + } + coverage.covered_by(row, requirements, budget) + } + + fn dead_sets( + cells: &[Vec], + row: usize, + requirements: &[Vec], + budget: &mut Budget, + index: &RowIndex, ) -> Option>> { let region: Region = cells[row] .iter() diff --git a/core/engine/src/workspace/db.rs b/core/engine/src/workspace/db.rs index d6baf353..b7317c29 100644 --- a/core/engine/src/workspace/db.rs +++ b/core/engine/src/workspace/db.rs @@ -823,11 +823,7 @@ impl Db { return d; } let value = if snap.graphs.contains_key(path) { - Arc::new( - self.graph_analysis(path) - .map(|analysis| analysis.diagnostics.clone()) - .unwrap_or_default(), - ) + Arc::new(self.graph_table_diagnostics(path)) } else { Arc::new(self.compute_policy_diagnostics(path)) }; diff --git a/core/engine/src/workspace/graph/analysis.rs b/core/engine/src/workspace/graph/analysis.rs index a5782bb5..17e23d5c 100644 --- a/core/engine/src/workspace/graph/analysis.rs +++ b/core/engine/src/workspace/graph/analysis.rs @@ -15,7 +15,7 @@ use zen_expression::intellisense::ArmTest; use crate::analysis::nullable::{NullableOperand, OnError}; use crate::analysis::table::{ - Bound, HitMode, Interval, NumberSet, PathConstraints, TableColumn, VerifyTable, + Bound, HitMode, Interval, NumberSet, PathConstraints, TableColumn, VerifyInput, VerifyOutput, }; use crate::model::GraphContent; use crate::policy::blocks::{ @@ -63,9 +63,20 @@ impl GraphNodeAnalysis { } } +#[derive(Debug)] +pub(crate) struct GraphTableCheck { + pub(crate) at: usize, + pub(crate) node: Arc, + pub(crate) mode: HitMode, + pub(crate) inputs: Vec, + pub(crate) outputs: Vec, + pub(crate) fallible: Vec, +} + #[derive(Debug)] pub struct GraphAnalysis { pub diagnostics: Vec, + pub(crate) table_checks: Vec, pub signature: GraphSignature, pub nodes: HashMap, GraphNodeAnalysis>, pub inferred_inputs: Vec>, @@ -103,6 +114,7 @@ pub(crate) struct GraphAnalyzer<'a> { path: Arc, content: &'a GraphContent, diagnostics: Vec, + table_checks: Vec, validate: bool, unchecked: bool, nodes_scope: VariableType, @@ -158,6 +170,7 @@ impl<'a> GraphAnalyzer<'a> { path, content, diagnostics: Vec::new(), + table_checks: Vec::new(), validate: false, unchecked: false, nodes_scope: VariableType::Any, @@ -234,6 +247,7 @@ impl<'a> GraphAnalyzer<'a> { let input = self.graph_input_signature(); GraphAnalysis { diagnostics: self.diagnostics, + table_checks: self.table_checks, signature: GraphSignature { input, output }, nodes, inferred_inputs, @@ -1573,7 +1587,9 @@ impl<'a> GraphAnalyzer<'a> { .collect(), DecisionTableHitPolicy::Collect => Vec::new(), }; - let table = VerifyTable { + let check = GraphTableCheck { + at: self.diagnostics.len(), + node: node.id.clone(), mode: match content.hit_policy { DecisionTableHitPolicy::First => HitMode::RowFirst, DecisionTableHitPolicy::Collect => HitMode::Collect, @@ -1621,20 +1637,9 @@ impl<'a> GraphAnalyzer<'a> { }) }) .collect(), - rules: &content.rules, fallible, }; - let diagnostics = table.diagnostics( - &mut intellisense.borrow_mut(), - |row| Self::row_key(&content.rules[row], row), - |expression_id| match expression_id { - Some(id) => { - DiagnosticLocation::expression(self.path.clone(), node.id.clone(), id, None) - } - None => DiagnosticLocation::block(self.path.clone(), node.id.clone()), - }, - ); - self.diagnostics.extend(diagnostics); + self.table_checks.push(check); } fn declared_output_type( diff --git a/core/engine/src/workspace/graph/queries.rs b/core/engine/src/workspace/graph/queries.rs index 3bb75b73..fc53bb84 100644 --- a/core/engine/src/workspace/graph/queries.rs +++ b/core/engine/src/workspace/graph/queries.rs @@ -10,8 +10,12 @@ use crate::workspace::graph::analysis::{ }; use crate::workspace::reads::ReadView; +use crate::analysis::table::VerifyTable; +use crate::model::DecisionNodeKind; use crate::policy::queries::scope::VariableTypeScope; -use crate::workspace::types::{InputProperty, OutputProperty, PropertyKind, ScopeRequest}; +use crate::workspace::types::{ + Diagnostic, DiagnosticLocation, InputProperty, OutputProperty, PropertyKind, ScopeRequest, +}; impl Db { pub(crate) fn graph_analysis(&self, path: &Arc) -> Option> { @@ -33,6 +37,52 @@ impl Db { Some(analysis) } + pub(crate) fn graph_table_diagnostics(&self, path: &Arc) -> Vec { + let Some(analysis) = self.graph_analysis(path) else { + return Vec::new(); + }; + let snap = self.snapshot(); + let content = snap.graphs.get(path).and_then(|doc| doc.as_graph()); + let (Some(content), false) = (content, analysis.table_checks.is_empty()) else { + return analysis.diagnostics.clone(); + }; + let intellisense = self.graph_intellisense(); + let mut out = Vec::with_capacity(analysis.diagnostics.len()); + let mut cursor = 0; + for check in &analysis.table_checks { + out.extend(analysis.diagnostics[cursor..check.at].iter().cloned()); + cursor = check.at; + let rules = content.nodes.iter().find_map(|node| match &node.kind { + DecisionNodeKind::DecisionTableNode { content } if node.id == check.node => { + Some(&content.rules) + } + _ => None, + }); + let Some(rules) = rules else { + continue; + }; + let table = VerifyTable { + mode: check.mode, + inputs: check.inputs.clone(), + outputs: check.outputs.clone(), + rules, + fallible: check.fallible.clone(), + }; + out.extend(table.diagnostics( + &mut intellisense.borrow_mut(), + |row| GraphAnalyzer::row_key(&rules[row], row), + |expression_id| match expression_id { + Some(id) => { + DiagnosticLocation::expression(path.clone(), check.node.clone(), id, None) + } + None => DiagnosticLocation::block(path.clone(), check.node.clone()), + }, + )); + } + out.extend(analysis.diagnostics[cursor..].iter().cloned()); + out + } + pub(crate) fn is_graph(&self, path: &str) -> bool { self.snapshot().graphs.contains_key(path) } diff --git a/core/engine/tests/table_scaling.rs b/core/engine/tests/table_scaling.rs new file mode 100644 index 00000000..4e0e0228 --- /dev/null +++ b/core/engine/tests/table_scaling.rs @@ -0,0 +1,602 @@ +use std::alloc::{GlobalAlloc, Layout, System}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; + +use serde_json::{json, Map, Value}; +use zen_engine::model::DecisionContent; +use zen_engine::policy::{DiagnosticCode, Workspace}; +use zen_engine::workspace::ScopeRequest; + +struct Counting; + +static LIVE: AtomicUsize = AtomicUsize::new(0); +static PEAK: AtomicUsize = AtomicUsize::new(0); +static MEASURING: Mutex<()> = Mutex::new(()); + +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + let live = LIVE.fetch_add(layout.size(), Ordering::Relaxed) + layout.size(); + PEAK.fetch_max(live, Ordering::Relaxed); + System.alloc(layout) + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + LIVE.fetch_sub(layout.size(), Ordering::Relaxed); + System.dealloc(ptr, layout) + } + + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + if new_size >= layout.size() { + let grown = new_size - layout.size(); + let live = LIVE.fetch_add(grown, Ordering::Relaxed) + grown; + PEAK.fetch_max(live, Ordering::Relaxed); + } else { + LIVE.fetch_sub(layout.size() - new_size, Ordering::Relaxed); + } + System.realloc(ptr, layout, new_size) + } +} + +#[global_allocator] +static GLOBAL: Counting = Counting; + +const MIB: usize = 1024 * 1024; + +fn peak_of(work: impl FnOnce() -> T) -> (T, usize) { + let before = LIVE.load(Ordering::Relaxed); + PEAK.store(before, Ordering::Relaxed); + let result = work(); + (result, PEAK.load(Ordering::Relaxed).saturating_sub(before)) +} + +struct Rng(u64); + +impl Rng { + fn below(&mut self, bound: usize) -> usize { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + (self.0 % bound as u64) as usize + } +} + +fn range_table(seed: u64, rows: usize, columns: usize) -> DecisionContent { + let mut rng = Rng(seed); + let mut properties = Map::new(); + let inputs: Vec = (0..columns) + .map(|index| { + properties.insert(format!("n{index}"), json!({ "type": "number" })); + json!({ "id": format!("c{index}"), "name": format!("N{index}"), "field": format!("n{index}") }) + }) + .collect(); + let required: Vec = properties.keys().cloned().collect(); + let schema = json!({ "type": "object", "properties": properties, "required": required }); + let rules: Vec = (0..rows) + .map(|row| { + let mut rule = Map::new(); + rule.insert("_id".into(), json!(format!("r{row}"))); + for index in 0..columns { + let cell = match index % 6 { + 3 => ["12", "24", "36", "48", "60", "> 60", "<= 36", ""][rng.below(8)] + .to_string(), + 4 => ["< 0.2", "[0.2..0.35)", "[0.35..0.45)", ">= 0.45", ""][rng.below(5)] + .to_string(), + kind => { + let (floor, span, step) = [ + (18, 62, 1), + (2, 78, 5000), + (30, 55, 10), + (0, 0, 0), + (0, 0, 0), + (1, 90, 1000), + ][kind]; + let low = (floor + rng.below(span)) * step; + let high = low + (1 + rng.below(6)) * step; + match rng.below(5) { + 0 => format!("[{low}..{high})"), + 1 => format!(">= {low} and < {high}"), + 2 => format!("> {low}"), + 3 => format!("<= {high}"), + _ => String::new(), + } + } + }; + rule.insert(format!("c{index}"), json!(cell)); + } + rule.insert("o".into(), json!(format!("{}", rng.below(9)))); + Value::Object(rule) + }) + .collect(); + serde_json::from_value(json!({ + "nodes": [ + { "id": "in", "name": "request", "type": "inputNode", "content": { "schema": schema.to_string() } }, + { "id": "dt", "name": "table", "type": "decisionTableNode", "content": { + "hitPolicy": "first", + "inputs": inputs, + "outputs": [ { "id": "o", "name": "Out", "field": "out" } ], + "rules": rules, + "passThrough": true + } }, + { "id": "out", "name": "out", "type": "outputNode", "content": {} } + ], + "edges": [ + { "id": "e1", "sourceId": "in", "targetId": "dt" }, + { "id": "e2", "sourceId": "dt", "targetId": "out" } + ] + })) + .expect("graph") +} + +struct Measured { + peak: usize, + payload: usize, + cases: usize, + incomplete: bool, +} + +fn diagnose(content: DecisionContent) -> Measured { + let mut workspace = Workspace::new(); + workspace.set_document("g", content); + let (diagnostics, peak) = peak_of(|| workspace.diagnostics("g")); + let payload = diagnostics + .iter() + .map(|d| d.message.len() + d.args.values().map(String::len).sum::()) + .sum(); + let cases = diagnostics + .iter() + .find(|d| d.code == DiagnosticCode::MissingCases) + .and_then(|d| d.args.get("count")) + .and_then(|count| count.parse().ok()) + .unwrap_or(0); + let incomplete = diagnostics + .iter() + .any(|d| d.code == DiagnosticCode::TableChecksIncomplete); + Measured { + peak, + payload, + cases, + incomplete, + } +} + +#[test] +fn schema_queries_stay_small_on_range_heavy_tables() { + let _guard = MEASURING + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + for rows in [500, 1000, 2000] { + let mut workspace = Workspace::new(); + workspace.set_document("g", range_table(0xA11C_E5ED_0000_0001, rows, 6)); + let request = ScopeRequest::for_policy("g"); + let (inputs, input_peak) = peak_of(|| workspace.inputs(&request)); + let (outputs, output_peak) = peak_of(|| workspace.outputs(&request)); + assert_eq!(inputs.len(), 6, "{rows} rows"); + assert!(!outputs.is_empty(), "{rows} rows"); + assert!( + input_peak < 8 * MIB, + "{rows} rows: deriving inputs peaked at {} KiB", + input_peak / 1024 + ); + assert!( + output_peak < 8 * MIB, + "{rows} rows: deriving outputs peaked at {} KiB", + output_peak / 1024 + ); + let diagnostics = workspace.diagnostics("g"); + assert!( + diagnostics.iter().any(|d| matches!( + d.code, + DiagnosticCode::MissingCases | DiagnosticCode::TableChecksIncomplete + )), + "{rows} rows: table checks still run for diagnostics" + ); + } +} + +fn mixed_table(seed: u64, rows: usize) -> DecisionContent { + let mut rng = Rng(seed); + let regions = [ + "north", "south", "east", "west", "central", "coastal", "inland", "island", + ]; + let terms = ["12", "24", "36", "48", "60", "> 60", "<= 36", ""]; + let ratios = ["< 0.2", "[0.2..0.35)", "[0.35..0.45)", ">= 0.45", ""]; + let spans: [(usize, usize, usize); 4] = [ + (18, 80, 1), + (10_000, 400_000, 5_000), + (1_000, 900_000, 1_000), + (300, 850, 10), + ]; + let mut properties = Map::new(); + properties.insert("region".into(), json!({ "type": "string" })); + let mut inputs = vec![json!({ "id": "region", "name": "Region", "field": "region" })]; + for index in 0..6 { + properties.insert(format!("n{index}"), json!({ "type": "number" })); + inputs.push(json!({ "id": format!("c{index}"), "name": format!("N{index}"), "field": format!("n{index}") })); + } + let required: Vec = properties.keys().cloned().collect(); + let schema = json!({ "type": "object", "properties": properties, "required": required }); + let rules: Vec = (0..rows) + .map(|row| { + let mut rule = Map::new(); + rule.insert("_id".into(), json!(format!("r{row}"))); + rule.insert( + "region".into(), + json!(format!("\"{}\"", regions[rng.below(regions.len())])), + ); + for (index, (min, max, step)) in spans.iter().enumerate() { + let low = (min / step + rng.below(max / step - min / step)) * step; + let high = low + (1 + rng.below(6)) * step; + let cell = match rng.below(5) { + 0 => format!("[{low}..{high})"), + 1 => format!(">= {low} and < {high}"), + 2 => format!("> {low}"), + 3 => format!("<= {high}"), + _ => String::new(), + }; + rule.insert(format!("c{index}"), json!(cell)); + } + rule.insert("c4".into(), json!(terms[rng.below(terms.len())])); + rule.insert("c5".into(), json!(ratios[rng.below(ratios.len())])); + rule.insert("o".into(), json!(format!("{}", rng.below(9)))); + Value::Object(rule) + }) + .collect(); + serde_json::from_value(json!({ + "nodes": [ + { "id": "in", "name": "request", "type": "inputNode", "content": { "schema": schema.to_string() } }, + { "id": "dt", "name": "table", "type": "decisionTableNode", "content": { + "hitPolicy": "first", + "inputs": inputs, + "outputs": [ { "id": "o", "name": "Out", "field": "out" } ], + "rules": rules, + "passThrough": true + } }, + { "id": "out", "name": "out", "type": "outputNode", "content": {} } + ], + "edges": [ + { "id": "e1", "sourceId": "in", "targetId": "dt" }, + { "id": "e2", "sourceId": "dt", "targetId": "out" } + ] + })) + .expect("graph") +} + +#[test] +fn finished_checks_on_range_heavy_tables_cost_memory_in_proportion_to_their_report() { + let _guard = MEASURING + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + for rows in [250, 500, 1000, 1500] { + let measured = diagnose(mixed_table(0x5EED_F00D_0000_0004, rows)); + assert!(!measured.incomplete, "{rows} rows: checks did not finish"); + assert!( + measured.cases > 1000, + "{rows} rows: {} missing cases", + measured.cases + ); + assert!( + measured.peak <= 4 * measured.payload + 2 * MIB, + "{rows} rows: peak {} KiB for {} KiB of diagnostics ({} missing cases)", + measured.peak / 1024, + measured.payload / 1024, + measured.cases + ); + } +} + +fn banded_table(bands: usize, columns: usize, hole_every: usize) -> DecisionContent { + let mut properties = Map::new(); + let inputs: Vec = (0..columns) + .map(|index| { + properties.insert(format!("n{index}"), json!({ "type": "number", "minimum": 0, "exclusiveMaximum": bands * 10 })); + json!({ "id": format!("c{index}"), "name": format!("N{index}"), "field": format!("n{index}") }) + }) + .collect(); + let required: Vec = properties.keys().cloned().collect(); + let schema = json!({ "type": "object", "properties": properties, "required": required }); + let mut rules: Vec = Vec::new(); + for combination in 0..bands.pow(columns as u32) { + let picks: Vec = (0..columns) + .map(|index| combination / bands.pow(index as u32) % bands) + .collect(); + if (combination.wrapping_mul(2_654_435_761) >> 7) % hole_every == 0 { + continue; + } + let mut rule = Map::new(); + rule.insert("_id".into(), json!(format!("r{combination}"))); + for (index, band) in picks.iter().enumerate() { + rule.insert( + format!("c{index}"), + json!(format!("[{}..{})", band * 10, (band + 1) * 10)), + ); + } + rule.insert("o".into(), json!(format!("{}", combination % 7))); + rules.push(Value::Object(rule)); + } + serde_json::from_value(json!({ + "nodes": [ + { "id": "in", "name": "request", "type": "inputNode", "content": { "schema": schema.to_string() } }, + { "id": "dt", "name": "table", "type": "decisionTableNode", "content": { + "hitPolicy": "first", + "inputs": inputs, + "outputs": [ { "id": "o", "name": "Out", "field": "out" } ], + "rules": rules, + "passThrough": true + } }, + { "id": "out", "name": "out", "type": "outputNode", "content": {} } + ], + "edges": [ + { "id": "e1", "sourceId": "in", "targetId": "dt" }, + { "id": "e2", "sourceId": "dt", "targetId": "out" } + ] + })) + .expect("graph") +} + +#[test] +fn missing_cases_cost_memory_in_proportion_to_their_number() { + let _guard = MEASURING + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + for bands in [6, 9, 12, 15] { + let measured = diagnose(banded_table(bands, 3, 3)); + assert!(!measured.incomplete, "{bands} bands: checks did not finish"); + assert!(measured.cases > 0, "{bands} bands: no missing cases"); + assert!( + measured.peak <= 4 * measured.payload + 8 * MIB, + "{bands} bands: peak {} KiB for {} KiB of diagnostics ({} missing cases)", + measured.peak / 1024, + measured.payload / 1024, + measured.cases + ); + } +} + +#[test] +fn range_heavy_table_checks_stay_within_a_fixed_ceiling() { + let _guard = MEASURING + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let mut finished = 0; + let mut incomplete = 0; + for (rows, columns) in [ + (250, 6), + (500, 5), + (1000, 5), + (2000, 5), + (1000, 6), + (4000, 6), + (8000, 6), + ] { + let measured = diagnose(range_table(0xB0B5_CAFE_0000_0002, rows, columns)); + finished += usize::from(!measured.incomplete); + incomplete += usize::from(measured.incomplete); + assert!( + measured.peak <= 4 * measured.payload + 64 * MIB, + "{rows}x{columns}: peak {} KiB for {} KiB of diagnostics ({} missing cases)", + measured.peak / 1024, + measured.payload / 1024, + measured.cases + ); + } + assert!( + finished >= 2, + "only {finished} tables finished their checks" + ); + assert!( + incomplete >= 2, + "only {incomplete} tables exhausted the budget" + ); +} + +fn decision_graph( + schema: Value, + inputs: Value, + outputs: Value, + rules: Vec, +) -> DecisionContent { + serde_json::from_value(json!({ + "nodes": [ + { "id": "in", "name": "request", "type": "inputNode", "content": { "schema": schema.to_string() } }, + { "id": "dt", "name": "table", "type": "decisionTableNode", "content": { + "hitPolicy": "first", + "inputs": inputs, + "outputs": outputs, + "rules": rules, + "passThrough": true + } }, + { "id": "out", "name": "out", "type": "outputNode", "content": {} } + ], + "edges": [ + { "id": "e1", "sourceId": "in", "targetId": "dt" }, + { "id": "e2", "sourceId": "dt", "targetId": "out" } + ] + })) + .expect("graph") +} + +fn lookup_table(rows: usize) -> DecisionContent { + let schema = json!({ + "type": "object", + "properties": { "status": { "type": "number" }, "code": { "type": "string" } }, + "required": ["status", "code"] + }); + let rules = (0..rows) + .map(|row| { + let status = ["200", "400", "500"][row % 3]; + json!({ + "_id": format!("r{row}"), + "s": status, + "c": format!("'CODE_{row:06}'"), + "o": format!("'REASON_{row:06}'") + }) + }) + .collect(); + decision_graph( + schema, + json!([ + { "id": "s", "name": "Status", "field": "status" }, + { "id": "c", "name": "Code", "field": "code" } + ]), + json!([ { "id": "o", "name": "Reason", "field": "reason" } ]), + rules, + ) +} + +fn banded_grid(rows: usize) -> DecisionContent { + let schema = json!({ + "type": "object", + "properties": { + "amount": { "type": "number" }, + "region": { "type": "string" }, + "tier": { "type": "string" }, + "flag": { "type": "boolean" }, + "age": { "type": "number" } + }, + "required": ["amount", "region", "tier", "flag", "age"] + }); + let regions = [ + "\"north\", \"south\"", + "\"east\"", + "\"west\", \"central\"", + "\"coastal\"", + ]; + let tiers = ["\"basic\"", "\"plus\"", "\"premium\""]; + let ages = [(18, 30), (30, 45), (45, 65), (65, 120)]; + let rules = (0..rows) + .map(|row| { + let band = row / (regions.len() * tiers.len() * 2 * ages.len()); + let (low, high) = ages[row % ages.len()]; + let region = regions[row / (tiers.len() * 2 * ages.len()) % regions.len()]; + let tier = tiers[row / (2 * ages.len()) % tiers.len()]; + let flag = match row / ages.len() % 2 { + 0 => "true", + _ => "false", + }; + json!({ + "_id": format!("r{row}"), + "a": format!(">= {} and < {}", band * 1000, (band + 1) * 1000), + "r": region, + "t": tier, + "f": flag, + "g": format!("[{low}..{high})"), + "o": format!("{}", band as f64 * 0.001) + }) + }) + .collect(); + decision_graph( + schema, + json!([ + { "id": "a", "name": "Amount", "field": "amount" }, + { "id": "r", "name": "Region", "field": "region" }, + { "id": "t", "name": "Tier", "field": "tier" }, + { "id": "f", "name": "Flag", "field": "flag" }, + { "id": "g", "name": "Age", "field": "age" } + ]), + json!([ { "id": "o", "name": "Rate", "field": "rate" } ]), + rules, + ) +} + +#[test] +fn lookup_tables_with_one_value_per_row_grow_linearly() { + let _guard = MEASURING + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let small = diagnose(lookup_table(10_000)); + let large = diagnose(lookup_table(40_000)); + assert!( + large.peak <= 6 * small.peak, + "four times the rows took {} KiB after {} KiB", + large.peak / 1024, + small.peak / 1024 + ); + assert!( + large.peak <= 40_000 * 2 * 1024, + "40,000 lookup rows peaked at {} KiB", + large.peak / 1024 + ); +} + +#[test] +fn compressible_grids_stay_under_two_kibibytes_a_row() { + let _guard = MEASURING + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + for rows in [20_000, 40_000] { + let mut workspace = Workspace::new(); + workspace.set_document("g", banded_grid(rows)); + let (diagnostics, peak) = peak_of(|| workspace.diagnostics("g")); + assert!( + diagnostics + .iter() + .any(|d| d.code == DiagnosticCode::CompressibleTable), + "{rows} rows: the grid should be reported as compressible" + ); + assert!( + peak <= rows * 2 * 1024 + 8 * MIB, + "{rows} rows peaked at {} KiB", + peak / 1024 + ); + } +} + +fn merging_lookup(rows: usize) -> DecisionContent { + let schema = json!({ + "type": "object", + "properties": { "status": { "type": "number" }, "code": { "type": "string" } }, + "required": ["status", "code"] + }); + let rules = (0..rows) + .map(|row| { + let code = row * 7919 % rows; + let status = ["200", "400", "500"][row % 3]; + json!({ + "_id": format!("r{row}"), + "s": status, + "c": format!("'CODE_{code:06}'"), + "o": "'BLOCKED'" + }) + }) + .collect(); + decision_graph( + schema, + json!([ + { "id": "s", "name": "Status", "field": "status" }, + { "id": "c", "name": "Code", "field": "code" } + ]), + json!([ { "id": "o", "name": "Reason", "field": "reason" } ]), + rules, + ) +} + +#[test] +fn lookup_rows_that_merge_into_one_cell_grow_linearly() { + let _guard = MEASURING + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let mut peaks = Vec::new(); + for rows in [10_000, 20_000, 40_000] { + let mut workspace = Workspace::new(); + workspace.set_document("g", merging_lookup(rows)); + let (diagnostics, peak) = peak_of(|| workspace.diagnostics("g")); + assert!( + diagnostics + .iter() + .any(|d| d.code == DiagnosticCode::CompressibleTable), + "{rows} rows: the lookup should be reported as compressible" + ); + assert!( + peak <= rows * 2 * 1024 + 2 * MIB, + "{rows} rows peaked at {} KiB", + peak / 1024 + ); + peaks.push(peak); + } + assert!( + peaks[1] <= 3 * peaks[0], + "twice the rows took {} KiB after {} KiB", + peaks[1] / 1024, + peaks[0] / 1024 + ); +} diff --git a/core/expression/src/intellisense/values/mod.rs b/core/expression/src/intellisense/values/mod.rs index ddae18a5..7c97473a 100644 --- a/core/expression/src/intellisense/values/mod.rs +++ b/core/expression/src/intellisense/values/mod.rs @@ -1,3 +1,4 @@ pub mod cell; pub mod print; +pub mod strings; pub mod value_set; diff --git a/core/expression/src/intellisense/values/strings.rs b/core/expression/src/intellisense/values/strings.rs new file mode 100644 index 00000000..c790f70b --- /dev/null +++ b/core/expression/src/intellisense/values/strings.rs @@ -0,0 +1,343 @@ +use std::cmp::Ordering; +use std::collections::{btree_set, BTreeSet}; +use std::fmt; +use std::hash::{Hash, Hasher}; +use std::rc::Rc; +use std::slice; + +#[derive(Clone)] +pub struct Strings(Repr); + +#[derive(Clone)] +#[allow(clippy::box_collection)] +enum Repr { + One(Rc), + Few(Box<[Rc]>), + Many(Box>>), +} + +impl Strings { + const FEW: usize = 32; + + pub fn new() -> Self { + Self(Repr::Few(Box::default())) + } + + pub fn one(value: Rc) -> Self { + Self(Repr::One(value)) + } + + fn sorted(values: Vec>) -> Self { + if values.len() > Self::FEW { + return Self(Repr::Many(Box::new(values.into_iter().collect()))); + } + match <[Rc; 1]>::try_from(values) { + Ok([only]) => Self(Repr::One(only)), + Err(values) => Self(Repr::Few(values.into_boxed_slice())), + } + } + + pub fn len(&self) -> usize { + match &self.0 { + Repr::One(_) => 1, + Repr::Few(values) => values.len(), + Repr::Many(values) => values.len(), + } + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + pub fn iter(&self) -> Iter<'_> { + Iter(match &self.0 { + Repr::One(only) => Walk::List(slice::from_ref(only).iter()), + Repr::Few(values) => Walk::List(values.iter()), + Repr::Many(values) => Walk::Tree(values.iter()), + }) + } + + pub fn contains(&self, value: &str) -> bool { + match &self.0 { + Repr::One(only) => &**only == value, + Repr::Few(values) => values.binary_search_by(|held| (**held).cmp(value)).is_ok(), + Repr::Many(values) => values.contains(value), + } + } + + pub fn union(&self, other: &Self) -> Self { + if other.is_empty() { + return self.clone(); + } + if self.is_empty() { + return other.clone(); + } + let mut out = Vec::with_capacity(self.len() + other.len()); + let mut left = self.iter().peekable(); + let mut right = other.iter().peekable(); + loop { + let order = match (left.peek(), right.peek()) { + (Some(a), Some(b)) => a.cmp(b), + (Some(_), None) => Ordering::Less, + (None, Some(_)) => Ordering::Greater, + (None, None) => break, + }; + match order { + Ordering::Less => out.extend(left.next().cloned()), + Ordering::Greater => out.extend(right.next().cloned()), + Ordering::Equal => { + out.extend(left.next().cloned()); + right.next(); + } + } + } + Self::sorted(out) + } + + pub fn intersection(&self, other: &Self) -> Self { + let (small, large) = if self.len() <= other.len() { + (self, other) + } else { + (other, self) + }; + Self::sorted( + small + .iter() + .filter(|value| large.contains(value)) + .cloned() + .collect(), + ) + } + + pub fn difference(&self, other: &Self) -> Self { + if other.is_empty() { + return self.clone(); + } + Self::sorted( + self.iter() + .filter(|value| !other.contains(value)) + .cloned() + .collect(), + ) + } +} + +impl Default for Strings { + fn default() -> Self { + Self::new() + } +} + +impl PartialEq for Strings { + fn eq(&self, other: &Self) -> bool { + self.len() == other.len() && self.iter().eq(other.iter()) + } +} + +impl Eq for Strings {} + +impl Hash for Strings { + fn hash(&self, state: &mut H) { + state.write_usize(self.len()); + for value in self { + value.hash(state); + } + } +} + +impl fmt::Debug for Strings { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_set().entries(self).finish() + } +} + +impl FromIterator> for Strings { + fn from_iter>>(values: I) -> Self { + let mut values: Vec> = values.into_iter().collect(); + if !values.windows(2).all(|pair| pair[0] < pair[1]) { + values.sort_unstable(); + values.dedup(); + } + Self::sorted(values) + } +} + +impl From>> for Strings { + fn from(values: BTreeSet>) -> Self { + if values.len() > Self::FEW { + return Self(Repr::Many(Box::new(values))); + } + Self::sorted(values.into_iter().collect()) + } +} + +impl Extend> for Strings { + fn extend>>(&mut self, values: I) { + if let Repr::Many(held) = &mut self.0 { + held.extend(values); + return; + } + let mut all: Vec> = self.iter().cloned().collect(); + all.extend(values); + *self = all.into_iter().collect(); + } +} + +impl<'a> IntoIterator for &'a Strings { + type Item = &'a Rc; + type IntoIter = Iter<'a>; + + fn into_iter(self) -> Iter<'a> { + self.iter() + } +} + +#[derive(Clone)] +pub struct Iter<'a>(Walk<'a>); + +#[derive(Clone)] +enum Walk<'a> { + List(slice::Iter<'a, Rc>), + Tree(btree_set::Iter<'a, Rc>), +} + +impl<'a> Iterator for Iter<'a> { + type Item = &'a Rc; + + fn next(&mut self) -> Option { + match &mut self.0 { + Walk::List(values) => values.next(), + Walk::Tree(values) => values.next(), + } + } + + fn size_hint(&self) -> (usize, Option) { + match &self.0 { + Walk::List(values) => values.size_hint(), + Walk::Tree(values) => values.size_hint(), + } + } +} + +impl DoubleEndedIterator for Iter<'_> { + fn next_back(&mut self) -> Option { + match &mut self.0 { + Walk::List(values) => values.next_back(), + Walk::Tree(values) => values.next_back(), + } + } +} + +impl ExactSizeIterator for Iter<'_> {} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::hash_map::DefaultHasher; + + struct Random(u64); + + impl Random { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn below(&mut self, limit: usize) -> usize { + (self.next() % limit as u64) as usize + } + + fn values(&mut self, pool: &[Rc]) -> Vec> { + let size = match self.below(6) { + 0 => 0, + 1 => 1, + 2 => 2 + self.below(6), + 3 => Strings::FEW - 1 + self.below(3), + _ => self.below(pool.len()), + }; + (0..size) + .map(|_| pool[self.below(pool.len())].clone()) + .collect() + } + } + + fn pool(size: usize) -> Vec> { + (0..size) + .map(|i| Rc::from(format!("v{:03}", (i * 37) % size))) + .collect() + } + + fn hash_of(value: &impl Hash) -> u64 { + let mut hasher = DefaultHasher::new(); + value.hash(&mut hasher); + hasher.finish() + } + + fn listed(set: &Strings) -> Vec> { + set.iter().cloned().collect() + } + + fn expected<'a>(values: impl Iterator>) -> Vec> { + values.cloned().collect() + } + + #[test] + fn matches_a_tree_set_on_random_inputs() { + let pool = pool(120); + let mut random = Random(0x9e37_79b9_7f4a_7c15); + for _ in 0..4_000 { + let (left, right) = (random.values(&pool), random.values(&pool)); + let (a, b): (Strings, Strings) = ( + left.iter().cloned().collect(), + right.iter().cloned().collect(), + ); + let (x, y): (BTreeSet>, BTreeSet>) = ( + left.iter().cloned().collect(), + right.iter().cloned().collect(), + ); + + assert_eq!(listed(&a), expected(x.iter())); + assert_eq!(a.len(), x.len()); + assert_eq!(a.is_empty(), x.is_empty()); + assert_eq!(listed(&a.union(&b)), expected(x.union(&y))); + assert_eq!(listed(&a.intersection(&b)), expected(x.intersection(&y))); + assert_eq!(listed(&a.difference(&b)), expected(x.difference(&y))); + assert_eq!( + a.iter().rev().cloned().collect::>(), + x.iter().rev().cloned().collect::>() + ); + for value in &pool { + assert_eq!(a.contains(value), x.contains(value)); + } + assert_eq!(a == b, x == y); + assert_eq!(hash_of(&a), hash_of(&x)); + assert_eq!(format!("{a:?}"), format!("{x:?}")); + assert_eq!(Strings::from(x.clone()), a); + + let mut grown = a.clone(); + grown.extend(right.iter().cloned()); + assert_eq!(grown, a.union(&b)); + assert_eq!(hash_of(&grown), hash_of(&a.union(&b))); + } + } + + #[test] + fn grows_one_value_at_a_time_across_every_size() { + let pool = pool(200); + let mut set = Strings::new(); + let mut tree = BTreeSet::new(); + for value in &pool { + set.extend([value.clone()]); + tree.insert(value.clone()); + assert_eq!(listed(&set), expected(tree.iter())); + assert_eq!(set, tree.iter().cloned().collect::()); + } + } + + #[test] + fn stays_three_words_wide() { + assert!(size_of::() <= 3 * size_of::()); + } +} diff --git a/core/expression/src/intellisense/values/value_set.rs b/core/expression/src/intellisense/values/value_set.rs index d63a8a19..8fb95097 100644 --- a/core/expression/src/intellisense/values/value_set.rs +++ b/core/expression/src/intellisense/values/value_set.rs @@ -5,6 +5,8 @@ use std::rc::Rc; use rust_decimal::Decimal; use serde_json::Value; +pub use super::strings::Strings; + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Bound { Unbounded, @@ -307,19 +309,19 @@ impl NumberSet { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum StringSet { - Finite(BTreeSet>), - CoFinite(BTreeSet>), + Finite(Strings), + CoFinite(Strings), } impl Default for StringSet { fn default() -> Self { - StringSet::Finite(BTreeSet::new()) + StringSet::Finite(Strings::new()) } } impl StringSet { pub fn all() -> Self { - StringSet::CoFinite(BTreeSet::new()) + StringSet::CoFinite(Strings::new()) } pub fn is_empty(&self) -> bool { @@ -339,31 +341,23 @@ impl StringSet { pub fn union(&self, other: &Self) -> Self { match (self, other) { - (StringSet::Finite(a), StringSet::Finite(b)) => { - StringSet::Finite(a.union(b).cloned().collect()) - } + (StringSet::Finite(a), StringSet::Finite(b)) => StringSet::Finite(a.union(b)), (StringSet::CoFinite(a), StringSet::CoFinite(b)) => { - StringSet::CoFinite(a.intersection(b).cloned().collect()) + StringSet::CoFinite(a.intersection(b)) } (StringSet::Finite(f), StringSet::CoFinite(c)) | (StringSet::CoFinite(c), StringSet::Finite(f)) => { - StringSet::CoFinite(c.difference(f).cloned().collect()) + StringSet::CoFinite(c.difference(f)) } } } pub fn intersect(&self, other: &Self) -> Self { match (self, other) { - (StringSet::Finite(a), StringSet::Finite(b)) => { - StringSet::Finite(a.intersection(b).cloned().collect()) - } - (StringSet::CoFinite(a), StringSet::CoFinite(b)) => { - StringSet::CoFinite(a.union(b).cloned().collect()) - } + (StringSet::Finite(a), StringSet::Finite(b)) => StringSet::Finite(a.intersection(b)), + (StringSet::CoFinite(a), StringSet::CoFinite(b)) => StringSet::CoFinite(a.union(b)), (StringSet::Finite(f), StringSet::CoFinite(c)) - | (StringSet::CoFinite(c), StringSet::Finite(f)) => { - StringSet::Finite(f.difference(c).cloned().collect()) - } + | (StringSet::CoFinite(c), StringSet::Finite(f)) => StringSet::Finite(f.difference(c)), } } @@ -456,7 +450,7 @@ impl ValueSet { pub fn string(s: &str) -> Self { Self { - strings: StringSet::Finite(BTreeSet::from([Rc::from(s)])), + strings: StringSet::Finite(Strings::one(Rc::from(s))), ..Self::empty() } } @@ -531,8 +525,8 @@ impl ValueSet { } out.numbers = NumberSet::from_intervals(intervals); out.strings = match cofinite { - Some(acc) => acc.union(&StringSet::Finite(finite)), - None => StringSet::Finite(finite), + Some(acc) => acc.union(&StringSet::Finite(finite.into())), + None => StringSet::Finite(finite.into()), }; out } @@ -693,7 +687,7 @@ mod tests { let pair = ValueSet::strings([Rc::from("gold"), Rc::from("silver")]); assert_eq!( pair.difference(&gold).strings, - StringSet::Finite(BTreeSet::from([Rc::from("silver")])) + StringSet::Finite(Strings::one(Rc::from("silver"))) ); }