Repository navigation
Collect several column-statistics sets per column in one pass (stack 2/5) - #318
Conversation
A standard-library-only module for process-wide settings shared by the Kumo packages. It holds the scratch directory: configure(scratch_dir=...), scratch_dir() and scoped(scratch_dir=...), plus the KUMO_SCRATCH_DIR environment variable. Resolution is scoped, then configure, then the environment, then ~/.cache/kumo-engine. The path must be local; configure creates it if missing. Co-Authored-By: Claude Opus 5.5 <[email protected]>
kumo.engine.configure delegates to kumo.settings.configure, the scratch helpers resolve through kumo.settings.scratch_dir(), and batch prediction scopes its scratch directory with kumo.settings.scoped. kumo-engine now depends on kumo-settings, so the engine wheel bundles it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
kumo.settings.configure only records the path again, as the engine's configure did: callers create what they write, and configuring a scratch directory inside a FileConnector root writes nothing there. The license metadata inventory now counts kumo-settings. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the public scoped block and the KUMO_SCRATCH_DIR variable; the engine keeps its private scoped scratch directory for in-process model serving. Co-Authored-By: Claude <[email protected]>
Co-Authored-By: Claude <[email protected]>
Co-Authored-By: Claude <[email protected]>
FileColStats keeps each column's collector at its column index and any further collectors of a column after them, so one pass can fill several collectors per column. Each observer method feeds the column's own collector, then its further ones. col_stats.json merges a column's collectors into one object, and Kumo-format stats iterate every collector. Semantic-type callers still build one collector per column, so their output is unchanged. Co-Authored-By: Claude <[email protected]>
A StatSet names the semantic types whose statistics a column collects, so one pass can give a column category counts and moments: StatSet::COUNTS | StatSet::MOMENTS. FileColStats::new_with_stat_sets takes one StatSet per column, and TableCategoryCounts accepts stat sets as well as semantic types. A semantic type maps to the StatSet of its own statistics, so existing callers build the same collectors. A Text collector that shares a column with category counts takes its distinct count from HyperLogLog when the counts are capped, as Categorical does. Co-Authored-By: Claude <[email protected]>
Change map#306 needs category counts and moments for the same column, and before this PR that took one pass per semantic type. This PR lets a column hold several of the existing collectors and feeds them all in one pass. No statistic or output format is added. Verification: callers that pass semantic types build the same collectors as before. The existing Rust and Python col-stats tests pass unchanged, including the SHA-256-pinned output test. One new test checks that a A column that needs both sets is read and decoded once instead of twice (expected, not measured). Rejected: two
|
|
Caution Review failedThe pull request is closed. Walkthrough
Pre-merge checks:
|
| Check name | Status | Explanation |
|---|---|---|
| Pr Size | The PR size check counts changed files and fails only above 40. The local checkout has the PR branch at 841e8b3. Its merge base with origin/main is 8b4942f. `git diff --name-status -M origin/main...… | |
| Public Resource Access | The check applies only to external resource references added or modified by this pull request. I compared the PR's own code changes (d161417^..HEAD, which covers the col_stats.rs rewrite and the kumo… |
Full details: Pr Size
-
Explanation
The PR size check counts changed files and fails only above 40. The local checkout has the PR branch at 841e8b3. Its merge base with origin/main is 8b4942f.
git diff --name-status -M origin/main...HEADlists 22 changed files (722 insertions, 159 deletions). The branch has 12 commits beyond origin/main, including the stacked#299kumo-settings commits. The PR-only diff against the#299base cannot contain more files than this full diff, so the count is at most 22. That is below the 40-file threshold. Author context: primary PR #318, author login Vedaant-J. Line counts are ignored, as the check requires. No failure message or split recommendation applies.
Full details: Public Resource Access
-
Explanation
The check applies only to external resource references added or modified by this pull request. I compared the PR's own code changes (d161417^..HEAD, which covers the col_stats.rs rewrite and the kumo-pytorch e2e README edit) against their parent. They add no URL, git, registry, or package-source reference. The only README change replaces a local
$KE/packages/kumo-settingspath with another local path inside this repository, which is not an external reference. A wider scan from c707dbb^ (earlier stack commits that may belong to#299) found three URL-like additions: an Apache license header, another Apache license header, and ans3://bucket/scratchtest parameter. The license headers are boilerplate and are not needed to build, test, or use the changed code. The s3 value is a test fixture. The PR description's links (#299,#306, a GitHub comment, claude.com) are not repository reference text in the diff. Result: the PR adds no external resource reference that needs an anonymous-access check.
Full details: Change Map Design Review
-
Explanation
Summary: The change map is PR conversation comment 6837958197 (author Vedaant-J). It starts with
<!-- kumo-pr-change-map -->. The core design is sound. AStatSetbitset feeds a collector list. The first collector stays at the column index. Further collectors follow. The map gives a concrete reason for rejecting the two-FileColStatsalternative. The map still has four substantive gaps, and the current comment text does not fix them. The prior FAIL claims are confirmed. Evidence checked againstpackages/diskgraph/diskgraph-ingest/src/col_stats.rsat HEAD 841e8b3: 1. Omitted semantic_type behavior (confirmed). The map says only that "the first value of a shared key wins."StatSet::stypes()(lines 745–761) listsCategoricalbeforeNumerical.add_column_json(lines 830–841) usesor_insert. A column withCOUNTS | MOMENTStherefore writes"semantic_type": "categorical"intocol_stats.json, even when the declared type is numerical. The map does not state this. The same rule coverscount,null_countandnum_unique. The consequence matters for#306consumers, which the map names as the user of this design. This is an uncertain design question, not a proven defect. The map must state the rule and its effect. 2. Unverified Text arm (confirmed). TheTextarm ofkumo_stats(lines 2319–2324) now uses the exhaustive-map length or HLL. A Text column can now hold category counts throughStatSet::from(Some(SemanticType::Text))combined withCOUNTS. The only new test,stat_set_collects_counts_and_moments_in_one_pass(line 6325), builds an Int64 column viamake_test_cols_with_types(&[(None, IngestedType::Int64, None)]). No test covers the Text path. The map does not mark this branch as untested. 3. Misleading hot-path claim (confirmed). TheFileColStatsrow says "the single-collector layout and hot path unchanged." Theobserve_each_collector!macro (lines 3215–3231) runsself.extra_cols.partition_point(...)and agetcheck on every observed value (line 3222). The cost is small for single-collector columns. The benchmark (74.4–77.5 vs 75.1–77.4 ns/value) is in the PR description, not in the map. "Unchanged" is inaccurate. 4. Unstated API effect (confirmed as a risk).TableCategoryCounts::new(lines 225–231) changed from&[Option<SemanticType>]to&[impl Copy + Into<StatSet>]. The map says semantic-type callers "compile unchanged," which holds for typed slices. It does not mention that a bare&[]literal now has no element type to infer. No in-repo caller uses&[](checked withrgacross the workspace). I could not compile, so this remains a risk to document, not a proven break. Scope: This verdict covers the map's explanation and verification. It does not claim a code defect in the implementation.Resolution
Revise the change map comment (6837958197) as follows: 1. semantic_type rule. Replace "the first value of a shared key wins" with an explicit rule. For a column with several collectors,
semantic_type,count,null_countandnum_uniqueincol_stats.jsoncome from the first collector in stat-set order (Categorical before Numerical; seeStatSet::stypes). State that aCOUNTS | MOMENTScolumn on a numerical source reports"semantic_type": "categorical". Either document this for#306consumers, or change the design so the output carries the declared semantic type. Keep the design as is if the documented rule is acceptable. 2. Text verification. Add a test with a Text column that has category counts. It should cover the exhaustive-map case (NUM_UNIQUEfrom map length) and the capped or subsampled case (HLL fallback). Or state in the map that this branch is untested and why. 3. Hot path. Replace "hot path unchanged" with the actual cost. Each observed value now runspartition_pointonextra_colsand onegetcheck (observe_each_collector!). Cite the benchmark result from the PR description (74.4–77.5 vs 75.1–77.4 ns/value, one thread, 30M rows). 4. API signature. Note theTableCategoryCounts::newsignature change. State whether&[]callers still compile. If they do not, document the typed form (for example&[] as &[Option<SemanticType>]). Keep the design unless item 1 changes the required output.
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
kumo.engine imports kumo.settings, and the README installs kumo-engine with --no-deps. Co-Authored-By: Claude <[email protected]>
It checks that a column has category counts exactly when its stat set counts them. The shared counts do not record which stat set built them. Co-Authored-By: Claude <[email protected]>
Co-Authored-By: Claude <[email protected]>
|
Reply to the CodeRabbit Change Map Design Review check.
|
Victsm
left a comment
There was a problem hiding this comment.
Reviewed the collector slot mapping, default statistics compatibility and one-pass reuse of existing collectors. The focused combined-collector test passes; no correctness blocker found.
…k 3/5) (#306) Stack 3/5. Merge order: #299 (`kumo.settings`), #318 (`StatSet`), then this PR (it contains #318's commits; review the commits after #318), then #307 (Text tokenizers trained inside DiskGraph), then #324 (fitting without samples). ## Summary In kumo-pytorch, an encoder over a **stored table column** now fits on the table's rows created at or before an *encoder cutoff*, not on the training examples. This covers `Vocabulary`, `ZScore` and `Buckets(bins=N)` over an entity field, an event field or a graph node field. The numbers come from **DiskGraph's existing col-stats pipeline**, the `FileColStats` and `TableCategoryCounts` collectors behind `col_stats.json`: - `Vocabulary` uses the Hybrid category counts, capped at 1M distinct values. - `ZScore` uses Welford's mean and standard deviation. - `Buckets` uses the t-digest. This PR adds three hooks to that pipeline: 1. A per-row cutoff gate during ingest. 2. A recompute that reads an index's stored rows and drives them through the Arrow driver `compute_col_stats_for_parquet` already uses. 3. t-digest quantiles published on request. It also fills gaps in the pipeline, listed under "Statistics added to the pipeline" below. Both routes write the existing `col_stats.json` format, one file per table, under `<index>/col_stats/<cutoff dir>/`. A column's statistics are requested by #318's `StatSet`, so one pass computes everything a column needs. > **Behaviour change.** An encoder over a stored column learns from every table row created at or before the cutoff, **whatever `fit_split` selects**. Rows of held-out or unassigned entities count too. Vocabularies, z-score statistics and bucket cuts change, and so do model metrics. These still fit on the examples, as before: per-anchor values (aggregates, calculations, targets), `Text` (until #307), and an encoder shared through `UseEncoding` with a per-anchor value. > **Not in this PR.** Fitting still builds samples. `Plan.materialize` still fetches every fitting anchor, and `fit_plan` still builds samples whenever anything needs fitting, even when every input encoder is pinned from statistics. A follow-up PR stacked on #307 removes that. ## What changes for users ### kumo-pytorch | API | Accepts | Default | Errors and warnings | | --- | --- | --- | --- | | `Plan.materialize(..., encoder_cutoff=...)` | ISO 8601 string (validated by `datetime.fromisoformat`, its value exact to the nanosecond from `diskgraph.resolve_temporal`), epoch seconds (`int`, as an anchor takes them), `datetime`, `date`, or `None` (every row) | `LATEST_ANCHOR`: the latest anchor time in `fit_split` | `ValueError: encoder_cutoff 'soon' is not an ISO 8601 timestamp`; `TypeError` for other types. A cutoff later than the latest fitting anchor, or `None` on a temporal contract, logs `encoder_cutoff … is after the latest fitting anchor …`. | | `DiskGraphEngine(..., encoder_cutoffs=[...])` | A list of the same values | `()` | `TypeError: encoder_cutoffs is a list of cutoffs; wrap a single one in a list` for a bare string. When an ingest builds the index, the statistics for these cutoffs are computed in the same pass. | | `FitRecord["statistics"]` (inputs only) | — | — | `{"cutoff": <epoch nanoseconds or None>, "col_stats": ["<dir>/<table>.col_stats.json", ...]}`. Informational: fitted-state equality and fingerprints ignore it. | Other errors and warnings: - `Vocabulary` over a column with more than 1M distinct values logs `<table>.<column> has more distinct values than DiskGraph counts; encoder … learns the ones it counted`. - `ZScore` or `Buckets` over a column holding NaN or ±inf raises `ValueError: encoder …: numeric transforms require finite values`. - `Vocabulary` over a float column holding NaN or ±inf raises `ValueError: float32 vocabulary values must be finite` (or the `float64` equivalent). ### DiskGraph Python | Function | Signature and return | Notes | | --- | --- | --- | | `diskgraph.ingest` | New keyword `cutoff_col_stats: str \| None = None` (request JSON) | Collects during Encode and adds each table's statistics to `col_stats/<dir>/<table>.col_stats.json` at the end of Encode. The table name is percent-encoded in the file name: every byte except ASCII letters, digits, `-` and `_`. Errors: `col_stats and cutoff_col_stats are exclusive`, unknown table or column, `column … requests more than one kind of category counts`, `one directory per cutoff`, `each cutoff needs its own directory`, a non-local output. | | `diskgraph.cutoff_col_stats(index_dir, request_json, num_threads=None) -> None` | Recomputes the request from the index's stored rows and adds it to the same files | The same validation. A column already in a file keeps its keys and gains the new ones. | | `diskgraph.convert_ticks(value, from, to, *, rounding="truncate") -> int` | A value in one index clock as ticks of another; `rounding` is `"truncate"` or `"floor"`. The encoder cutoff converts from `nanoseconds` with `rounding="floor"`. The same binding as #310 | `convert_ticks requires fixed index clocks`; `rounding must be truncate or floor`; never raises on precision | The request JSON: ```json {"cutoffs": [1694608000, null], // index-clock ticks; null counts every row "dirs": ["3f2a91c0d4e5b678", "…"], // col_stats/<dir>/ of each cutoff "columns": {"events": {"amount": ["categorical", "numerical"], "channel": ["categorical"]}}, "quantiles": [0.0, 0.0009765625, …, 1.0]} // t-digest quantiles every numerical column publishes ``` Each column lists the semantic types whose statistics it collects; #318's `StatSet` collects all of them in one pass. ### DiskGraph Rust | API | Added or changed | | --- | --- | | `IngestOptions::cutoff_col_stats: Option<CutoffColStatsRequest>` | New option, default `None` | | `cutoff_col_stats::{CutoffColStatsRequest, CutoffTable, CutoffSinks}` | New module. `columns` maps table → column → `Vec<SemanticType>`, built into #318's `StatSet`; `CutoffTable::sinks() -> Result<CutoffSinks>` | | `column_scan::{node_chunks, scan_chunk, ScanBudget, create_times, at_cutoff}` | New module: a chunk's stored rows in batches of at most about 128 MiB of decoded values, each admitted by a `ScanBudget` (ingest's `ByteBudget`) shared by the workers; #307 builds its text scan on it | | `ColumnValueObserver::{observe_bytes, observe_decimal, observe_u64, wants_create_time, start_row, finish_row}` | New default methods. `observe_decimal` defaults to `observe_f64` and `observe_u64` to `observe_i64` of the value's bits, so other observers see the same calls as before; `finish_row(stored)` follows each encoded row. | | `FloatListView`, `IntListView`, `StringListView` and their value enums | Derive `Clone` | | `FileColStats::{with_quantiles, collects, counts_categories}`, `col_stats::bytes_hex` | New; `collects` and `counts_categories` look at every collector of a column | | `decimal_i128_to_f64`, `decimal_i256_to_f64`, `format_decimal_i128`, `format_decimal_i256` | Made public | | diskgraph-ingest's `serde_json` | `raw_value` feature, so values already in a file are copied as written | | `diskgraph_rowpack::builder_value_bytes` | New: the decoded value bytes in a builder from `make_arrow_builder` | | `TDigestEstimator` merge and quantile | Each mean is weighed separately when a sum or difference overflows near ±f64::MAX; other values are unchanged | | diskgraph-pybind crate version | 0.1.0 → 0.2.0, so `diskgraph.__version__` matches the package | ### Statistics added to the pipeline (every col-stats consumer) | Encoder and column type | Gap | Fix | Lines | | --- | --- | --- | --- | | `Vocabulary` over `timestamp` | Categorical timestamp columns had no counts | `FileColStats::observe_timestamp` counts them, keyed by index-clock ticks | ~5 | | `Vocabulary` over `bytes` | Ingest never observed bytes values | `encode_row_observed` calls `observe_bytes`; `FileColStats` counts lowercase hex (`bytes_hex`, now shared with the Arrow driver) | ~17 | | `Vocabulary` over decimals | Keys were the f64 rendering, so wide decimals collided | `observe_decimal` gives categorical columns the exact decimal string, on both routes | ~25 | | `ZScore`/`Buckets` over `decimal256` | Ingest never observed `decimal256` | Observed through `observe_decimal` | ~6 | | Any encoder over `uint64` values of 2^63 and above | They were observed as their bits reinterpreted as an `i64`, so moments, quantiles and value bins saw negative numbers, and counts were keyed by them | `observe_u64` on both routes: numerical statistics see the value as an `f64`, and category counts key it by its exact decimal text | ~30 | | Any encoder over `date32` or a decimal, recompute route | The Arrow driver refused these types | `drive_from_arrow_column` reads them as ingest observes them | ~25 | | `Buckets(bins=N)` | Only q25/q50/q75 were published | Requested t-digest quantiles appear as `"quantiles"` | ~15 | ## How it works 1. **Which encoders qualify** (`kumo/pytorch/column_stats.py: table_column_encoders, _learns_from_stats`). An unpinned `Vocabulary`, `ZScore` or `Buckets(bins=N)` qualifies when every use reads a stored column directly; `ZScore` and `Buckets` additionally need a numeric dtype. A `UseEncoding` shared by several stored columns combines them; one shared with a per-anchor value keeps the old path. 2. **The request** (`column_stats.py: stats_request`, `TableColumnEncoder.requests`). - `Vocabulary` asks for its columns' `categorical` statistics (counts); `ZScore` and `Buckets` ask for `numerical` (moments, t-digest, value bins). - A column read by several encoder kinds is requested once, with every type it needs. - Every request carries the quantile grid (1,025 probabilities), which every numerical column publishes. - Cutoffs that land on the same index-clock tick are requested once (`materialization.py: ensure_diskgraph_index`). 3. **Ingest route** (`diskgraph-ingest/src/lib.rs`). - In the Encode loop, `CutoffSinks` (`cutoff_col_stats.rs`) holds one `FileColStats` per cutoff, built with #318's `new_with_stat_sets`. - Before each row is encoded, `write_node_row_from_access` reads its create time with `access.get_timestamp` and calls `start_row`, which marks the cutoffs that include the row. - The requested columns' observations are held in buffers reused across rows (`Row`: one `Vec` of values, one `String`, one byte `Vec`). Once warm, a row allocates nothing, except to format a categorical decimal's exact text and to copy a list column parsed from text. - After the row passes ingest's null-create-time drop and the `MAX_NODE_DATA_LEN` check, `finish_row(true)` replays the observations into each marked cutoff's `FileColStats`, which feeds every collector of the column. A row the index doesn't store calls `finish_row(false)` and counts nowhere. - Worker sinks are merged with `FileColStats::merge`. - At the end of Encode, each cutoff's tables are published as described in step 7. 4. **Recompute route** (`diskgraph-pybind/src/cutoff_col_stats.rs: from_index`). - Chunks of 65,536 nodes (`column_scan::node_chunks`) are scanned in parallel with `scan_chunk`. It decodes rows one at a time into Arrow builders with `decode_row_to_builders`, as the engine's feature fetch does, and hands over a batch once its decoded values reach 128 MiB (`builder_value_bytes`). This matters because dictionary, LZ4, BPE and alphabet strings can decode to far more than they store. - Before decoding a batch, a worker takes a permit from one `ScanBudget`: ingest's `ByteBudget`, sized as ingest sizes Encode's (a third of the machine's or cgroup's memory, at least 1 GiB). A batch that ends below 128 MiB shrinks its permit to what it holds. One that ends above, such as a single larger row, trades its permit for one of its actual size, through ingest's oversized path. - Each batch is filtered per cutoff (`create_times`, `at_cutoff`) and driven through the existing `bp_col_stats::drive_from_arrow_column` into the same sinks. Values are dispatched on their stored type, as ingest observes them. - Results merge in chunk order, then publish as in step 7. Windows of four chunks per worker keep a few sinks per worker alive at once. 5. **In memory** (`engines/in_memory/source.py: column_stats`). The rows of the requested tables, normalized to their dtypes, are written to Parquet and ingested into one temporary index, and `read_column_stats` computes the request from it. 6. **Encoders from the numbers** (`column_stats.py: fit_from_stats`). - **`Vocabulary`**: from `category_counts`, ordered as `fit_encoder` orders them, with `min_frequency` and `max_size` applied. - **`ZScore`**: Welford's mean and sample standard deviation, converted to the population standard deviation and combined exactly across columns. - **`Buckets`**: each column publishes its t-digest at the 1,025 grid points. The N cuts are interpolated from the combined distribution of the encoder's columns. `separate_zero` first removes the exact zeros, counted from `value_bins`. 7. **Storage and reuse** (`column_stats.py: read_column_stats`; `cutoff_col_stats.rs: publish`). - `<dir>` is the first 16 hex characters of the sha256 of `[COL_STATS_RECIPE, cutoff ticks, clock unit]`. `COL_STATS_RECIPE = 1` is a format version, bumped whenever a request's statistics change. - kumo-pytorch reads `<dir>/<table>.col_stats.json` for each requested table and asks DiskGraph only for the column statistics those files lack: `category_counts` for categorical, `mean` for numerical. - DiskGraph writes each table with `write_col_stats` into a temporary directory beside the files. Holding an exclusive lock on the directory's `.lock` file, it adds the new columns, and the new keys of columns already there, copying every value as written. It then syncs the file and replaces the old one with a rename. - An Encode retry deletes `col_stats/` with the rest of Encode's outputs (`wipe_phase_outputs`), so a failed attempt's statistics never survive into the retry. - `fitted=` and `inference=True` read nothing. ## Storage `<index>/` after the first `materialize` (from the 200M-row benchmark index): ``` before after index/ index/ ├── diskgraph_config.json ├── diskgraph_config.json ├── index_manifest.json ├── index_manifest.json ├── index_metadata.json ├── index_metadata.json ├── ingest_stats.json ├── ingest_stats.json └── nodes/… ├── nodes/… └── col_stats/ └── 3f2a91c0d4e5b678/ one per encoder cutoff ├── events.col_stats.json DiskGraph's col_stats.json format, one table └── users.col_stats.json ``` From `events.col_stats.json` (lists truncated): ```json {"events": {"amount": {"semantic_type": "numerical", "count": 150003117, "null_count": 0, "invalid_count": 0, "mean": 33.1167359324272, "std": 43.410330297599934, "q25": …, "quantiles": [0.08, 0.9098560657984863, …], "value_bins": [[0.078125, 1], …], …}, "channel": {"semantic_type": "categorical", "count": 150003117, "null_count": 0, "category_counts": [["channel_01", 39380114], …], "category_counts_capped": false, …}}} ``` A column requested as both types holds both sets of keys; shared keys (`semantic_type`, `count`, `num_unique`) come from the categorical statistics. ## Semantics to check - **Cutoff.** A string cutoff must read as `datetime.fromisoformat` reads it, so impossible dates and bare digits are refused. Its value is taken exactly from `diskgraph.resolve_temporal`, the parser ingest uses, when that parses it too: `2024-01-01T00:00:00.000000001Z` is `1704067200000000001`. A `date` or `datetime` is normalized by the same parser, keeping a pandas `Timestamp`'s nanoseconds. An `int` stays epoch seconds. The latest-anchor default converts the latest anchor time once, through the same function, so it and an explicit cutoff at the same time agree. The encoder cutoff floors to the index clock, as kumo-pytorch floors anchors (`convert_ticks(..., rounding="floor")`, from nanoseconds), so encoders count exactly the rows history can see. Before the epoch, flooring and truncating differ: −0.5 s is second −1, not 0. A row counts when its create time in index-clock ticks is at or before the cutoff's tick. On a coarse clock, rows in the anchor's own tick are excluded, because ingest rounds their create times up. A sub-second cutoff on a nanosecond index is exact. - **Rows the index doesn't store.** Ingest drops a row whose create time is NULL or doesn't parse, and stores a row with more than 64 MiB of node data without its values. Neither route counts these rows, at any cutoff or at `None`. - **`NON_TEMPORAL` tables** count every row at every cutoff. - **A list of cutoffs.** One sink per cutoff; each row reaches every cutoff that includes it. - **`fit_split`** no longer limits these encoders. See the behaviour change above. - **One pass per column.** A column requested with several types is observed once and feeds every collector. A decimal gives its categorical collector the exact text and its numerical collector the value. - **Statistics added later.** A column already in a file keeps every key it has and gains the new ones, the rule #318 uses within one pass. Adding numerical statistics to a categorical entry gives exactly the one-pass entry. In the other order, the shared keys (`semantic_type`, `num_unique`) come from the numerical pass; encoders don't read them, and `count` and `null_count` agree either way. - **Approximation.** - Buckets cuts come from a t-digest; the tests accept each cut within 1.5 ranks of the exact quantile. - The digest depends on how the index splits rows into shards, so a 3-shard and a 1-shard index give cuts up to a few ranks apart. Conformance compares Buckets cuts across engines within 3 ranks (`BUCKET_RANKS`), where a cut's rank is the number of values below it, matching how encoding assigns a value equal to a cut to the upper bucket. - `num_unique` is HyperLogLog. - Means agree with exact values to about 1e-13 relative; across shard counts they differ in the last bits. - **Run-to-run variation.** - Recompute is stable except for capped vocabularies: the same index wrote byte-identical files twice, unless a column passes the 1M-value cap, where which values concurrent workers admit first can differ (see below). - Ingest is not: encode workers pull batches from a shared stream, so t-digest quantiles and the last bits of the mean can differ between two ingests of the same data. Category counts below the cap do not. - **Recompute memory.** Decoded values in flight stay within the `ScanBudget`: each worker holds at most about one 128 MiB batch, plus at most one row past it. Filtering a batch per cutoff copies at most one more batch per worker, outside the budget. - **Capped vocabularies.** Past 1M distinct values, the counts cover the first 1M values DiskGraph admits as it scans, and those counts are exact. A value first seen after the cap is not in the vocabulary, and a warning names the column. With several encode or recompute workers, which values are admitted can differ between runs. - **uint64.** Both routes observe a `uint64` as unsigned. Values below 2^63 are observed as before. From 2^63 up, moments, quantiles and value bins see the value as an `f64`, and category counts key it by its exact decimal text. - **Values near the float limits.** Buckets cuts stay finite for columns near ±1.8e308. ## Back-compat | Case | Behaviour | | --- | --- | | Indexes built before this PR | Work; statistics are computed on first use into `col_stats/<dir>/<table>.col_stats.json` | | Fitted states and artifacts written before this PR | Load unchanged; a fit record without `statistics` is fine | | Artifacts written by this PR, read by older kumo-pytorch | Load; the extra `statistics` key is ignored | | `diskgraph.ingest` without `cutoff_col_stats` | The same index files | | Existing `col_stats.json` and `compute_col_stats_for_parquet` users | Unchanged, except for the gaps filled above: categorical timestamp and bytes columns now get counts, `decimal256` is observed, categorical decimals are keyed exactly, and `uint64` values of 2^63 and above are observed as unsigned (they were negative `i64` bits on ingest, and parse failures in `compute_col_stats_for_parquet`). The Arrow driver gains date and decimal arms, which only the recompute route reaches: `compute_col_stats_for_parquet` still never receives those types, because kumo's dtype map and `validate_stats_dtype` keep them out | | DiskGraph builds without these functions | DiskGraph's version goes to 0.2.0 and kumo-pytorch requires `diskgraph>=0.2.0`, so an older build is rejected at install instead of failing at fit time. kumo-core and kumo-engine keep `diskgraph>=0.1.0`; they don't call the new functions. | | Supplied encoder state (`Vocabulary(values=...)`, `ZScore(mean=..., scale=...)`, `Buckets(boundaries=...)`) | Unchanged; no statistics read | | Out-of-tree engines without `column_stats` | Keep the old fitting path | ## Production questions | Question | Answer | | --- | --- | | Cost (200M event rows, 64 cores; see the benchmark) | Ingest takes 34.3–37.3 s without the statistics and 37.9–41.3 s with them, on a loaded box. Recompute from the index takes 13.6–15.2 s. Reuse reads one file per table, and a later fit computes only the columns and statistics those files lack. | | Memory | Recompute holds at most about 128 MiB of decoded values per worker, within ingest's Encode budget across workers, so wide or dictionary-expanded strings no longer scale with the 65,536-row chunk: 70,000 rows of 40,000-character strings peaked at 0.28 GiB, down from 2.47 GiB. On the 200M-row benchmark, recompute peak RSS was 9.7 GiB, down from 10.0 GiB, mostly mapped index pages. Ingest peak RSS was 20.7–20.9 GiB with or without the statistics. The category counts are dropped at the end of Encode. | | Concurrency | Each writer writes a table to its own randomly named temporary directory, then, holding an exclusive lock on the cutoff directory's `.lock` file, merges into the table's file, syncs it and renames it into place. Readers take no lock and see the old or the new file, never a partial one. Two writers never drop each other's columns. | | Read-only index | Fitting writes `col_stats/` into the index directory, which must be writable. Scoring with `fitted=` writes nothing. | ## Testing Done On the final head e30b26d, with DiskGraph built from that tree, targeted tests (the full suite, conformance and the benchmark table below ran on 137c11a): - `pytest diskgraph-pybind/python/tests/test_cutoff_col_stats.py`: 9 passed on e30b26d. At a cutoff and at `None`: - ingest's counts, means, standard deviations and quantiles match a `Counter` and numpy over the rows at or before the cutoff, for strings, bytes, timestamps, dates, ints and decimals, with the create time an int64 millisecond column; - an int column and a decimal column are each requested as categorical and numerical in one pass, and get both; - a table without a create time counts every row; - a `uint64` column holding 0, 5, 2^63 and 2^64−1 gets exact counts, the numpy mean and standard deviation, and quantiles within its range, as categorical and numerical in one pass; - recompute equals ingest, including that `uint64` column, when one column's numerical statistics are added by a second request; - a row whose create time doesn't parse, a NULL create time and a row with 65 MiB of node data count on neither route, and ingest equals recompute; - refusals: repeated directories, and two kinds of category counts for one column; - on a milliseconds and a days clock, a row later in the cutoff's own tick is excluded, and a sub-second cutoff on a nanosecond index is exact; recompute counts these as ingest does; - `convert_ticks` floors −0.5 s to −1 and truncates it to 0, and both give 1 for 1.5 s; - a recompute over 70,000 rows of 40,000-character strings (about 2.8 GB decoded from a 1.1 MB index) counts correctly, in budgeted batches. - `cargo test -p diskgraph-ingest --test column_scan`, on e30b26d: 70,000 rows of three 1 KiB dictionary-encoded strings (68 MiB decoded, two chunks), scanned by two workers under a 1.5 MiB budget with 1 MiB batches. Every batch holds at most 1 MiB plus one row, every row is counted once, and the budget's high-water mark stays within 1.5 MiB. - `pytest --require-imports tests` (kumo-pytorch, full suite, as CI runs it), on 137c11a: 1907 passed, 3 skipped. On 9984c23, `test_column_stats.py`, `test_fitted_state_persistence.py`, `test_api_reference.py` and `conformance/test_field_semantics.py` gave 46 passed. They include: - `tests/test_column_stats.py`: encoders against numpy on both engines at three cutoffs; Buckets within 1.5 ranks; `Vocabulary` over every stored column type on both engines; shared encoders; warnings; one directory per cutoff with a file per table, one request for a column that two encoder kinds read, and a later fit that requests only the added column and leaves the file's other entries unchanged; a table named `../items/x y` on both engines, in `%2E%2E%2Fitems%2Fx%20y.col_stats.json`; Buckets over ±1.7e308 giving finite, sorted cuts; - `tests/test_field_outputs.py`: wide decimals and the other numeric outputs keep engine and delivery parity; - the updated expectations in `test_anchor_tables.py`, `test_fitted_state_persistence.py` and `conformance/test_field_semantics.py`, and `test_docs_code.py` with the serving page's printed scores. - `python -m conformance --engine all`, on 137c11a: 701 passed. On 9984c23, its `fitted_state` property: 5 passed. - `cargo test -p diskgraph-ingest --lib`, on 137c11a: 488 passed. On 9984c23, diskgraph-core lib: 134 passed. On e3559b1, diskgraph-rowpack: 318 passed; diskgraph-ingest lib: 488 passed; diskgraph-pybind lib: 121 passed; `test_column_stats.py`: 13 passed. `cargo clippy --workspace --all-targets -D warnings`, `ruff check`, `ruff format --check` and vulture are clean. - `pytest -m notebook tests/test_notebooks.py`: 3 passed on 4075e78; the committed `output_schema.json` files reproduce. The commits since change no fitted state. - **Benchmark, on the final code.** 200M event rows plus 4M users, 64 cores, 8 shards; the cutoff keeps 150,003,117 events. Requested: `events.amount` numerical, and `events.channel`, `events.quantity` and `users.country` categorical. Each step ran in a fresh process on a shared box. | Step | Runs | Wall | Peak RSS | | --- | --- | --- | --- | | Ingest, no statistics | 3 | 34.3–37.3 s | 20.8–20.9 GiB | | Ingest with the statistics (`encoder_cutoffs`) | 3 | 37.9–41.3 s | 20.7–20.9 GiB | | Recompute from the index (`cutoff_col_stats`) | 3 | 13.6–15.2 s | 11.5–11.8 GiB | Load average 25–34, with another test run on the box. Bounded decode (e30b26d) against the commit before it (4d23550), recompute only, alternating fresh processes, load average 1–38 and rising: | Recompute | Runs each | Before: wall, peak RSS | After: wall, peak RSS | Cores | | --- | --- | --- | --- | --- | | 200M-row benchmark | 6 | 9.1–14.6 s, 10.0 GiB | 8.9–13.9 s, 9.7 GiB | 49–53 both | | 32M-row wide table, 4 columns | 3 | 3.22–3.25 s, 4.5 GiB | 3.25–3.28 s, 4.46 GiB | 30–32 before, 31–33 after | | 70,000 rows of 40,000-character strings (two chunks) | 3 | 2.19–2.20 s, 2.47 GiB | 2.16 s, 0.28 GiB | 1.1 both | The 200M walls are bimodal (about 9 s or 14 s) on both builds as the load changed. Statistics are byte-identical between the builds, except the wide table's capped `d0` vocabulary, which also differs between two runs of the old build. - **Wide table, on the final code.** 32M rows of 26 columns (8 strings, 6 decimals, 12 numbers and times), 4 requested at one cutoff (a float and a decimal as numerical, a string and a decimal as categorical): ingest takes 11.7–13.2 s without the statistics and 13.7–14.4 s with them (3 runs), with identical statistics on every run. - **GPU end to end:** not rerun on this code; the tiers need a rerun. ## Where to look 1. `packages/diskgraph/diskgraph-ingest/src/cutoff_col_stats.rs`: the request, stat sets per column, the per-cutoff sinks, and `add_to_file`. 2. `packages/diskgraph/diskgraph-ingest/src/lib.rs`: the `start_row` and `finish_row` calls in `write_node_row_from_access`, the cutoff branch of the encode closure, and the publish after `write_col_stats`. 3. `packages/diskgraph/diskgraph-pybind/src/cutoff_col_stats.rs` and `packages/diskgraph/diskgraph-ingest/src/column_scan.rs`: recompute from the index. 4. The pipeline additions: `diskgraph-ingest/src/col_stats.rs` (`observe_timestamp_at`, `observe_bytes_at`, `observe_decimal_at`, `observe_u64_at`, `with_quantiles`, `collects`, `counts_categories`), `diskgraph-rowpack/src/lib.rs` (`ColumnValueObserver`, `encode_row_observed`) and `diskgraph-pybind/src/bp_col_stats.rs` (`drive_from_arrow_column`). 5. `packages/experimental/kumo-pytorch/src/kumo/pytorch/column_stats.py`: qualification, `stats_request`, `read_column_stats` and `fit_from_stats`. 6. `preparation.py` (`_pinned_from_stats`), `engines/diskgraph.py`, `engines/in_memory/source.py`, `materialization.py` and `assembly.py`: the flow. 7. The tests, `conformance/properties.py` (`BUCKET_RANKS`), then the docs and regenerated outputs. ## Change map [File-by-file change map](#306 (comment)). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
…#307) Based on main. #299 (`kumo.settings`), #318 (`StatSet`) and #306 (column statistics with an encoder cutoff) are merged; #324 (fit without samples) is stacked on this PR. ## Summary A learned `Text` encoder over a **stored string column** now trains its byte-level BPE tokenizer on that column's table rows created at or before the encoder cutoff, like #306's table-column encoders. DiskGraph trains it. `diskgraph.train_tokenizer` decodes the column through #306's chunk decoder (`column_scan::scan_chunk`, byte-budgeted) and cutoff filter, so it covers exactly the rows #306's statistics count. Each worker pre-tokenizes the values it decoded into its own word counts; the counts are summed, and the `tokenizers` crate's BPE trainer runs once on them. The crate is pinned to the version and regex engine (Oniguruma) the `tokenizers` Python wheel is built from, so the tokenizer JSON is byte-for-byte what `train_from_iterator` produces on the same values. Python receives only that JSON. The tokenizer is kept in the cutoff's `<index>/col_stats/<dir>/` beside #306's statistics, and later tasks reuse it. A fit on the DiskGraph engine with `Batching.length_input` set also records each event table's token cost per event, for the tables that input reads: a constant for columns without `Text`, plus a raw `u16` per-node file of `Text` pieces when the input reads `Text`. A batch planner reads them before sampling (see "Per-row token lengths"). The PR also makes two batch-time changes, described under "Speedups" below: - text encoding writes into preallocated arrays; - the length summary measures records in chunks. > **Behaviour change.** A learned `Text` over a stored column learns from that table's rows created at or before the encoder cutoff, whatever `fit_split` selects, instead of from the training examples. `Text` over per-anchor values (aggregates, calculations) still fits on the examples, fed in batches. Supplied tokenizer state (`Text(state=...)`) is unchanged, except that its padding no longer applies (see Back-compat). As in #306, fitting still builds samples; the follow-up PR stacked on this one removes that. ## What changes for users | Where | API | What it does | | --- | --- | --- | | kumo-pytorch | none new | #306's `encoder_cutoff` now also applies to a learned `Text` over a stored string column. `DiskGraphEngine(encoder_cutoffs=...)` does not: ingest computes only statistics, and a tokenizer trains on the first fit at its cutoff. | | kumo-pytorch | `FitRecord["statistics"]["col_stats"]` | Also lists the tokenizer file of each tokenizer read or trained. | | DiskGraph Python | `diskgraph.train_tokenizer(index_dir, columns, cutoff, *, vocab_size, min_frequency, special_tokens, unk_token, num_threads=None) -> str` | The JSON of a byte-level BPE tokenizer trained on the non-null values of `columns` (`(table, column)` pairs) over the rows counted at `cutoff` (index-clock ticks; `None` counts every row), as `tokenizers`' `train_from_iterator` trains it on those values | | DiskGraph Python | `diskgraph.TOKENIZER_TRAINER` | The `tokenizers` crate and regex engine the trainer is built on (`"tokenizers 0.23.2 onig"`), part of the tokenizer cache key | | DiskGraph Python | `diskgraph.token_lengths(index_dir, table, columns, path, *, num_threads=None)` | Writes `path`: one little-endian `u16` per node of `table`, its count over `columns` (a string column's pieces under its tokenizer JSON, and a variable-length list's elements), NULL counting 0, saturated at 65,535. A column with a fixed cost is refused (see "Per-row token lengths") | | kumo-pytorch | `column_stats.read_token_lengths(index, entry)` | A table's `(constant, per_node)`: the per-event constant, and a read-only memory map of the lengths file with one `uint16` per node ID, or `None` without a file | | kumo-pytorch | `FitRecord["statistics"]["token_lengths"]` | With `Batching.length_input` set, `{"constant": n, "file": name or None}` for each event table that input reads; `file` is relative to `col_stats/` | | DiskGraph Rust | `column_scan::{stored_tables, StoredTable}`; `node_chunks(table, size)` | The stored-table lookup the trainer shares with #306's recompute; `node_chunks` takes a chunk size and is lazy | `train_tokenizer` details: - It decodes chunks of 1,024 nodes on `num_threads` threads with the GIL released, and checks for Ctrl-C between windows of 1,024 chunks. The final training step is not interruptible, as with `train_from_iterator`. - It refuses an unknown table or column, and a non-string column (`… holds Int64 values, not strings`), with `DiskgraphConfigError`, and `num_threads=0`. ## How it works 1. **Which encoders.** `column_stats.py: _learns_from_stats` lets a learned `Text` over a string column qualify. `TableColumnEncoder.requests` is empty for it, because it needs no col-stats. 2. **The trainer** (`diskgraph-pybind/src/cutoff_col_stats.rs: train_tokenizer, word_counts`). - `stored_tables` opens the tables and finds each create-time column; each column must hold strings. - Chunks of 1,024 nodes (`node_chunks`; #306's recompute keeps 65,536) are decoded in parallel with #306's byte-budgeted `scan_chunk`, which may hand a chunk over as several batches, and filtered with `create_times` and `at_cutoff`. Between windows of 1,024 chunks the GIL is taken back for `py.check_signals()`. - The worker that decoded a chunk pre-tokenizes each non-null value with the crate's `ByteLevel(add_prefix_space=false)` and counts the words in its own map, one per pool thread. The maps are summed in thread order. - `BpeTrainer::do_train` runs once on the summed counts, in the same pool, with `train_text`'s settings: vocabulary size, minimum frequency, special tokens, no progress bar, `BPE(unk_token)`. This is what `train_from_iterator` does after its own word count, so the JSON is identical. `min_frequency` stays where the trainer applies it, as the stop condition of the merge loop. - `tokenizers = "=0.23.2"`, default features off, only `onig`: the crate and regex engine the 0.23.3 wheel is built from. `onig_sys` compiles the Oniguruma C source it bundles. 3. **Per-anchor text** (`encoding.py: train_text`). Unchanged: per-anchor `Text` trains with Python `tokenizers` on batches of 1,024 strings (`TRAIN_BATCH`, `_text_batches`). `TEXT_SPECIAL_TOKENS` and `TEXT_UNKNOWN` are shared with the DiskGraph call. 4. **The cache** (`engines/diskgraph.py: DiskGraphSource.column_text`; `column_stats.py: TableColumnEncoder.tokenizer_file`). - Path: `<index>/col_stats/<dir>/<table>.<column>.text-<settings>.tokenizer.json`. `<dir>` is #306's cutoff directory (from the cutoff ticks, clock unit and `COL_STATS_RECIPE`); `<table>.<column>` is the encoder's first column; `<settings>` is the first 16 hex characters of the sha256 of `[vocabulary_size, min_frequency, columns, TEXT_RECIPE, diskgraph.TOKENIZER_TRAINER]`. A changed setting, recipe (`TEXT_RECIPE = 1`), trainer crate or regex engine never reuses a stale tokenizer. The table and column are percent-encoded in the file name (#306's `file_name_part`), and the cutoff reaches the index clock with `convert_ticks(..., rounding="floor")`, from nanoseconds, as #306's statistics cutoff does. - The file holds `{"columns", "cutoff", "tokenizer", "sha256"}`. It is reused when it exists and the sha256 of its tokenizer matches. A file that doesn't parse, or whose digest doesn't match, is refused with `… is not a valid tokenizer file; delete it to retrain`. - It is written to an exclusively created, uniquely named file in the same directory, with the umask's permissions, synced, then renamed over the target. 5. **In memory** (`engines/in_memory/source.py: column_text`). Trains on its own rows, normalized with the encoder's dtype, with the same filter (create time at or before the cutoff; every row of a table without one) using `train_text`. It gives the same tokenizer and caches nothing. `<index>/col_stats/` after a materialize with a `Text` encoder on `card_transactions.description`: ``` index/col_stats/ └── <dir>/ one per encoder cutoff (#306) ├── card_transactions.col_stats.json #306's statistics └── card_transactions.description.text-<settings>.tokenizer.json {"columns": [["card_transactions", "description"]], "cutoff": {"value": 1733011200, "unit": "seconds"}, "tokenizer": "{\"version\":\"1.0\",…}", "sha256": "…"} ``` ## Per-row token lengths A fit on the DiskGraph engine with `Batching.length_input` set also records, for each event table that input reads, the token cost of its stored rows, for a planner that sizes batches before sampling. The cost has two parts: a per-event constant for the columns whose cost does not depend on the value, and a per-node count for the `Text` columns. The counts describe the source data only. The per-input rules stay with the consumer: `Tokens.max_tokens`, `missing`, Text's `empty="unknown"`, Flatten markers and budget, `max_events`, aggregates and constants. - **What a row counts.** The stored columns of the table that the `Batching.length_input` input reads, each column once: - a column whose cost does not depend on its value: 1, NULL included, added to the constant. kumo-pytorch's stored columns are scalars, so every non-`Text` column is one; - a `Text` column: its pieces under the fitted tokenizer, with padding off and no special tokens, as `FittedEncoder.encode_arrow` encodes it, in the per-node file. A NULL text counts 0; - a variable-length list: its element count, in the per-node file, with a NULL list counting 0. Lists can't be declared yet (DG-NESTED-COLUMN), so only `Text` reaches the file today. A row's cost is the constant plus its per-node count. - A column the input reads through a Text encoder and another encoder is a Text column, and counts its pieces once. - Two Text encoders with different tokenizers on one column of the input are refused as ambiguous. - Columns only other inputs read are not counted, so adding or changing another input leaves the record unchanged. - Graph-input node fields are not counted; only event rows are. - Under `Tokens(missing="emit")` the constant equals each emitted event's tokens, NULLs included. Under `missing="omit"`, the default, a NULL value emits no token, so the constant overstates that event by its NULLs. - **What the record holds.** `FitRecord["statistics"]["token_lengths"]` maps each event table to `{"constant": n, "file": name}`. - `n` is the per-event constant. - `file` is the per-node file relative to `col_stats/`, or `None` when the input reads no `Text` column of the table. - `FitRecord["statistics"]` also records `"cutoff"`. - `read_token_lengths(index, entry)` returns `(constant, per_node)`. `per_node` is a read-only memory-mapped `uint16` array indexed by node ID, or `None` without a file. - **Where.** `<index>/col_stats/<dir>/<table>.lengths-<hash>.bin`, written only for a table with `Text` columns. - `<dir>` is the fit's cutoff directory (#306), and `<table>` passes through `file_name_part`. - `<hash>` is the first 16 hex characters of the sha256 of the `Text` columns, each one's tokenizer sha256, and `diskgraph.TOKENIZER_TRAINER`. - An existing file is reused. - The constant has no file: each fit derives it from the fitted plan. - **Layout.** Raw little-endian `u16`, with no header: node ID `n` is at byte offset `2 * n`. - Node IDs run from 0, contiguous across shards, so no base or count is recorded. - A node stored without data (a row over the 64 MiB node-data limit), or with empty data, gets 0 in the file. The constant still applies to it. - Rows ingest dropped (NULL create time, duplicate keys) are not nodes and have no slot. ``` index/col_stats/<dir>/ ├── card_transactions.col_stats.json ├── card_transactions.description.text-<settings>.tokenizer.json └── card_transactions.lengths-<hash>.bin u16 LE per node ID: 03 00 05 00 00 00 … → 3, 5, 0, … ``` Take `length_input="transactions"` reading `amount` (Buckets), `channel` (Vocabulary) and `description` (Text) from `card_transactions`. The record is `{"constant": 2, "file": "<dir>/card_transactions.lengths-<hash>.bin"}`, and the file holds each node's description pieces. Without `description`, the record is `{"constant": 2, "file": None}` and no file is written. - **Cap.** A per-node count above 65,535 saturates at 65,535; it is not an error. - **When.** On a fit of the inputs with the DiskGraph engine whose `Batching.length_input` is set, after the encoders are fitted. - `max_tokens` and `bucket_by_length` already require `length_input`, so every budgeted or bucketed fit gets the record. - The constant needs no scan. DiskGraph decodes a table only when the input reads a `Text` column of it, so a fixed-width-only recipe runs no pass and writes no file. - Without `length_input` nothing runs, and `FitRecord["statistics"]` has no `"token_lengths"`. - Reusing fitted state (`fitted=`) writes nothing, and the in-memory engine records none, since it has no index. - **How.** `diskgraph.token_lengths` is called with the per-node columns only. It refuses any other column with `DiskgraphConfigError` (`… has a fixed token cost; pass only list columns and string columns with a tokenizer`). - It decodes 1,024-node chunks with #306's byte-budgeted `scan_chunk`, which passes each row's node with every batch. - It counts in parallel with the GIL released, checks for Ctrl-C between windows of 1,024 chunks, and writes each window's block with the GIL released. - The output goes through a hidden, uniquely named temporary file, which is synced and then renamed. - **Cost.** Measured before the constant split, with the scalar counted per node. - 100M rows of about 6 words, Text plus one scalar, 64 threads: 42.0–42.6 s (2.35–2.38M rows/s), a 200 MB file and 1.9 GiB of process growth. - 10.9M rows: 23.7 / 11.9 / 5.7 / 4.3 s at 8 / 16 / 32 / 64 threads. - Extrapolated: about 7 min per 1B rows. - A table read without `Text` now costs no pass and no file. ## Speedups These two changes were not measured on their own, and the end-to-end tiers use no `Text`. - **Batch text encoding** (`FittedEncoder.encode_arrow`). The text branch tokenizes 65,536 strings at a time (`TEXT_BATCH`) with `encode_batch_fast`, and writes piece IDs and offsets straight into int64 arrays: offsets are preallocated, and the ID array grows geometrically. It no longer builds a Python list per string. Missing, empty and unknown values are handled as before: a NULL becomes the missing ID, and an empty string becomes no pieces, or the unknown ID with `empty="unknown"`. The output is identical (tested against one-string-at-a-time encoding). - **Length summary** (`PreparedBatchPlan`, `_LENGTH_CHUNK = 4096`). Records are measured 4,096 at a time, keeping one length per sample, so peak memory no longer holds every record's encoded text at once. This bounds memory; it is not meant as a speedup. A DiskGraph `ModelSourceBatch` is still measured whole. ## Back-compat | Case | Behaviour | | --- | --- | | `Text(state=...)` | Unchanged, except padding: encoding turns the tokenizer's padding off, because the output is ragged IDs with offsets. A padded state used to emit pad IDs that depended on which strings shared an encode call; it now gives the unpadded IDs. | | Learned `Text` over a per-anchor value | Fits on the examples, fed in batches | | Learned `Text` over a stored string column | Learns from table rows up to the cutoff (the behaviour change) | | Encoded batches | The same piece IDs and offsets as before for unpadded tokenizers, NULL, empty and `empty="unknown"` included | | Artifacts and fitted states | Unchanged format | | Indexes from before this PR | Work; tokenizers are trained on first use | | DiskGraph builds without `train_tokenizer` | Builds older than 0.2.0 are rejected at install by #306's `diskgraph>=0.2.0` floor. This PR adds `train_tokenizer` to the same, still unreleased, 0.2.0; kumo-pytorch's CI builds DiskGraph from the same commit. | | Engines without `column_text` | Keep the old fitting path | ## Production questions | Question | Answer | | --- | --- | | Memory while training | Word counts take about 200 B per distinct word (one entry per worker that saw the word, then the summed map); the crate's trainer then takes about 0.8 KB per distinct word, as in `train_from_iterator`. 10.9M rows (5,000 distinct): 0.26 GiB growth (was 0.29 GiB streamed, 3.31–3.33 GiB from one list). 100M rows (7.8M distinct): counts 0.97 GB per-thread plus 0.48 GB summed, 6.9 GiB peak. 1B rows (45.8M distinct): 7.7 GB plus 1.9 GB, 36 GiB peak in the trainer. | | Speed | 10.9M rows, 64 threads: 3.55–4.26 s (was 20.7–21.1 s streamed, 18.7–19.8 s from a list), same tokenizer. 100M rows: 118–148 s, about 119 s in two of three runs (counting 31 s, summing 4 s, crate training 82 s), against 294 s for `train_from_iterator` fed from Parquet with the same tokenizer. 1B rows: 969 s (counting 381 s at 2.6M rows/s, summing 35 s, training 552 s). At 2.6–3.2M rows/s, 25B rows would take about 2.2–2.7 h to count, an extrapolation; training time and memory follow the number of distinct words. Reuse reads one file. | | Determinism | DiskGraph threads {1, 4} × shards {1, 3} and both engines train the same tokenizer (tested), byte-identical to `train_from_iterator` (tested; by hand at 10.9M and 100M rows) | | Concurrency | Each writer writes its own temporary file; two writers write the same bytes, and the rename is atomic. The file gets normal umask permissions, so other accounts sharing the index can read it. | | Read-only index | As in #306, fitting writes `col_stats/`. Scoring with `fitted=` reads nothing. | | Native dependencies | Oniguruma, a C library: `onig_sys` compiles the Oniguruma source it bundles, which is BSD-2-Clause. Its `COPYING` ships in `THIRD-PARTY.txt`, and an `expression_overrides` entry in `3rdparty/notices/policy.json` labels `onig_sys` `MIT AND BSD-2-Clause` instead of the `MIT` its Cargo metadata declares. 29 new crates are in `THIRD-PARTY.txt`. Wheels were built and tested only on x86_64 Linux: a zig manylinux build gave a `cp311-abi3-manylinux_2_17_x86_64` wheel with a GLIBC 2.17 floor; aarch64, Windows and macOS were not built. | ## Semantics to check - The trainer counts exactly #306's rows: `create_time <= cutoff`, NULL create times never stored, every row of a non-temporal table. As in #306, rows the index doesn't store (an unparseable create time, more than 64 MiB of node data) count nowhere. - The tokenizer depends only on the word counts, not on row order or thread count. - `min_frequency` is the trainer's merge-loop stop condition, as in `train_from_iterator`; rare words are not dropped before training. ## Testing Done On 3ffaaa0 (main merged, the same tree as ecfcd73), with DiskGraph built from that tree, targeted tests and the license checks; the full suite and conformance last ran on 252c0db (full results below), and CI runs them on this head: - `pytest diskgraph-pybind/python/tests/test_train_tokenizer.py diskgraph-pybind/python/tests/test_token_lengths.py diskgraph-pybind/python/tests/test_cutoff_col_stats.py`: 13 passed. The trainer part covers: - at a cutoff the tokenizer learns the row at the cutoff and not the next second's; - the same JSON for train threads {1, 4} × index threads {1, 4} × shards {1, 3}; - a table without a create time counts every row, and a row with a NULL create time is never counted; - refusals raise `DiskgraphConfigError`. - `test_token_lengths.py`: each node of a 3-shard table equals its body's words under a whitespace tokenizer plus its list's elements, with a NULL text or list counting 0, at threads {1, 4}; a node stored without data gets 0; a 70,000-element list saturates at 65,535; no temporary file is left. An unknown column, a scalar and a fixed-length array (fixed token cost), a tokenizer on a non-string column, and `num_threads=0` raise `DiskgraphConfigError`. - `tests/test_text_from_index.py`, `test_column_stats.py` and `test_fitted_state_persistence.py` on bc967fc, with `test_api_reference.py`: 51 passed, the first including the mixed-script column trained at 1 and 4 threads, byte-identical to `train_text`, and the token-length tests: with `length_input` set, for a learned and for a padded supplied tokenizer, the constant is 2 (amount, channel) and each `card_transactions` node's file value is `len(encoder.tokenizer.encode(description).ids)`, so constant plus file equals the earlier per-row total, and a second fit reuses the file untouched; a fixed-width-only budgeted recipe (Buckets + Vocabulary, `Tokens(missing="emit")`, NULL channels) records `(2, None)` with `diskgraph.token_lengths` patched to raise, writes no file, and every emitted event has 2 tokens; a fit without `length_input` records nothing; a second input reading `merchant_id` leaves the record and file unchanged; a column a second encoder in the same input also reads counts once, and two different tokenizers on one column are refused. `pytest --require-imports tests` (kumo-pytorch, full suite), run once on the tree just before 252c0db: 1911 passed, 3 skipped, 1 failed. The failure was the thread-count test still deleting a `text-<hash>/` directory. 252c0db changes only that test, and `tests/test_text_from_index.py` then passes 5 of 5. It covers: - on both engines, the tokenizer equals one trained on the column filtered to the cutoff; - a second materialize reuses the kept file in the cutoff directory untouched, and the file has the umask's permissions; - both engines and DiskGraph threads {1, 4} train the same tokenizer; - a 2,000-row column of mixed scripts, emoji, combining marks, tabs, newlines, runs of spaces and NULLs, trained from the index with 1 and 4 threads, equals `train_text`'s JSON exactly; - chunked encoding equals one-string-at-a-time encoding across chunk boundaries, also for a padding-enabled supplied state. - `python -m conformance --engine all`, on 252c0db: 701 passed. - License checks, as the `license_notice` and `licensing` jobs run them: `check_cargo_license_metadata.py`, `generate_artifact_manifest.py --check`, all five `gen_third_party.py --check` lines, the notice generator unit tests (including the `expression_overrides` test), `check_license_headers.py` and `check_python_license_metadata.py` all pass. `cargo deny` was not run here. - `cargo clippy --workspace --all-targets -D warnings` and rustfmt are clean, and flake8 and isort are clean on the notice scripts. `ruff check`, `ruff format --check` and vulture were clean on the kumo-pytorch tree, which the change to Oniguruma doesn't touch. - **Equality, by hand:** 3,000 Unicode rows × cutoffs {None, T0} × (vocabulary, min_frequency) {(300, 0), (2000, 2)} × threads {1, 4, 16} × shards {1, 3}: 24/24 byte-identical to `tokenizers` 0.23.3, also with the zig-built manylinux wheel on Python 3.11. The 10.9M-row benchmark gives `22c54696…`, and 100M rows gave `67ad5bf5…` from both routes. - **Benchmark** (fresh process per run, 64 threads, `Text(vocabulary_size=8000)`, shared box at load 12–80; measured on an earlier head of this PR with the same trainer, before #306's byte-budgeted scan): | Rows (distinct words) | Route | Wall | Peak RSS growth | Tokenizer | | --- | --- | --- | --- | --- | | 10.9M (5,000) | DiskGraph trainer | 3.55 / 4.26 / 3.57 s | 0.26 GiB | `22c54696…` | | 10.9M | Before: streamed to Python | 20.7 / 21.1 s | 0.29 GiB | `22c54696…` | | 10.9M | One Python list | 19.8 s | 3.33 GiB | `22c54696…` | | 100M (7.8M) | DiskGraph trainer | 148 / 118 / 119 s | 6.8–6.9 GiB | `67ad5bf5…` | | 100M | Python `train_from_iterator` fed from Parquet | 294 s | 7.1 GiB max RSS | `67ad5bf5…` (identical) | | 1B (45.8M) | DiskGraph trainer, 1 run | 969 s | 36.3 GiB | `ebe76f99…` | - **Ctrl-C, by hand:** SIGINT 3.0 s into a 100M-row training raised `KeyboardInterrupt` at 3.21 s. - **GPU end to end:** not rerun on this code; the tiers need a rerun. ## Where to look 1. `packages/diskgraph/diskgraph-pybind/src/cutoff_col_stats.rs`: `word_counts`, `train_tokenizer`, and `from_index` using `stored_tables`. 2. `packages/diskgraph/diskgraph-ingest/src/column_scan.rs`: `stored_tables`, `node_chunks`. 3. `packages/experimental/kumo-pytorch/src/kumo/pytorch/engines/diskgraph.py: DiskGraphSource.column_text`, and `column_stats.py: TableColumnEncoder.tokenizer_file`: the cache. 4. `preparation.py: Plan._pinned_from_stats`: Text encoders pinned from the tokenizer. 5. `encoding.py`: `train_text`, `_text_batches`, `FittedEncoder.encode_arrow`; and `assembly.py`: the length summary. 6. `engines/in_memory/source.py: column_text`, the tests, then `Cargo.toml`/`Cargo.lock`, the regenerated notices, and `scripts/gen_third_party.py: validate` with the `expression_overrides` entry in `3rdparty/notices/policy.json`. ## Change map [File-by-file change map](#307 (comment)). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
Stack 5/5. Based on main; #299, #318, #306 and #307 are merged. ## Summary `Plan.materialize` used to fetch every fitting anchor as a `SampleRequest` and build every fitting sample at once, then fit encoders from that list. After #306 and #307 most encoders no longer need those samples: they are pinned from DiskGraph column statistics or a tokenizer trained from the index. This PR stops building the samples for them: - Fitting anchors are read 4,096 at a time. - The default `encoder_cutoff` (the latest fitting anchor time) is the max anchor time over those chunks, converted once at full precision by #306's `cutoff_nanos`, so it selects the same rows as the same cutoff given explicitly. - Encodings whose state comes from column statistics, a tokenizer or the contract (`Raw()`, `Vocabulary(values=...)`, `ZScore(mean=, scale=)`, `Buckets(boundaries=)`, `Text(state=)`) build nothing. - Learned encodings over supplied labels (`ExternalTarget`) read the labels from the anchors; nothing is built. - What still needs a sample builds it 4,096 anchors at a time, keeping only each encoder's observed values. That is learned encodings over aggregates, calculations and computed targets, plus the cases listed under "Known remaining cases". Inputs build without their targets. Computed targets build alone (no entity values, events or neighbourhoods) unless they read input rows. - The fit-time length summary (`manifest["lengths"]`) is deleted. Computing it meant building every fitting sample, and nothing reads it: batching measures its own lengths when it iterates. Fitted state is bit-identical to #307's (head `252c0dbd`) for the same inputs. This was checked over the whole test suite and on 13,000-anchor multi-chunk cases; see "Testing Done". On a DiskGraph contract whose encoders are all pinned or declared, with 100k Parquet anchors, materialize takes 1.0 s and grows peak RSS by 20 MiB. Before this PR it took 30.1–30.3 s and 933–963 MiB. ## Behaviour changes > **Checks that ran only because fitting built samples now run when a batch builds the anchor.** When nothing is built at fit time, the following are refused by the batch (or `preview`) that builds the anchor, not by `materialize`: > - an entity created after its anchor time (`entity did not exist before …`); > - an unknown candidate set, or duplicate candidate IDs; > - duplicate sample IDs (in-memory engine); > - a single sample over `Batching.max_tokens` (`one sample exceeds Batching.max_tokens`), which the length summary used to catch. > > As before, anchors outside `fit_split` were never checked at fit time. > **Dropped at fit time.** > - An `AlignedEventTarget` derived label (`ThresholdEventLabel`) with a supplied `threshold` and a declared encoding no longer checks at fit that its field's values are finite. With a fitted threshold or a learned encoding, the check still runs. > - Declared encodings no longer normalise every fitting value, which was a validation-only pass. > **Length summary removed.** > - `Task.manifest` and `PreparedBatchPlan.manifest` no longer have `"lengths"`, and `fitted-state.json` no longer holds it. > - `manifest["artifact_fingerprint"]` covered that key (`None` without a `length_input`), so its value, and every batch's `metadata["artifact_fingerprint"]`, changes for every task. > - The fitted-state fingerprint and `Task.fingerprints` are unchanged. ## Public API touched | API | Change | Errors | | --- | --- | --- | | `Plan.materialize` | Same signature. Builds samples only as described above, and reads anchors in chunks. | The refusals listed under "Behaviour changes" moved to batch time. All others are unchanged. | | `PreparedBatchPlan(...)` | The `fitting_values=` and `length_summary=` keyword parameters are removed. They only fed the summary. | None | | `PreparedBatchPlan.manifest`, `Task.manifest` | No `"lengths"`; new `artifact_fingerprint` value | None | | `prepare_batch_spec` | Same signature; no summary | `one sample exceeds Batching.max_tokens` is raised by `batches()`, not by `prepare_batch_spec` | | `FittedState` | The `_lengths` field is removed (it appears in the documented constructor) | None | | `Artifact.save` / `Artifact.load` | No `"lengths"` is written. `load` accepts an older artifact that has one, and ignores it. | `load` no longer raises `has no length summary`, `has a malformed length summary` or `the length summary … is not the one manifest.json records`. All other refusals are unchanged. | | `SampleSource.fit_graph_fields` (engine seam) | Called once with every fitting root, as before. The roots are now made from the anchors, not from built samples. | None | `fit_plan` (internal) now fits only with a contract; `Plan.materialize` and serving always pass one. ## How it works 1. **Anchors** (`preparation.py: Plan.materialize`, `assembly.py: _Mapped`, `_chunks`). `fitting = _Mapped(partial(task_anchors.fetch, chosen), range(count))`: slicing it fetches those positions. `_chunks(values)` yields `values[i:i + 4096]`. `Plan._pinned_from_stats` takes the latest anchor time as a max over `_chunks(fitting)`. 2. **What learns** (`encoding.py: learns_from_values`, moved from `column_stats._learns_from_stats` unchanged). An encoding learns from values when it is `Vocabulary(values=None)`, `ZScore(mean=None)` with a numeric dtype, `Buckets(bins=…)` with a numeric dtype, or `Text(state=None)` with a string dtype. Every other encoding takes its state from the contract. 3. **Inputs** (`assembly.py: _fit_inputs`). - First, without values, it computes each encoder's config and dtype from the declarations, as before. - It records a slot `(input, field)`, or `(input, table, field)` for a graph, for each encoder that learns and is not pinned. Slots are kept in the old iteration order, so shared encoders concatenate their observations exactly as the single build did. - Unpinned graph slots: `source.fit_graph_fields` is called once, with `GraphRoot(sample_id, entity_id, cutoff_to_epoch(as_of_time))` for every fitting anchor. - Field slots, and `Composite(vocabulary=None)` rows, take `_chunks(values_for(sample_without_targets(sample)))`. Per chunk, the rows' learned columns are appended to their slot, and composite rows are counted as raw-value tuples. - After the chunks, `fit_encoder` runs on the concatenated slot lists. Composite tuple counts are mapped through `_component_key` and summed, which gives the same counts and the same ordering as counting per row. 4. **Targets** (`assembly.py: _fit_targets`). - Slots go to target encoders that learn and are not shared with an input. - Observations are also kept for derived labels with a fitted threshold, and for matching groups. - What it builds: - the full sample, if a learned target reads input rows (`AlignedEventTarget`, `MatchingGroupTarget`, `CandidateTarget`); - otherwise, if a learned target is computed (`Aggregate`, `Compare`, `RowTarget`), a targets-only sample (`entity_values`, `dated_entity_values`, `events`, `current_events` and `neighborhoods` emptied); - otherwise the anchors themselves, with `_normalize_supplied_targets` applied as the engines apply it. `_targets` reads a `SampleRequest`'s targets. - Thresholds, labels and group numbering are computed after the chunks, as before. 5. **Builds** (`assembly.py: fit_plan.values_for`). `values_for(spec)` is a `_Mapped` over the fitting requests. Each slice's supplied labels are first normalised against the full sample with `_normalize_supplied_targets`. A value supplied for a generated target is therefore refused as `… was both supplied and generated`, as a full build refuses it, even when the build itself uses a sample without targets. The slice is then built with `source.build_model` (or `build`) under `spec`. `values_for(None)` returns the normalised requests and builds nothing. `prepare_batch_spec` passes its already-built values as the single source. 6. **Length summary** (`assembly.py: PreparedBatchPlan`; `artifact.py`; `task.py`; `serving.py`; `preparation.py`). Removed. `Artifact.load` pops `"lengths"` from an older `fitted-state.json`. If an older `manifest.json` has `"lengths"`, `load` first checks the manifest against the rebuilt one with that summary added and its fingerprint recomputed the old way. It then drops the summary and takes the rebuilt `artifact_fingerprint`. Every manifest field, the old fingerprint included, is verified. ## Known remaining cases These still build samples, chunk by chunk, keeping only observed values. Before this PR they were fitted from the full sample list. | Case | What it needs | Why | | --- | --- | --- | | Learned encodings over aggregates, `Compare`, `Derived` entity values | Each chunk's input sample (without targets) | The values are computed per anchor from history | | Learned encodings over computed targets | Each chunk's targets-only sample | The labels are computed from future rows | | Learned encodings over event fields that aren't plain stored columns (`Derived`, `EventTimeDelta`, `Constant`, a `Field` with `path`), including `current_events` | History rows | Values exist only per event in a sample | | Learned encodings over entity `Field`s with `path`, and over dated entity values (`OccurrencesOf`) | Related-row lookup, or dated facts | Not a stored column of the entity table | | `Composite(vocabulary=None)` rows | History rows | Tuple counts are over each event's encoded components, even when every component is pinned | | Learned encodings on `CandidateSource` inputs, and learned `CandidateTarget`s | The candidates' rows (full sample) | Values are per requested candidate | | `AlignedEventTarget` with a learned field or a fitted threshold | The input's event rows (full sample) | Labels are aligned with the retained events | | `MatchingGroupTarget` | The entity input's rows (full sample) | Groups are the typed values those rows hold | | A `UseEncoding` shared between a stored column and a per-anchor value | Rows for both | It is not pinned, so it learns from built rows | | Unpinned graph node fields: shared as in the row above, or on an engine without `column_stats` | One `fit_graph_fields` call over every fitting root, as before | Node values come from neighbourhood sampling | ## Semantics a reviewer should check - **Observation order.** Each slot list is filled chunk by chunk in request order, and slots concatenate in the old loop order: sorted inputs, then tables and fields; targets' fields before their derived labels. ZScore (numpy summation) and Text depend on order. Vocabulary, Buckets and composite counting don't. - **Graph roots from the anchors.** Both engines' built samples have `sample_id = request.sample_id`, `entity_id = request.entity_id` and `evaluation_time = cutoff_to_epoch(as_of_time)`. Model collation already makes graph roots this way. - **Targets-only builds.** Computed targets reference only their own rows and fields, never entity values or events. - **Supplied labels.** They are normalised by the same `_normalize_supplied_targets` the engines use, so a `Vocabulary` over a label sees the same typed values. ## Back-compat | Case | Behaviour | | --- | --- | | New artifact | No `"lengths"` in `fitted-state.json` or `manifest.json` | | Artifact written before this PR, loaded by this PR | Loads. The old `artifact_fingerprint` is checked against the summary it covers, then the summary is dropped from both files and the fingerprint replaced by the rebuilt one. Tested, including a summary edited after writing, which is refused. | | New artifact, loaded by #307 | Refused (`has no length summary` with a `length_input`, and a manifest mismatch otherwise). Older code expected the key. | | `materialize(..., fitted=...)` | Never fits, as before | | Fitted state | Bit-identical for the same inputs | | Batch metadata | Same tensors. `metadata["artifact_fingerprint"]` has a new value. | | `prepare_batch_spec` | Same fitted state; no summary in its manifest | ## Production questions | Question | Answer | | --- | --- | | Peak memory of `materialize`, all encoders pinned or declared (DiskGraph, Parquet anchors) | Before: about 11 KB per anchor. Now: about 0.1 KB per anchor, which is the anchor table. Table under "Testing Done". | | Wall time, 100k anchors | 1.02–1.05 s, against 30.1–30.3 s | | Contracts that still build (aggregates, computed targets) | Bounded per chunk. Learned values are kept as Python lists, which is about 0.1 KB per anchor per learned encoder. | | Anchor reads | Each pass fetches the fit-split anchors chunk by chunk, each only when needed: the default cutoff, one pass per graph input with an unpinned learning field (it collects every root), the input pass and the target pass. Before, there was one fetch of all anchors. | | Builds | At most two: inputs without targets, and targets (alone, or the full sample if they read input rows). Before, there was one build of every full sample. | | Unpinned graph fields | One `fit_graph_fields` over every fitting root, as before. That is population-sized, which is why it is listed as a remaining case. | ## Testing Done Head `59b4d727`: this PR's commits, merged with #307's `3ffaaa03` (which brings in main through #306's `1c46724f`). DiskGraph was built from that tree. - On this head, the targeted tests pass; conformance last ran on `88df2a4f`. In kumo-pytorch, `test_text_from_index.py`, `test_column_stats.py`, `test_fitted_state_persistence.py`, `test_model_history_limits.py`, `test_candidates.py`, `test_core_api.py`, `test_api_reference.py`, `test_keyless_tables.py` and `test_entity_identity.py` gave 177 passed, and DiskGraph `test_token_lengths.py`, `test_train_tokenizer.py` and `test_cutoff_col_stats.py` gave 14 passed; `python -m conformance --engine all` gave 705 passed on `88df2a4f`. CI runs the full suite on this head. - On `c84dcbc0`, the commit before the #307 merge: the full kumo-pytorch suite gave 1914 passed, 3 skipped. That run doubled as the fitted-state comparison below. - On `1b85da73`, before the review fixes: `python -m conformance --engine all` gave 701 passed, and `pytest -m notebook tests/test_notebooks.py` gave 3 passed. No docs page or notebook output changed. `docs/api` was regenerated for the removed parameters. - `ruff check`, `ruff format --check` and vulture: clean. - New and changed tests: - `test_column_stats.py::test_a_shared_encoder_fits_the_graph_values_of_every_root_then_the_aggregate`. - A `UseEncoding` `ZScore` is shared by a graph node field and an aggregate, over 10,000 anchors, on DiskGraph. - The test asserts the fitted mean and scale equal numpy's over the documented order: one `SampleSource.fit_graph_fields` call over every root, then each anchor's built aggregate. - Chunking the graph pass (this branch at `618107de`) fails it in the last bit: `33042.8568529613` vs `33042.85685296129`. - `test_column_stats.py::test_a_value_supplied_for_a_generated_target_is_refused_while_fitting`. It fails on `618107de`, which gave `unknown supplied target`. - `test_fitted_state_persistence.py::test_an_artifact_written_with_a_length_summary_still_loads`. It replaces the summary refusal test. - An artifact given a summary in both files, with the manifest fingerprint computed as #307 computed it, loads equal to the original. - Editing that summary afterwards is refused by the fingerprint check. - Four tests now check the late validations at batch time: - `test_candidates.py::test_unknown_candidate_groups_and_duplicate_candidates_are_refused` - `test_diskgraph_backend.py`: the materialize-time "did not exist before" block is removed; the batch-time block below it stays - `test_core_api.py::test_token_budget_rejects_one_example_that_cannot_fit` - `test_field_outputs.py::test_single_grouped_history_exceeding_padding_budget_is_refused` - `test_model_history_limits.py::test_real_model_requests_are_bounded_but_preview_and_labels_are_not` (renamed from `…_but_preview_fitting_and_labels_are_not`) now asserts that fitting that contract issues no history query: its `Vocabulary` is pinned and the rest is `Raw()`. - **Fitted state against #307, by hand**, on #307's head `252c0dbd` and this branch at `c84dcbc0`. - A pytest plugin recorded every `PreparedBatchPlan`'s fitted-state fingerprint across the full suite on both. The renamed history-limit tests are matched by their old names. - 951 tests ran on both. In 950 of them every plan matches, 3,231 plans in all. - In the remaining one, a contract `preview` that #307 refused during fitting now fits first and is refused by the preview's build. All its plans match #307's one. - 6 extra cases with 13,000 anchors (4 chunks), on both engines, plus 24 small ones: all equal. The large cases cover: - a ZScore shared across two inputs and two fields; - Buckets and Vocabulary over aggregates; - `Composite(top_k=4)`; - `MatchingGroupTarget`; - `AlignedEventTarget` with a fitted threshold; - learned computed labels. - **Memory and time, by hand, fresh processes, on `579baaa0`.** - **Peak RSS growth during `materialize`** (`VmHWM` minus `VmRSS` before the call; warm index). - The contract is #307's banking fixture with stored-column Vocabulary, Buckets, ZScore and Text, a graph, a `Raw()` aggregate and a `Vocabulary` over the supplied label. - It runs on DiskGraph with a Parquet anchor table. - Both trees fit the same state. | Fitting anchors | Before (#307) | This PR | | --- | --- | --- | | 25,000 | 332 / 337 MiB | 61 / 67 MiB | | 100,000 | 1,174 / 1,174 MiB | 75 / 75 MiB | | 400,000 | 4,640 MiB (one run) | 101 / 102 MiB | The ~60 MiB floor is fixed: imports, statistics and the tokenizer. What grows is the anchor table and one chunk. - **Wall time at 100k anchors** on a similar contract (stored columns, a graph, a `Raw()` aggregate and a `Raw()` label): 1.02 / 1.05 s and 20 / 20 MiB, against 30.1 / 30.3 s and 933 / 963 MiB. Same fitted state. - **Contracts that still build.** A 3-user fixture with 200,000 anchors, on DiskGraph with 4 threads. Each row fits the same state on both trees. | Contract | Before (#307) | This PR | | --- | --- | --- | | A ZScore shared by three aggregate fields across two inputs, Buckets and Vocabulary over aggregates, `Composite(top_k=4)`, a Buckets computed label, `MatchingGroupTarget` | 15.8 / 16.3 s, 258 / 263 MiB | 10.5 / 10.6 s, 121 / 123 MiB | | The same with `Batching(max_tokens=4096, length_input="history")` | 187.0 / 199.5 s, 286 / 288 MiB | 10.8 / 11.0 s, 122 / 125 MiB | | `AlignedEventTarget` with a learned field and a fitted threshold, and a Vocabulary computed label | 9.8 / 10.2 s, 193 / 195 MiB | 9.0 / 9.4 s, 124 / 125 MiB | The second row's 187–200 s before was the length summary. ## Where to look 1. `assembly.py: _fit_inputs`: slots, the single graph pass, the chunked input pass, composite counting. 2. `assembly.py: _fit_targets`: what is built for targets, and thresholds and groups after the chunks. 3. `assembly.py: fit_plan` (`values_for`), `_Mapped`, `_chunks`; `preparation.py: Plan.materialize`, `Plan._pinned_from_stats`. 4. `artifact.py: Artifact.load`, `_split_fit`: the length-summary removal and back-compat. 5. `encoding.py: learns_from_values`; then the tests. ## Change map [File-by-file change map](<change-map comment URL>). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
Stacked on #299. #306 (column statistics for kumo-pytorch encoders) will be based on this branch.
Change map
File-by-file change map
Problem
DiskGraph collects column statistics with exactly one collector per column, picked by the column's semantic type. A numerical column gets mean, std, quantiles and value bins. A categorical column gets category counts. A caller that needs category counts and moments for the same column has to read the data twice, once per semantic type.
Change
A column can now hold several collectors, and one pass feeds all of them. A caller picks them per column with a
StatSet:There are no new statistics and no new output format. Each member of a
StatSetis the bundle of statistics one semantic type collects today. The results go into the existingcol_stats.jsonfields. Real output for anint64column fed1, 2, 2, 3, 3, 3, 4, 4, 4, 4and one null (abbreviated):How one pass serves several stat sets:
FileColStatskeeps each column's first collector at the column's index, so the single-collector layout is unchanged. Further collectors follow after the last column, and a sorted list records which column each one belongs to.col_stats.json, a key that several collectors write keeps the first collector's value. This coverssemantic_type,count,null_countandnum_unique. Numerical comes last because it ignores non-numeric values. Kumo-format keys already include the collector's semantic type, so they don't collide.new_with_stat_setsreturns an error in three cases: the number of stat sets doesn't match the number of columns; a stat set has more than one category-counting member (for example categorical and ID); or a column's category counts intable_catdon't match whether its stat set counts categories.Back-compat
compute_col_stats_for_parquetand Kumo-format stats, all built from semantic typestest_default_output_is_unchanged, pass with no test changes.TableCategoryCounts::new(strategy, &stypes, ..)callsTesting
New test:
col_stats::tests::stat_set_collects_counts_and_moments_in_one_pass. One column is requested withCOUNTS | MOMENTSand written throughwrite_col_statsin one pass. Itscol_stats.jsonentry equals theCOUNTSandMOMENTSresults merged, and its Kumo-format file equals the union of the two. The test also covers the three error cases.Run from
packages/diskgraph:cargo test --release -p diskgraph-ingest -p diskgraph-core -p diskgraph-pybindcargo clippy --release -p diskgraph-ingest -p diskgraph-pybind --all-targets -- -D warningspytest diskgraph-pybind/python/tests(with a wheel built from this branch)rustfmt --check diskgraph-ingest/src/col_stats.rsNo Python files changed.
Benchmark: synthetic data on one machine. The table has three columns: an int64 numerical column with 1M distinct values, an int64 categorical column with 5k distinct values, and a string categorical column with 1k distinct values. In each paired run, the base branch and this PR ran at the same time on separate cores, and each figure is the best of 3. A base-against-base run varies by ±1%.
FileColStatsobserver only, 30M rows, 1 thread, 6 paired runscompute_col_stats_for_parquet, 100M rows in Parquet, 8 threads, 4 paired runsThe
compute_col_stats_for_parquetrow was measured one revision before the final commit. That revision scanned the list of further collectors on every call, where the final commit uses a binary search. The list is empty for semantic-type callers, so both revisions take the same path on this run.🤖 Generated with Claude Code