Skip to content

Plan native sequence batches with cached anchor and fitted token lengths - #339

Merged
Victsm merged 2 commits into
mainfrom
codex/native-length-planning-main-20261113
Nov 14, 2026
Merged

Victsm merged 2 commits into
mainfrom
codex/native-length-planning-main-20261113

Conversation

@Victsm

@Victsm Victsm commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Plan length-aware sequence batches in the native AnchorTable iterator. Shuffle anchors into bounded pools, consume fitted constant/text-token metadata, form layout-aware batches and cache per-anchor lengths for later epochs. The history plan is prepared once; planning neither reconstructs Python requests nor re-encodes anchor histories. Frozen text constants are counted once when attaching the iterator.

Replaces #329 and targets main directly, with no #310 or #328 dependency. The reviewed patch was replayed onto current main, followed by the focused review fixes below. Existing encoder fitting/counting support is already merged. Native planning supports history EventSource inputs with Packed/Padded/Nested layouts; other sources and distributed variable-token budgets remain explicitly refused. The sparse task-owned cache uses 4–12 bytes per anchor.

Validation: 2,122 package tests passed independently on current main (3 skipped, 47 deselected), including documentation/API checks, using a rebuilt matching native module. Ruff and whitespace checks passed. Regressions verify actual tensors, shuffled coverage, row/token bucketing, caps, budgets, required-field/empty-text counting and epoch-two cache reuse. No new training-speedup claim.

Review fixes in 8824ef1e: scope planning to its designated history merge; preserve restored states with absent input provenance; count constant-only same-table components independently; release mapped token metadata on close; skip example optimizer updates without supervision. Five added regression cases fail before these fixes and pass afterward. The padded-event-budget claim was checked against real output tensors: nested events use a separate index map, not a dense padded token cube.

Change map

#339 (comment)

@copy-pr-bot

copy-pr-bot Bot commented Nov 13, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@Victsm
Victsm temporarily deployed to gha-kumo-workflow-tests November 13, 2026 23:52 — with GitHub Actions Inactive
@coderabbitai

coderabbitai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

DiskGraph adds native length planning for anchor batches, including mapped caches, token-length calculations, and iterator support for planning and sampling explicit IDs. Kumo binds fitted token-length metadata and planning contracts to supported AnchorTable inputs. The changes add tests and document planner constraints. Separately, the pragma encoder updates its validity mask, and masked-value pretraining skips batches with no valid targets and errors if an epoch has no supervised batches.

Sequence Diagram(s)

sequenceDiagram
  participant NativeAnchors
  participant RuntimeBatchIterator
  participant MappedLengthCache
  participant HistoryQuery
  participant DiskGraphEngine
  NativeAnchors->>RuntimeBatchIterator: attach length contract and cache
  RuntimeBatchIterator->>MappedLengthCache: read cached row lengths
  RuntimeBatchIterator->>HistoryQuery: query history for uncached anchors
  HistoryQuery-->>RuntimeBatchIterator: return history rows and metadata
  RuntimeBatchIterator->>MappedLengthCache: store computed row lengths
  RuntimeBatchIterator->>DiskGraphEngine: sample planned stage IDs
Loading
Merge Risk: Minimal · up to 8824e

This change adds cached native length-aware batching for supported history event inputs and makes the masked-value pretraining example skip batches with no valid targets. The earlier concerns about merge selection, missing fit provenance, per-component cost metadata, padded-budget accounting and cache cleanup are addressed at the reviewed head. No merge-blocking risk remains. The author-reported tests were not independently re-run here.

Security architecture risk: Minimal · up to 8824e

The inspected changes do not establish an introduced or worsened security or failure-containment risk. Cached metadata remains task-scoped, fitted metadata is checked before use, and unsupported planning configurations are rejected.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The inspected planning state is scoped to the calling task's anchors and local index access. Each materialization creates a fresh NativeAnchors instance with its own temporary directory, bounding cache sharing to that instance rather than introducing a cross-task cache.

Trust Boundaries and Controls

  • observed — Contract lowering rejects unsupported sources and layouts rather than silently planning them. Native attachment validates metadata types, and enqueue checks anchor IDs against cache bounds before reading or writing cached lengths.

Resilience and Maintainability Implications

  • observed — The cache distinguishes uncomputed rows from computed empty histories. Writes validate every stored field before modifying the mapping, while iterator access serializes cache operations through a mutex. Planning and sampling errors propagate to the task iteration path.

Hardening Proposals

  • proposed — For future lower-level cache reuse across different contracts, validate cache field width and cost identity when attaching planning. This would make the current reliance on a task-bound immutable policy explicit; it is not an established security regression in supported task iteration.
Pre-merge checks: Passed 2 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Change Map Design Review Warning ## Summary I read the change map from the PR conversation comment marked <!-- kumo-pr-change-map --> (#339 (comment)). It maps nine files to d… Revise the change map as described above. Then: - Add the observed failure or release requirement, and the measured or stated necessity for the cache. - Add the omitted public behavior changes (__len__/worker_batch_count raising, non-fi…
Passed Passed checks: 2 passed

Check name Status Explanation
Pr Size Passed The PR size check counts changed files. The reviewed range (refs/coderabbit/pre-merge-check/base to head) contains 9 changed files: 8 modified (M) and 1 added (A). No renames or deletions appear. Both…
Public Resource Access Passed The check applies only to external resource references (URLs, repository locations, package source locations) that this PR adds or modifies. I inspected the reviewed range (refs/coderabbit/pre-merge-c…
Full details: Pr Size

Explanation

The PR size check counts changed files. The reviewed range (refs/coderabbit/pre-merge-check/base to head) contains 9 changed files: 8 modified (M) and 1 added (A). No renames or deletions appear. Both git diff --name-status and git diff --name-only report 9 entries. Since 9 does not exceed the threshold of 40, the check passes. Line counts were ignored, as the check requires.

Full details: Public Resource Access

Explanation

The check applies only to external resource references (URLs, repository locations, package source locations) that this PR adds or modifies. I inspected the reviewed range (refs/coderabbit/pre-merge-check/base..head), which changes 9 files: 8 modified and 1 added (tests/test_native_length_planning.py). I searched all 2,067 added diff lines for http(s)/www/markdown-link/href/src references, git+, git@, github.com, pypi, crates.io, npmjs, docs.rs, .git, file://, git://, and ssh:// forms. No matches were found. The only changed documentation file, docs/05-training-batches.md, adds prose with no links. No manifest, lock, or dependency-source file changed. The new code references only repository-internal names and error codes such as DG-CURRENT-EVENTS, which are not external resources. With no added or modified external reference, the check passes.

Full details: Change Map Design Review

Explanation

Summary I read the change map from the PR conversation comment marked &lt;!-- kumo-pr-change-map --&gt; (#339 (comment)). It maps nine files to design rationales. It does not meet the check. It gives no observed failure, it omits material behavior changes, and it claims a budget invariant that the code does not clearly support. ## Findings 1. No observed failure or requirement motivates the design. The "Why" column gives design intent only. Examples: "Reuse lengths across epochs without a Python per-anchor dictionary" and "Keep batch planning in the native iterator". The table does not cite a measured bottleneck, a failing case, or a release requirement. The PR states that no benchmark was run and makes no speedup claim. The necessity of the MappedLengthCache and the native planner is therefore unproven. The table also has no stopping condition and does not separate optional refinements. 2. Material behavior is omitted. - RuntimeBatchIterator.worker_batch_count and __len__ now return PyResult. While planning is enabled, worker_batch_count raises PyTypeError (runtime_batch_iterator.rs, about lines 902–906). __len__ delegates to it (line 1099–1101). Any caller that uses len() on a planned iterator now receives an exception. The table does not mention this public API change. - The direct model-batch path now accepts non-fixed batches in single-process runs without graph neighborhoods (native_anchors.py, the fixed or world_size == 1 and not neighborhoods condition). The table does not mention this. - hm_pragma.py now raises ValueError("pretraining epoch has no masked-value supervision") when an epoch has no supervised batches. The table describes only the skip and does not mention the new hard failure. - Closing an anchor task clears the length caches and token maps. The table does not mention this lifecycle change. - RuntimeLengthCache is exported from the public diskgraph package. The only consumer found in the head revision is internal, in native_anchors.py (line 328). The table does not justify a public export. 3. The stated invariant conflicts with the code. The table says the change preserves "nested padding and token-budget semantics". For nested_padded layouts, runtime_batch_iterator.rs (lines 598–601) charges (history_sum + history_length) × max(maximum, row_maximum). That is the sum of history lengths times the maximum row cost. A padded event axis would need samples × max_history × max_row. An open review thread states that Nested(fields=Padded(), events=Padded()) is under-charged this way. The PR text says nested events use a separate index map and therefore do not need that charge. The table does not state which layout is correct, and it does not show a test for padded events. This is an uncertain design question, not a proven defect. The table still presents the invariant as settled. 4. Vague or non-self-contained rationale. - The preparation.py row says "Use the agreed length_input gate". The agreement is not stated. - The hm_pragma.py row says "Length-based ordering must not require dropping valid anchors". The file change is a masking dtype change, a zero-loss guard, and an optimizer skip. The rationale does not explain the optimizer skip or the new ValueError. - The review fixes (merge scoping, absent fit provenance, constant-only counting, mapping release) appear only in prose after the table. The table rows do not reflect them. ## Suggested correction 1. Add the observed problem. Give a measured baseline, or state that the cache is a memory and planning design choice with no performance claim. State the smallest change that meets the problem. 2. Add rows or notes for: the PyResult and PyTypeError change to __len__ and worker_batch_count; the non-fixed direct-path enablement; the new ValueError in hm_pragma.py; cache release on close; and the justif… [truncated to fit comment limits]

Resolution

Revise the change map as described above. Then: - Add the observed failure or release requirement, and the measured or stated necessity for the cache. - Add the omitted public behavior changes (__len__/worker_batch_count raising, non-fixed direct path, hm_pragma ValueError, cache release on close, and the RuntimeLengthCache export). - Resolve the padded-events budget question with the exact cost formula and a regression test. Do not keep the claim "preserves nested padding and token-budget semantics" unless that test passes. - Make the rationale for each row concrete and self-contained.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 2412654 and 8824ef1.

Files selected for processing: 6

  • packages/diskgraph/diskgraph-pybind/src/runtime_batch_iterator.rs
  • packages/experimental/kumo-pytorch/docs/05-training-batches.md
  • packages/experimental/kumo-pytorch/e2e/flows/hm_pragma.py
  • packages/experimental/kumo-pytorch/src/kumo/pytorch/engines/native_anchors.py
  • packages/experimental/kumo-pytorch/src/kumo/pytorch/preparation.py
  • packages/experimental/kumo-pytorch/tests/test_native_length_planning.py

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 8 remain after this review.

@Victsm

Victsm commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator Author

Change map

Native length-aware sequence planning replayed directly onto main. No #310 ancestry or runtime dependency; the other follow-up is independent.

File Function / scope What changed Why
packages/diskgraph/diskgraph-pybind/python/diskgraph/__init__.py RuntimeLengthCache export Expose the task-owned native mapped cache Reuse lengths across epochs without a Python per-anchor dictionary
packages/diskgraph/diskgraph-pybind/src/runtime_batch_iterator.rs LengthPlanning; with_length_planning; pool scheduling Prepare one history-length query; ignore rows marked dropped by counting, reserve 65534 as real-count saturation, and plan bounded pools using frozen costs and cached lengths Keep batch planning in the native iterator without re-encoding or parsing plans per pool
packages/diskgraph/diskgraph-pybind/src/token_stream.rs merged-history length and token-cost accounting Count capped selected histories using the same merge and layout rules Preserve first/last, missing-field, nested padding and token-budget semantics
packages/diskgraph/diskgraph-runtime/src/lib.rs MappedLengthCache Store measured anchor lengths in a task-owned sparse mapping Reuse computed lengths in later epochs with bounded private planning buffers
packages/experimental/kumo-pytorch/e2e/flows/hm_pragma.py empty-history model summary Keep empty histories valid and skip optimizer steps without supervised targets Length-based ordering must not require dropping valid anchors
packages/experimental/kumo-pytorch/src/kumo/pytorch/engines/native_anchors.py bind_token_lengths; _length_contract; native iterator attachment Consume #332’s constant/text costs, empty policies, dropped-row sentinel and policy-keyed files; lower layouts and attach the task cache Avoid Python request reconstruction or per-anchor planning-time encoding
packages/experimental/kumo-pytorch/src/kumo/pytorch/preparation.py Plan.materialize token metadata binding Use the agreed length_input gate and preserve fitted cutoff/recipe metadata Consume merged encoder work including fixed-only constants and reused fitted state
packages/experimental/kumo-pytorch/tests/test_native_length_planning.py native planning and second-epoch regressions Compare actual tensors, shuffle coverage, budgets, refusal cases and cache reuse Protect sample semantics while proving that planning avoids repeated encoding
packages/experimental/kumo-pytorch/docs/05-training-batches.md Native length-input limits Explicitly document history EventSource-only native length planning and current-event/non-EventSource refusal Avoid a hidden Python fallback or an ambiguous compatibility promise

Verification: 2,122 independent package tests pass with the exact freshly rebuilt native library; documentation/API checks are included. Ruff and whitespace checks pass. No live sweep or new benchmark was run for this replay.

The initial replay had the same stable patch ID as reviewed #329. The later focused review fixes are in 8824ef1e; all five new regression cases fail on the replay and pass on the fixed source. No source dependency on #310 or #338 was introduced.

Review fixes: scope the length-only query to the designated merge; accept absent input fit provenance; count constant-only components without unrelated stored-field metadata; release token mappings at close. The example skips optimizer steps for unsupervised batches. Incompatible variable-text recipes remain an explicit refusal.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

Note

Quiet mode is enabled, so only the most important comments were posted inline. Other review comments are grouped below.

Other comments: 1

packages/experimental/kumo-pytorch/src/kumo/pytorch/engines/native_anchors.py: 1

983-983: Minor · Stability & Availability · Quick win

Clear the length buffers stored in _event_costs.

Line 440 stores each per-node Arrow array in _event_costs. This cleanup clears _token_length_arrays instead. If a caller retains a closed NativeAnchors instance, its graph-sized length buffers remain reachable after _token_maps is reset.

Clear _event_costs during close, with a fallback for partially initialized instances.

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 8151fda and 2412654.

Files selected for processing: 9

  • packages/diskgraph/diskgraph-pybind/python/diskgraph/__init__.py
  • packages/diskgraph/diskgraph-pybind/src/runtime_batch_iterator.rs
  • packages/diskgraph/diskgraph-pybind/src/token_stream.rs
  • packages/diskgraph/diskgraph-runtime/src/lib.rs
  • packages/experimental/kumo-pytorch/docs/05-training-batches.md
  • packages/experimental/kumo-pytorch/e2e/flows/hm_pragma.py
  • packages/experimental/kumo-pytorch/src/kumo/pytorch/engines/native_anchors.py
  • packages/experimental/kumo-pytorch/src/kumo/pytorch/preparation.py
  • packages/experimental/kumo-pytorch/tests/test_native_length_planning.py

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 8 remain after this review.

@Victsm
Victsm disabled auto-merge November 14, 2026 00:16
Vedaant-J
Vedaant-J previously approved these changes Nov 14, 2026

@Vedaant-J Vedaant-J left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks okay

@Victsm
Victsm temporarily deployed to gha-kumo-workflow-tests November 14, 2026 00:37 — with GitHub Actions Inactive
@Victsm
Victsm requested a review from Vedaant-J November 14, 2026 00:39
@Victsm
Victsm enabled auto-merge (squash) November 14, 2026 00:39
@Victsm
Victsm merged commit de2bd34 into main Nov 14, 2026
145 checks passed
@Victsm
Victsm deleted the codex/native-length-planning-main-20261113 branch November 14, 2026 01:30
Victsm added a commit that referenced this pull request Nov 14, 2026
…ry batches (#310)

Preserve declared timestamp precision through aggregation, fitting,
anchors, graph features and native history batches, including exact
nanoseconds without pandas. Cutoffs retain causal-floor semantics; plain
integer anchors remain epoch seconds, while integer field/label values
use their declared timestamp ticks. Mixed query units and overflow are
refused.

This PR contains only timestamp support. Materialized statistics and
native planning now target main independently in #338 and #339; neither
depends on this PR. #332 and the earlier
aggregation/history/anchor/fitting changes are already in main.

The graph-output repair normalizes timestamp columns to their declared
type through the existing typed-array conversion before encoding. Six of
eight signed timestamp / request-versus-native-anchor cases failed
before the repair; all eight pass afterward. The eager TimestampScalar
repr concern did not reproduce without pandas on Arrow 15 or 24, so no
speculative change was added.

Validation: 291 focused clock/graph/regression checks pass on this
branch, including 177 clock cases. The complete package suite passes
2,310 checks on the combined integration of this PR with independently
based #338/#339 (3 skipped, 47 deselected), using an identical verified
native subtree. This includes the four-unit end-to-end feature/label
fitting lifecycle. Ruff, whitespace and all three published change maps
pass.

The old #328/#329 side-branch merges have been removed from this branch.
Their runtime changes now target main independently through #338/#339
and will be separate main commits.

Deferred by user: ingestion normalization/window membership, general
fitting redesign and key/IPC performance. No ingestion rewrite, tighter
input admission or new performance claim was added.

## Change map

#310 (comment)

---------

Co-authored-by: Min Shen <[email protected]>
Co-authored-by: Vedaant Jain <[email protected]>
Co-authored-by: Claude <[email protected]>
Victsm added a commit that referenced this pull request Nov 14, 2026
Fix a #339 regression where native length planning unconditionally
projected an event primary key, rejecting valid keyless tables.

Length-only sequence outputs now carry native row IDs, offsets and row
counts without dummy PK or timestamp value columns. Token costs use
node-ID metadata; direct validity checks project only their declared
input fields. The ordinary compiler also stops adding a placeholder for
constant-only events.

This intentionally extends the shared `query_temporal` /
`query_temporal_lengths` contract to accept empty sequence output
projections. Both reuse existing Arrow row-count handling; a length-only
bypass would add a second admission rule for the same supported result
shape. Frame-level PK/clock reads needed for deterministic ordering and
temporal filtering remain unchanged. Existing chronological EventSource
clock validation remains unchanged.

Validation: 202 focused Python tests pass with the matching native
library, including the complete temporal-query-shapes file (7 passed).
The old zero-column refusal test now verifies identities/row
counts/lengths for empty and nonempty results through both public
methods. Coverage also includes constant-only keyless events, four other
row representations, Packed/Padded layouts, 128-anchor parallel pools
and epoch-two cache reuse. Direct generic queries cover a real
no-PK/no-clock index with zero decoded values. Rust library tests: 288
passed; Rust source is unchanged since that run.

Modified runtime/API/shape-test lint and whitespace checks pass. The
aggregate-program test module retains one unchanged baseline PLC0206
diagnostic.

## Change map

#341 (comment)

---------

Co-authored-by: Min Shen <[email protected]>

This branch was previously deployed

1 inactive deployment
gha-kumo-workflow-tests — 8824ef1e Deployed Nov 14, 2026 by Victsm via import #2366
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants