Skip to content

Tier 7: Query System — Views, Pipeline, Allocation Optimization - #140

Merged
nockawa merged 25 commits into
mainfrom
feature/60-view-system
Mar 9, 2026
Merged

nockawa merged 25 commits into
mainfrom
feature/60-view-system

Conversation

@nockawa

@nockawa nockawa commented Mar 9, 2026

Copy link
Copy Markdown
Collaborator

Summary

Closes #60 — Complete Query System implementation including persistent Views with microsecond-level incremental refresh.

Core Query/View Infrastructure (#121–#126)

  • ViewDeltaRingBuffer: MPSC lock-free ring buffer with SOA layout, single PinnedMemoryBlock allocation via IMemoryAllocator, long deltaTSN (overflow-safe)
  • ViewRegistry: Copy-on-write per-field view registration with multi-tag deregistration support
  • FieldEvaluator: Type-dispatched predicate evaluation with AggressiveInlining
  • ViewChangeCapture: IndexMaintainer integration for field-granular change detection at commit time
  • View<T> / View<T1,T2>: Incremental refresh via ring buffer drain, overflow recovery via full re-query

Query Pipeline (#127)

  • ExpressionParser: C# lambda → FieldPredicate decomposition with closure support
  • PlanBuilder: Selectivity-ordered evaluation, secondary index selection (unique + AllowMultiple)
  • PipelineExecutor: Batched scan (256 PKs/batch for L1 cache), caller-provided result collections, dedicated Count path with fused secondary index streaming
  • QueryBuilder<T> / QueryBuilder<T1,T2>: Fluent API — Where/OrderBy/Skip/Take/Execute/Count/Any/ToView

Allocation Optimization (final pass)

  • PipelineExecutor accepts caller-provided HashSet/List — Views reuse _entityIds directly on RefreshFull (zero intermediate allocation + copy)
  • ViewDeltaRingBuffer: 5 NativeMemory calls → 1 PinnedMemoryBlock, tracked by IMemoryAllocator resource tree
  • PlanBuilder: insertion sort replaces Array.Sort delegate (eliminates closure allocation)
  • CollectPKsTyped: List pre-sized from plan estimates
  • DefaultCapacity: 8192 → 4096, deltaTSN: int → long

Ancillary Work

Test plan

  • 21 ViewDeltaRingBuffer tests (including concurrent MPSC stress test)
  • 13 ViewRegistry tests (including concurrent read-during-write)
  • 10 ViewChangeCapture tests
  • 35 View integration tests (single + multi-component, overflow recovery)
  • 34 PlanBuilder/Executor tests (secondary index, AllowMultiple, ordering)
  • 27 IntegrationQuery tests (end-to-end query API)
  • Full test suite passes (2047 tests)

🤖 Generated with Claude Code

nockawa added 25 commits March 2, 2026 18:25
Fix checkpoint snapshotting pages mid-OLC mutation via ActiveChunkWriters protocol
Fix BitmapL3 counter desync on Grow(), ghost bits in SetL1, missing dirty mark in ClearL0
Fix DirtyCounter inflation in WAL mode (ReleaseExcessDirtyMarks caps at 1)
Fix segment growth CRC failures with RequestPageEpochUnchecked
Fix page cache backpressure deadlock (demand-driven checkpoint flush, 100ms seqlock skip)
Switch ChunkAccessor dirty tracking from lazy to eager (MarkSlotDirty + deferred ACW)
Add BitmapL3 ReconcileState() self-healing and L0-only fallback mode
Add BTreeBase abstract class, KeyToLong, selectivity estimation (histogram + basic)
Add WAL writer diagnostics logging and segment read-sharing
Extend Shell with custom command dispatch and enhanced diagnostics
Added ARPG.Shell with new commands to use in tsh to generate data
…e, bounds validation

- VSBS: re-fetch ref rh after slot-evicting ops in AddElement/AddElements/DeleteElement/DeleteBuffer/BufferRelease/BufferAddRef
- ChunkAccessor: add chunkId bounds validation in GetChunkAddress (defense-in-depth)
- ChunkAccessor: add WarmSiblingAccessorCache (thread-local rent/return for sibling CA)
- ChunkBasedSegment: add RentWarmSiblingAccessor/ReturnWarmSiblingAccessor infrastructure
- BTree: two-CA split — primary CA for vertical descent, sibling CA for horizontal navigation
- BTree.Insert: pass sibAccessor through InsertArguments to SplitRight/SpillRight
- BTree.Remove: pass sibAccessor through RemoveArguments to MergeLeft/BorrowLeft/BorrowRight
- BTree.Move: rent/return sibAccessor in MovePessimistic/MoveValuePessimistic
- BTree.NodeWrapper: add sibAccessor overloads for HandleOverflow/HandleUnderflow/HandleChildMerge
- L16/L32/L64/String64BTree: wire sibAccessor through AllocNode and concrete split/merge/borrow
- PagedMMF: add SlotRefCount to prevent page eviction while CA slot holds it
- PagedMMF.PageInfo: add FilePageIndex validation on slot access
- PagedMMF.Metrics: add SlotRefCount tracking
- EpochManager/EpochThreadRegistry: add epoch re-stamp support
- Transaction: refresh warm cache epochs on commit to bound stale working set
- Shell: add echo command with --short/--ms/--us/--full timestamp formats
- Shell: set page cache to 1 GiB (128K pages), add comments on int overflow limit
- DiagnosticCommandExecutor: minor updates for cache diagnostics
…nowal

Engine:
 - VSBS stale-ref hardening: re-fetch ref rh after slot-evicting ops in AddElement/AddElements/DeleteElement/DeleteBuffer/BufferRelease
 - ChunkAccessor bounds validation on chunkId before page access
 - BTree: use SiblingAccessor for VSBS buffer ops to avoid CA slot eviction
 - PagedMMF: CRC computation on SavePages (CP-07 consistency), infinite wait for IncrementDirty/EnsureDirtyAtLeast (nanosecond hold time)
 - WAL ring buffer default increased from 4MB to 8MB

Shell:
 - Add db-stats command: file page capacity, per-component segment breakdown (chunk size, used/cap, fill%, pages, data size), totals
 - Add --nowal flag to bypass WAL for benchmarking/debugging

Tests:
 - Updated ResourceOptionsTests for 8MB ring buffer default
More accurate GenerateItems command.
… stack allocator + in metadata L0 free chunk bitmap.

Easier, way faster.
…mark scan, DeferredReclaim batching

- VSBS.LockBuffer: TryEnterExclusiveAccess before WaitContext creation, skip timestamp syscall when uncontended
- ComputeMinActiveEpoch: scan _highWaterMark slots instead of all 256
- BTree.DeferredReclaim: batch every 64 mutations instead of every insert
- Deferred TAIL writes: lazy backfill on first mutation via EnsureTailPopulated
…arm CommitChanges

Eliminate per-entity ChunkAccessor create/dispose and warm accessor CommitChanges calls during Transaction.Commit by hoisting accessor creation to per-component-type level and adding batch mode to warm caches.
Removed staled pointers detection in ChunkAccessor (redundant)
…angeSet

Move List<int> deferred eviction queue from ChunkAccessor struct to ChangeSet class, keeping the struct blittable for JIT inlining. Remove bounds check from GetChunkAddress.
- ChunkBasedSegment: replace Treiber stack with lock-free forward linked list, to solve high contention issues.
- Fixed small bug in B+Tree split.
- Unit tests are now more reliable, many bug fixes dues to exception being thrown in threads, an AssemblyWarmup type exec first to JIT all the code ahead of tests execution.
PK is now stored in CompRevStorageHeader, FirstItemRevision is removed and CommitSequence is internally used instead.
- PipelineExecutor: caller-provided result collections (HashSet/List) instead of internal allocation; Views reuse _entityIds directly, eliminating intermediate HashSet + O(n) copy on RefreshFull
- PipelineExecutor: dedicated Count<T> path with zero-collection counting, including fused secondary index streaming (no intermediate List)
- ViewDeltaRingBuffer: single PinnedMemoryBlock allocation via IMemoryAllocator (was 5 separate NativeMemory), deltaTSN int→long fixing overflow on long-running views, DefaultCapacity 8192→4096
- ViewRegistry: DeregisterView now removes all registrations per view (multi-tag fix)
- PlanBuilder: insertion sort replaces Array.Sort delegate, eliminating closure allocation
- CollectPKsTyped: List pre-sized from plan estimates
@nockawa
nockawa merged commit d2e5cca into main Mar 9, 2026
5 checks passed
@nockawa
nockawa deleted the feature/60-view-system branch March 9, 2026 20:41
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.

Tier 7: Query System

1 participant