You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Plan native sequence batches with cached anchor and fitted token lengths - #339
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.
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: 2 · 1
Failed checks: 1 warning
Check name
Status
Explanation
Resolution
Change Map Design Review
## 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 checks: 2 passed
Check name
Status
Explanation
Pr Size
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
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 <!-- kumo-pr-change-map --> (#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_pragmaValueError, 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
Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 8 remain after this review.
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
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.
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.
Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 8 remain after this review.
…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]>
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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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)