Repository navigation
#629 Index ownership consolidation — retire the per-ComponentTable secondary index - #680
Merged
Merged
Conversation
… per-archetype index defects All four share one root cause (#629): the index home is decided per ARCHETYPE, not per component StorageMode, so any archetype with an SV or Transient slot puts EVERY component's indexes — Versioned ones included — on the per-archetype segment. That path was written for SingleVersion-only archetypes and never grew the cases the flat path already handled. #660 — view delta PK space. Cluster paths published a bare 48-bit EntityKey into view deltas while flat paths published a full EntityId, so a consumer could not tell which it held. ViewDeltaEntry.EntityPK and FieldShadowBuffer.ShadowEntry.EntityPK are now typed EntityId rather than long, which turns the mismatch into a compile error at every producer and consumer. Same 8 bytes, blittable, ViewDeltaEntry stays exactly 24 bytes. Consuming as EntityKey was not viable: the ViewRegistry is per-ComponentTable and shared across archetypes, so a consumer cannot infer routing. #659 — AllowMultiple drain at the tick fence. A multi-value B+Tree leaf holds a VSBS buffer id, not an entity location. ProcessClusterShadowEntries called plain Move/Remove unconditionally, overwriting that buffer id with a raw ClusterLocation and dropping every entity sharing the mutated key at once. Now branches on field.AllowMultiple and threads the per-entity elementId through the cluster tail, matching its flat twin ProcessShadowFieldEntries. The pre-existing coverage missed this because it asserted key presence; the corruption is in the key's VALUE, so the new tests enumerate the key's values and resolve each to an entity. #658 — String64 node stride. A segment serves exactly one node size and every B+Tree variant asserts segment.Stride == sizeof(its node). Index16/32/64Chunk are all 256 bytes so one segment covered every numeric key, but IndexString64Chunk is 356. The cluster path allocated only the 256-byte segment and handed it to every field type: assert in Debug, writes past the chunk into its neighbour in Release. Adds a second per-archetype segment at the String64 stride, allocated only when needed, and gives each of the four sites that walk fields (init, rebuild, spawn, destroy, migration) a per-segment accessor instead of one accessor for all fields. [Index] on a String64 field is now rejected at registration for SingleVersion/Transient, which capture index keys through an 8-byte KeyBytes8 shadow slot that a 64-byte key overruns — see #667; Versioned is the reachable case and is what the stride fix makes work. #657 — directory key collision. Trees sharing a segment are found on reopen through a chunk-0 directory keyed on StableId = FieldId, and FieldIds are numbered per component definition. Two components in one archetype each indexing their field #0 both registered StableId 0. Creation worked because each instance caches the offset of the entry it appended; on reopen FindInDirectory returned the first match for both, so two live trees bound to one root and one component's index silently answered with the other's entities. The key is now the pair (StableId, Slot), carried by BTreeStableKey and stored in the directory entry's former Reserved short. An implicit conversion from short keeps every per-ComponentTable call site at slot 0 unchanged. Registration also rejects a duplicate pair rather than appending a shadowing entry, and MaxDirectoryEntries — a hardcoded 20 derived from a long-stale 64-byte chunk assumption — becomes BTreeBase.MaxDirectoryEntriesFor(stride): 84 at 256 bytes, 116 at 356. Repurposing Reserved changes on-disk directory semantics. Existing databases mis-resolve slot > 0 trees on reopen. Clean cutover, no shims, per pre-alpha policy. Two fixes beyond the issues, both surfaced by the above. The cluster index path never cleared a shared segment before re-registering trees into it, which silently appended shadowing directory entries and orphaned the old node chunks whenever loadIndexes went false on an existing segment; it now calls ClearSharedSegment first, as ComponentTable.BuildIndexedFieldInfo already did on its crash path. And the cluster destroy path copied the index key into a KeyBytes8 before calling Remove/RemoveValue, which take a void* — it now passes the field pointer directly, removing a copy at every key width. Tests: 11 new across ClusterViewDeltaTests, ClusterMultiValueIndexTests, ClusterString64IndexTests, ClusterIndexDirectoryTests and BTreeDirectoryTests. Every one was proven non-vacuous by reintroducing the bug it covers and confirming it fails. They assert at the index level rather than through WhereField, because at these entity counts the planner takes Path B (zone-map prune + direct SoA scan) and never touches the B+Tree — a query-based assertion reports the component data and passes happily over a corrupted index. LastOpenClusterIndexRebuildCount is added as a test oracle: it lets the reopen repro assert it is on the directory LOAD path rather than the create-and-rebuild path, which resolves keys differently and would make the test vacuous. Storage introspection and the Workbench file-map decoder now surface Slot, so two trees that differ only by slot no longer render as identical rows. Full suite 4125 passed, 0 failed. Workbench 608 passed, 0 failed. New fixtures verified in Release, where the stride assert is compiled out. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EHeNfnyttwHccbZ4wRxQQ7
…erse-lookup consumer now reads both index homes A secondary index lives either on the ComponentTable (one tree per component type, shared by every archetype holding it, values are chunk ids) or on the ARCHETYPE (one tree per archetype per field, values are packed ClusterLocations). Which one applies is decided by the archetype's COMPOSITION, not the component's storage mode — an archetype with any SingleVersion or Transient slot is cluster-backed and owns its indexes. Three consumers read only the first. #662 FK navigation. FkSourcePkResolver.Create guarded on StorageMode.SingleVersion and threw NotSupportedException — the wrong axis. A Versioned component in an archetype made cluster-eligible by an SV sibling sails past that guard and returns a silently empty set. Added FkReverseLookup: two phases, not one loop, because the ComponentTable tree spans archetypes and scanning it inside a per-archetype loop reports every non-cluster hit once per candidate. Phase 1 runs it once for all non-cluster candidates, phase 2 once per cluster-backed candidate. Struct-generic IFkSourceAction callback rather than an enumerator (RangeMultipleEnumerator is a ref struct; a hand-rolled one would be three-level while owning per-archetype ChunkAccessor lifetimes across MoveNext). FindFKIndex becomes FindFKIndexOrdinal, since the ordinal indexes both homes. #663 Incremental views. Execute() had a cross-archetype loop; the four ExecuteFullScan view-population sites did not, so a view on a cluster-backed archetype populated to nothing and stayed empty through every refresh. All five now share EcsQuery.ScanAllArchetypes, generic over an IEntityIdSink struct so one loop serves both Execute()'s HashSet<EntityId> and a view's HashMap<long>. Two findings fell out: the AND population sites applied no archetype filter at all, and two of RefreshFull's three branches are unreachable dead code (#668) — including the one that was cluster-correct, so that site was always broken rather than conditionally. #664 Cascade delete. FindCascadeChildren had no guard of any kind: it resolved the ComponentTable tree and dereferenced CompRevTableSegment unconditionally, so a cluster-backed child archetype scanned an empty tree, the parent was destroyed and the children silently orphaned. Ported onto FkReverseLookup via a CascadeChildCollector action struct. The routing-id filter stays — structurally redundant in phase 2, still load-bearing in phase 1. Three latent bugs found and fixed beyond the ACs: the cluster index path never cleared a shared segment before re-registering (shadowing directory entries, orphaned node chunks); two EcsNavigationTests were broken in themselves and invisible while [Ignore]d (tx.Open where OpenMut was needed, and a missing WriteTickFence — SV in-place writes defer both index maintenance and the view delta to the fence). Every fix proven non-vacuous by reverting it: #663 fails 6 of 7, #662 fails 5 of 11, #664 fails 4 with the cluster phase disabled and 6 with the Versioned PK decode forced (the predicted NullReferenceException). Suite 4146/0, Workbench 608/0. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EHeNfnyttwHccbZ4wRxQQ7
…Transient index home Three issues in one commit because they interleave in DatabaseEngine.cs and DifferentialRecoveryOracleTests.cs; splitting by hunk would produce commits that do not build. #661 The per-archetype index segment roots move into ArchetypeR1. They lived in the bootstrap dictionary under clusterindex.{ArchetypeId} — a key built from the per-process catalog id that ArchetypeR1 itself documents as not stable across processes. Every other archetype-keyed durable pointer lives in the name-matched row, and ComponentR1 already carried the equivalent pair for the per-ComponentTable home, so this removes an exception rather than adding a feature. ArchetypeR1 goes to revision 2 with ClusterIndexSPI + ClusterString64IndexSPI appended, which keeps every existing field id stable and zero-fills to the "not persisted, rebuild" sentinel the other SPIs already use. Both are now part of the checkpoint skip comparison instead of a write placed below it, so a root whose value changed is persisted even when nothing else did. The legacy keys are removed by prefix sweep, not merely left unread: each cost ~22 B of a fixed 8016 B page whose overflow throws from inside PersistMetaNow, under _metaLock, mid-checkpoint. Sweeping by prefix is what lets a database whose catalog numbering has already shifted be cleaned at all. #656 RB-01 crash rebuild for the per-archetype index home. On crash reopen the cluster-index init block read the persisted SPI, loaded the segment and skipped its rebuild — WalFilesPresentAtOpen is consulted in six places and none was that block. RB-04 then skipped CRC-failed index pages on the premise that RB-01 discards and rebuilds them, which was true for the per-ComponentTable home only, so a torn cluster-index page was neither loud-failed nor rebuilt but silently served. The rebuild could not simply be re-enabled where the clear lives: that block runs inside InitializeArchetypes, before RunWalV2Recovery, so it would index pre-apply state — RB-01 satisfied and RB-02 broken, yielding an index that is confidently wrong rather than merely stale. The clear stays at open and RebuildClusterIndexes runs in Phase 5, from the cluster SoA. RebuildSecondaryIndexes carried a comment claiming the cluster path handled these "not here" — true on a clean reopen, false on the crash path; each side believed the other did it. Reverting #656 under TornCheckpointedClusterIndexPage_RecoversViaRebuild kills the test host with an AccessViolationException rather than failing an assertion: a per-archetype index leaf holds a packed ClusterLocation, a pointer into the cluster SoA, so a trusted torn page dereferences garbage exactly the way RB-01 says a trusted torn EntityMap does. That home belongs in the EntityMap's category, not the opaque-bytes one, and RB-01's on_violation now says so. #655 steps 1-3: an indexed Transient component no longer disqualifies its archetype from cluster storage, when the archetype also holds an SV or Versioned one. Both documented reasons for the exclusion were wrong — the BTree<TransientStore>/BTree<PersistentStore> split constrains tree instances rather than archetype placement, and the "cluster Write<T> returns a ref so there is no hook" claim was false, since EntityRef's Transient write branch already ran the shadow capture before returning. ClusterIndexSlot/ClusterIndexField are now generic over the page store, CreateIndexForFieldCore replaced two byte-identical factories, and the drain, capture, spawn and destroy paths each run once per home. Three segments are in play and they are not the same axis: index (the tree's nodes), primary (occupancy word + AllowMultiple elementId tail) and data (the component bytes). They collapse onto one segment for an SV/Versioned slot, which is why one accessor sufficed before. The query path needed one line, not a rewrite: ScanPerArchetypeBTree returned with no results when the slot lookup missed, so a Where on a Transient field would have been silently empty — the #663 shape from the other side. Those archetypes route to the cross-archetype scan, which evaluates against component data and is therefore correct whichever home owns the index. Using the Transient tree for selectivity there is a performance follow-up. Removing the exclusion deletes the {SV + Transient-indexed} shape, which was the only way to build a non-cluster archetype holding a SingleVersion slot — RB-01/RB-04's entire "non-rebuildable EntityMap" residual. EntityMapRebuildability_Classifier now asserts that archetype IS rebuildable, and CommittedDisciplineTests' flat fixture became pure-Versioned because that is the only flat shape left. A PURE-Transient archetype with an indexed field is still excluded, and that is measured rather than assumed: lifting the gate fails five TransientIndexTests with silently-empty queries, because with no ClusterSegment the cluster scan cannot run and the non-cluster fallback reads ComponentTable.TransientComponentSegment, which holds nothing for a cluster-backed archetype. Path B has to become store-generic first. Its fence drain is already in place. Every fix proven non-vacuous by reverting it: #661 fails the retired-keys and skip-guard tests, #656 fails all four of its new tests (index axis 0 of 40, multi-value 0 of 120, mid-checkpoint exactly the checkpointed 30 of 50, torn page an AccessViolationException), #655 fails 5 of ClusterTransientIndexTests' 7. Suite 4162/0, Workbench 608/0. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EHeNfnyttwHccbZ4wRxQQ7
…zone-map/capture defects the gate was hiding Removes the last piece of the Transient-indexed cluster exclusion. The eligibility rule is now exactly "at least one SingleVersion or Transient slot" — pure-Versioned is the only disqualifier left, which is what ADR-045 §5 always intended. Path B splits into a store-picking dispatcher (ScanPerArchetypeBTree) plus a store-generic core (ScanClusterSoa<TSink, TPrimary, TData>) taking primary and data accessors by ref. Same three-store split as the drain — index / primary / data are separate axes that only collapse for SingleVersion and Versioned slots — and deliberately the same code shape. FindClusterIndexSlot searches both homes and reports which one it found; it is the only place that knows a second home exists. Path A stays persistent-only because its collector is typed to BTreeBase<PersistentStore>, and the planner routes every Transient home to Path B, which is correct either way since Path B never touches a tree. Lifting the gate cost 2 test failures rather than the 5 predicted, and the predicted mechanism was wrong: PipelineExecutor.ExecuteCore does nothing at all without a secondary index, so the non-cluster fallback was never involved. Both failures were post-mutation queries returning zero under BOTH the old key and the new one, while the SoA data was correct and EntityRef.Read agreed. That signature is a zone map, not an index. RecomputeClusterZoneMaps walked the persistent home alone — a defect step 3 shipped into mixed archetypes too. Spawn only ever widens a zone map (InsertClusterIndexEntries was already generic, which is why spawn-only queries passed throughout); tracking a value that moves out of range is the fence recompute's job, and the Transient home never got one. Path B then prunes the whole cluster: the new key is pruned, the old key is scanned but no longer matches. Fixed by dispatching the recompute over both homes with a ZoneMapArray.Recompute overload taking primary and data bases separately — on a mixed archetype the occupancy word is in the cluster chunk while the column is in the Transient one, and recomputing off a single base reads an all-zero occupancy word and silently marks the map invalid instead of refreshing it. The PrepareArchetypeFence gate also moves from IndexSlots != null to either home, or an archetype whose only indexed component is Transient skips both the drain and the recompute; the pure-Transient branch gains a recompute it never had. ShadowClusterIndexedFields captured nothing on a pure-Transient archetype: _transientClusterBase is null there because _clusterBase already IS the Transient base, so the per-home base split from step 2 hit CaptureIndexedSlots' null guard and skipped capture entirely, leaving the tree on the pre-mutation key for the entity's whole lifetime. The exact mirror of the bug that split exists to prevent. Independent of the zone-map defect and invisible to queries, since Path B never reads the tree. Tests: ClusterPureTransientIndexTests (5, new) covers placement, spawn, the fence-time key move, the zone-map regression and AllowMultiple sibling preservation; ClusterTransientIndexTests gains the mixed-archetype zone-map counterpart; the 12 pre-existing TransientIndexTests now run on the cluster path throughout. Non-vacuity by reversion: restoring the exclusion fails 4, disabling the Transient zone-map recompute fails 4 across all three fixtures, reverting the capture base fails exactly 1. Known gap, deliberate: ordered streaming skips a Transient home because ArchetypeSortedStream takes a BTreeBase<PersistentStore>. Those archetypes fall through to the generic sort — correct, but sorted by EntityKey rather than by the ordered field when the order-by column is the Transient one. Both sites carry the note; folded into #665. Engine suite 4168/0/53 skipped, Workbench 608/0, Release run of the three fixtures 25/25. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EHeNfnyttwHccbZ4wRxQQ7
… the cluster index home Two independent steps, both prerequisites for #666 deleting the per-ComponentTable index. Step 1 — write-path guards. The gaps were narrower than the issue framed them: the fence-time drain (DrainClusterShadowSlots) already short-circuits on an unchanged key and already hoists its accessor per field per tick. Everything missing lived in ReconcileClusterIndexAndViews, the COMMIT path — Versioned and Commit-discipline SingleVersion only. Worth recording so #666 does not double-count the work. The unchanged-field guard lands there, and takes the AllowMultiple double-dirty with it: an unchanged field never reaches GetChunkAddress(forWrite: true) at all, so no cluster page is dirtied to move a key onto itself. The index accessors join the existing archetype-keyed cache alongside map/content/cluster — two of them, default stride and String64 stride, because a segment serves exactly one node size. The three byte-identical accessor-establishment blocks collapse into one EnsureClusterCommitAccessors: the set has to stay in step with its disposer and three copies is three chances for it not to. The guard cannot be written with KeyBytes8. Its flat twin ReconcileFlatIndexAndViews compares that way and is correct to, because Commit discipline is SingleVersion-only and registration refuses a String64 index on any in-place storage mode. The per-archetype path has no such luxury: it is also the Versioned commit path, and Versioned is exactly where a String64 index is legal. Comparing 8 of 64 bytes silently skips the move and leaves the entity indexed under a key it no longer has — invisible, since the query layer refuses String64 predicates and cannot contradict it. The first shape of the guard was a 3% regression, and only the benchmark said so. The suite had no benchmark for this path at all: AaVcHealth carries no index, so VersionedWriteCommit never entered the field loop. IndexedVersionedCommit_KeyChanges / _KeyUnchanged write the same component through the same path and differ only in whether the indexed field moves, so their ratio measures the guard without a cross-version A/B. Guard off, the two are identical at 92.66 and 92.56 us — the defect stated as a measurement. Guard via SequenceEqual: key-changed 95.45 and 95.35 us across two runs, a reproducible +3.0%, against key-unchanged 75.02 and 73.87 us. Guard via FieldBytesEqual switching on the width: key-changed 93.53 us, +0.9% and inside the error bars, key-unchanged 73.01 us, -21.1%. A guard has to pay for itself on both sides, not just the one it optimises. Step 2 — per-archetype index statistics. IndexStatistics[] per slot on ClusterIndexSlot<TStore>, needing no generic surgery because the constructor already took the store-agnostic IBTreeIndex. A per-archetype MutationsSinceRebuild on ArchetypeClusterState, incremented at spawn, destroy, the fence drain and the commit reconcile, always past the guards. StatisticsWorker gains a second pass and StatisticsRebuilder.RebuildClusterAll walks active clusters instead of ComponentSegment pages — pointing the existing scan at a cluster archetype would sample nothing and publish statistics built from an empty scan, which is worse than leaving them stale. The ~150 lines of accumulator setup, sample scaling and atomic publication are extracted into a private Accumulators type so both scans share them; only the scan differs. ISelectivityEstimator.EstimateCardinality now takes IndexStatistics[] instead of a ComponentTable, since both implementations only ever reached through the table for table.IndexStats. The degraded-plan hypothesis is confirmed, and worse than filed. It was logged as likely degraded plan choice rather than wrong results. Measured: ComponentTable.IndexStats[f].EntryCount is 0 for a cluster-backed archetype, because that array wraps a tree with no entries in it. Every estimator returns 0 for every predicate, so the plan was not built from a skewed number but from an empty one. EstimateClusterSelectivity then reads the 0 as unknown and takes Path B unconditionally, which is why nothing ever looked broken. PlannerStats is asserted at the seam deliberately. Path A and Path B return the same entities, so the planner's choice is a performance decision that no query result distinguishes — an end-to-end test would pass either way. Multi-archetype queries keep the old behaviour: across several archetypes there is no single distribution to hand the planner, and blending them would reintroduce the very defect that splitting the array fixes. The mutation counter doubles as the only honest observable for the guard. It is incremented past the guards, so "an unrelated write does no index work" becomes an assertion rather than a claim about page counts, which is why the two steps share one fixture. Non-vacuity by reversion: excluding PlannerStats fails 1, disabling the guard fails 1, disabling the cluster rebuilder fails 1, narrowing the comparison to 8 bytes fails the String64 test. Also corrects a stale comment in the benchmark fixtures: cluster eligibility no longer excludes archetypes carrying an indexed Transient component, since #655. Engine suite 4174/0/53 skipped, Workbench 608/0. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EHeNfnyttwHccbZ4wRxQQ7
Deletes TemporalIndexQuery, TailGarbageCollector, VersionedIndexEntry, IndexBufferExtraHeader, TailVSBS, TailIndexSegment, ComponentR1.TailIndexSPI, Transaction._batchTailAccessor, ClearMultiValueTail and preserveEmptyBuffer. 28 files, -1283 lines net. To be accurate about what this is: TemporalIndexQuery was implemented, tested and working — not a stub and not dead code. It was UNREACHABLE, which is a different thing. No public API was ever added to ask a point-in-time index question, so the only callers in the repository were its own tests. Meanwhile every AllowMultiple mutation on a Versioned component appended a 12-byte entry to a log that the specified pruning algorithm never auto-triggered on, so the TAIL only grew. Real cost charged to every user, capability reachable by none. The judgement call is Loic's and was made explicitly: keeping it means either accepting that cost on all indexes, or building a dedicated opt-in path — one more code path, one more feature, for a capability we are not confident we want. Removed on that basis. What survives is the half that carried the correctness argument. Element-precise MoveValue/RemoveValue — one traversal, addressing the entity's own element rather than the key — is what keeps an entity from being stranded between keys on a value change and from taking its siblings with it on delete. That was always independent of the history log. The removal cascaded past the planned list. IndexBufferExtraHeader's only field was TailBufferId, so the four B+Tree variants dropped from VariableSizedBufferSegment<int, TExtra, TStore> to the plain two-argument form, which orphaned the three-argument VSBS class itself. preserveEmptyBuffer existed solely to keep an emptied HEAD buffer alive so its TAIL stayed reachable; with every caller now passing false the flag and its four conditions collapse out of the hot MoveValue/RemoveValue paths. IndexMaintainer goes 469 to 265 lines and its batch overloads lose the ref tailAccessor parameter that was most of what distinguished them from the plain ones. Its "LEGACY — will be removed after #168" header was wrong twice over and is corrected: the file is live, and #666 is what removes it. Two storage-layout changes, safe only because this is pre-alpha: dropping IndexBufferExtraHeader takes four bytes off every AllowMultiple index buffer root, and dropping ComponentR1.TailIndexSPI shifts every field after it in a persisted schema row. Verified first that no database fixture is checked in anywhere in the repo, so every test builds fresh and nothing reads a pre-change file. VersionedIndexTests was 17 tests, 14 of them TAIL. The three that remain cover the current-set path — spawn/update/read, and an AllowMultiple key move that must leave siblings in place — because that is the behaviour the pure-Versioned migration must not change. Engine 4160/0/53 skipped, Workbench 608/0, Shell 22/0, whole solution builds. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EHeNfnyttwHccbZ4wRxQQ7
…anning the component segment ComponentTable.PopulateNewIndexes runs when schema migration adds an [Index] to an existing field, and backfilled by scanning every allocated chunk of the component segment, inserting key -> chunkId. Correct for SingleVersion. Wrong two independent ways for Versioned. The VALUE must be the CompRev chain root. RebuildSecondaryIndexEntriesFromHeads inserts key -> rootChunkId and PipelineExecutor.ExecutePKsTypedVersioned walks the revision chain starting from whatever the leaf holds, so a content chunk id hands the reader a meaningless start. The POPULATION must be live entities. Every allocated chunk in a Versioned component segment is a retained REVISION, so a repeatedly-updated entity contributed one entry per revision, each keyed on whatever value that revision happened to hold — resurrecting superseded keys as though they were current. PopulateNewIndexes now dispatches on StorageMode. The Versioned half mirrors the Phase-5 crash rebuild: walk chain heads, skip tombstone heads, insert key -> rootChunkId, write the element id back to the content tail for AllowMultiple. SingleVersion keeps the segment scan, which is correct for it — one chunk per live entity, and the index value IS that chunk id. Transient never reaches migration at all; its data does not survive a restart. EnumerateVersionedChainHeads takes an optional archetype filter now instead of a required one. The crash rebuild passes one because it runs per archetype; this backfill must not, because a ComponentTable's index is shared by every archetype holding the component and a filtered backfill would leave the others unindexed. On the test, stated plainly because the first version of it proved nothing. It failed before the fix and passed after, which looked like proof and was not: the failure came from querying the wrong archetype, and once corrected the test passed with the buggy code too, because the query path does not read that index. Only reverting the fix revealed it. The assertions now read the B+Tree directly. Even so it pins only the POPULATION half. Measured, not assumed: content chunks are recycled into the same small-integer range as revision chunks, so a content chunk id written as a leaf value numerically aliases a valid chain root and resolves to a plausible entity instead of failing. Raising revision churn does not separate the id spaces. That aliasing is very likely why the bug survived this long, and the limitation is written into the test's remarks rather than left implied. Separately worth following up before #666 migrates this population: the query returned correct results whether the index was right or corrupt, so something other than this index served it. Engine suite 4161/0/53 skipped. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EHeNfnyttwHccbZ4wRxQQ7
…per-archetype home The last disqualifier for cluster storage — an archetype made only of Versioned components — is gone. A cluster stores the Versioned HEAD in the slot and keeps the revision chain separate, which is exactly what a mixed SV+Versioned archetype has done since Phase 5, so the machinery was never the obstacle. `isClusterEligible` is now unconditionally true. That makes the per-archetype index the only index home that ever holds entries, so every remaining reader had to move off the per-ComponentTable trees: - `Transaction.EnumerateIndex` is now an archetype fan-out. It K-way merges the already-sorted per-archetype runs instead of concatenating and re-sorting them (12.9x on set-up, 2.5x on the whole scan), and streams directly from the cursor when a single archetype holds the component so early termination still works. The old implementation read only the shared tree, so for a component held by both a flat and a cluster-backed archetype it silently returned half the entities — the same defect as #663, in the public API. - `DiagnosticCommandExecutor` resolves index statistics and B+Trees through the archetypes that own them, across both `IndexSlots` and `TransientIndexSlots`, and reports Transient-only indexes honestly instead of showing an empty tree. - `IndexTestHelpers` gives the test suite the same access, joined on component-table identity rather than on a guessed archetype name. Two bugs found and fixed along the way: - The cluster commit path cached its content accessor keyed on the archetype, but content chunks belong to the component. An archetype carrying several Versioned components looked the second one's chunk id up in the first one's segment and copied whatever sat there into the cluster slot. Now keyed on the segment. `MultiVersionedClusterCommitTests` covers it — 2000 entities x 15 rounds, two Versioned components of deliberately different sizes, read back through a query because `Open().Read()` resolves through the chain and passes either way. - `IndexEntityEnumerator.MoveNext` had a `stackalloc` inside its loop. Every skip path — freed slot, zero entity id, null chain root, revision invisible at this snapshot — looped back and allocated again without the stack pointer being restored until the method returned, so one call over a mostly-invisible range grew the frame without bound. Hoisted to one buffer per call, sized for the largest archetype. `StorageModelProfile` is the A/B harness used to measure the switch: indexed queries 4.3x/7.2x faster, indexed writes +16-19%, unindexed writes no signal, disk +19.6%. Tests asserting the old flat home are re-pointed; the schema-evolution ones are not, because `SchemaEvolutionEngine` is cluster-blind — tracked as #671, which gates deleting the flat path.
…uild from chains, and fix three crash-path defects Second half of the index-ownership consolidation. The per-ComponentTable index home is gone: IndexMaintainer and FkSourcePkResolver are deleted, PipelineExecutor drops to EvaluateFilters + FindFKIndexOrdinal, the four index segments and their bootstrap slots are removed (the 3 system tables go from FromInt4 to FromInt2 — a format change, no back-compat obligation pre-alpha), and IndexedFieldInfo keeps only the metadata the per-archetype code is built from. Every archetype now keeps its indexes on ArchetypeClusterState.IndexSlots. SelectPrimaryStream and SelectFullScanStream are pinned to -1 rather than reimplemented. The trees they scanned no longer exist, so the old bodies cannot compile; against origin/main this does cost the selective B+Tree scan, because pre-flip those shared trees were populated and the selection was real. Getting it back needs the overloaded PrimaryFieldIndex == -1 sentinel split in two (it currently means both "no index stream" and "use the K-way merge / SoA path", and ExecuteOrderedClustered and ScanAllArchetypes each key off one meaning) plus the float/double full-range question, where TypeMinAsLong/TypeMaxAsLong return raw IEEE bits that do not bracket negatives. Tracked, not forgotten. Three defects fixed, all of them made reachable by the eligibility flip rather than introduced by it: #14 host crash. On a crash reopen with a prior clean shutdown, InitializeArchetypes ran RebuildVersionedHeadFromChain before RebuildEntityMapsFromPersistedData had discarded and re-derived the EntityMap. That walk reads engineState.EntityMap.Segment, so it dereferenced a torn page's garbage hash-directory pointers into a hard AV with no managed exception at all. The code comment at the rebuild gate already named this as a documented residual, unreachable while no cluster archetype was also EntityMap-rebuildable-on-crash. WillRebuildEntityMapOnCrash now drives both the gate and a deferral, so the head rebuild is drained after the map is re-derived and always reads a fresh one. The clean-reopen path is unchanged. #673 seal watermark. The recovery seal consolidated revisions but never persisted TransactionChain.NextFreeId, so a later WAL-less open snapshotted below them and MVCC hid every one: entities alive, components reading as zeros, no error. Fixed through MutateBootstrapAndPersist. The obvious alternative, mirroring the clean-shutdown state save, takes the page-0 exclusive latch and races the live checkpoint thread into a process kill — verified by bisect, twice. QueryRead read cluster records with the flat accessor. Byte 14 is Location[0] in a flat record and ClusterChunkId in a cluster one, so every entity sharing a cluster resolved to whichever entity that chunk id happened to name. Same guard as the EntityRef resolve path. Any() was missing the cluster guard Count() already had. #671 Versioned half: RebuildClusterFromChains derives membership from the Versioned chains, claims cluster slots, rebuilds heads, indexes and spatial state. The SingleVersion half now fails loudly instead of silently producing flat records for a cluster archetype. Known failing on this branch, both confirmed mine against a pristine origin/main control that runs the full suite green: Versioned_ConcurrentSnapshot_IsolatedView (a reader sees rows committed after its snapshot) and SlotReuseUnderCachePressure_LeavesNoQuiescentPageWithOddSeqlock (duplicate segment root page on a fresh database under a deliberately undersized cache). Everything else passes and the suite no longer aborts. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EHeNfnyttwHccbZ4wRxQQ7
…ation on the cluster scan Two defects, both surfaced by making every archetype cluster-backed but only one of them caused by it. The allocator handed the same pages out twice under cache pressure. The occupancy L0 page is protected by DirtyCounter, but SavePages copies the page content, fsyncs, and only then decrements — and EnsureDirtyAtLeast(idx, 1) is a no-op while the counter already reads 1, so a bit set inside that window was not in the bytes that reached disk and had nothing left protecting it. The flush's decrement took the counter to 0, the page became evictable holding an unwritten bit, and the next allocation reloaded it stale. The trace shows the same occupancy segment page coming back in a different cache slot with the bit gone. Raising the floor to 2 leaves at least one mark after a single in-flight flush's decrement, so the page stays un-evictable until a flush that actually captured the bit, then drains normally. Plain IncrementDirty also closes it but is unbounded here — with no ChangeSet there is no owner to release the marks, so the counter would climb with every allocation and the page would never be evictable again. This is a latent engine bug, not a #629 one: the flip only made it reachable by roughly doubling open-time segment allocations, and any allocation-heavy workload on a small cache could hit it on main. ScanClusterSoa had no MVCC visibility check at all — it walks current occupancy and evaluates predicates against the SoA column, so a reader saw entities committed after its own snapshot. 04-data.md specifies the opposite and names Versioned_ConcurrentSnapshot_IsolatedView as the proof, so the gate is now the same BornTSN/DiedTSN test the chain-walking paths already apply, resolved from the entity's EntityMap record header at both emit sites. It is gated on VersionedSlotMask so pure-SingleVersion and pure-Transient archetypes keep the lookup-free scan — the storage-mode matrix is explicit that neither promises isolation. An unreadable record counts as visible: the scan already proved the entity occupied, and silently shrinking a result is the failure mode this migration exists to remove. That fixes the phantom half only. The value half is still broken and is filed as #674: predicates read the committed HEAD column, so an update committed after a snapshot leaks in as a non-repeatable read (verified, before=1 after=0). The born/died gate cannot fix it — it decides whether an entity is visible, not which version its data should be read at. Committed as an Ignored test rather than deleted so the gap stays visible in the suite. #674 lays out the options and flags the soundness wrinkle in the obvious one: an entity whose HEAD fails the predicate but whose visible version would pass never becomes a candidate, so verifying matches against the chain is not sufficient on its own. Full suite green for the first time on this branch: 4169 passed, 0 failed. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EHeNfnyttwHccbZ4wRxQQ7
…ver the storage-mode axis Completes cluster-aware schema evolution. A SingleVersion component has no revision chain — the cluster slot IS its data — and a migration changes component sizes, which changes ClusterSize, which moves every offset in the cluster. So its bytes have to be copied cluster-to-cluster, and that copy is the irreducible new code the issue called for. MigrationResult now carries the field map and the pre-migration component size, and _migratedComponents became a dictionary to keep them alive until the archetype pass. For a SingleVersion component the ComponentTable migration is skipped entirely rather than run: its ComponentSegment is never populated, so migrating would load an empty segment at the old stride and fail with a storage error that says nothing about the real problem. It publishes only the remap instead, and the component's own SPIs carry over untouched. The ComponentTable migration constructor turned out to be Versioned-only by construction — it hard-codes the storage mode and asserts it — so the caller now discriminates on NewComponentSegment rather than on HasValue. CapturePreMigrationCluster reconstructs the old ArchetypeClusterInfo from the pre-migration sizes and loads the old segment at the OLD stride before the fresh one is allocated. CollectPreMigrationPositions walks its occupancy bitmaps for membership, which is what lets a PURE-SingleVersion archetype migrate at all — it has no chain heads to enumerate, so the existing rebuild would have found nothing. CopyPreMigrationSlot then replays the field map into each newly claimed slot, widening where the migration widened and copying verbatim where it did not. Three cases still refuse to open rather than guess, each with the reason in the message: a migration that also adds an index (the AllowMultiple element-id tail resizes and its old size is not recorded per archetype, so the old offsets cannot be reconstructed — apply the two changes separately), a breaking user-function migration, and an old cluster segment that fails to load. New fixture SchemaEvolutionStorageModeTests covers the axis whose absence let this hide for months: SchemaEvolutionTests has zero occurrences of StorageMode, so every one of its tests ran a Versioned component. Versioned needs no duplication now that those components are themselves cluster-backed, so the four new tests go after the mode with no second copy — add, widen, remove, and a mixed archetype where SingleVersion and Versioned recover by different routes in the same pass. Sizes are non-uniform and payloads distinctive on purpose: uniform sizes let a mis-addressed read land in range and report success. The widen test uses a negative short so a zero-extending widen cannot pass, and the remove test asserts the field AFTER the removed one, which moves from offset 12 to 4 — that is the assertion that proves the field map drove the copy rather than a blind memcpy. All four were mutation-verified: disabling the copy fails all of them plus the probe. The probe test that reported this bug was inverted from asserting the loud rejection to asserting the data, which is what actually proves the fix. It had kept passing after the copy landed, because a different rejection was firing. SeqlockCounterSlotReuseTests now cleans up in a finally. Anything thrown in its body used to skip the delete and leave a half-written database at that path; the next run's EnsureFileDeleted swallows every failure and waits only 500 ms for the NTFS pending-delete, so a file still mapped by the previous run's wreckage was silently not deleted and the run after that opened it and failed with a CRC mismatch indistinguishable from a torn-write bug in the page cache. That phantom cost real debugging time chasing a page-cache defect that did not exist. Full suite 4173 passed, 0 failed. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EHeNfnyttwHccbZ4wRxQQ7
…ta oracle that should have caught one of them C1: a migrating reopen on a disk-backed WAL destroyed every entity of the archetype. WalFilesPresentAtOpen is true whenever *.wal files exist and they survive a clean shutdown, so a migrating open took the crash-rebuild branch, re-derived the EntityMap from the freshly-allocated (empty) cluster, and continued past RebuildClusterFromChains — the only pass that re-places the entities. The crash branch is now gated on !HasMigratedSlot(state): a migration allocates a fresh EntityMap and a fresh cluster, so there is nothing stale to discard and nothing for the crash path to do. C2: MigrateWithFunction omitted OldCompSize, so the cluster pass reconstructed the pre-migration geometry with the NEW size for that component, computed a wrong ClusterStride, and loaded the old cluster at the wrong geometry without complaint — TryLoadChunkBasedSegment takes the stride from its caller and never verifies it. The SingleVersion components sitting next to the migrated one came back zeroed, no error. The old size is a property of the archetype's geometry, not of this component's migration strategy, which is the distinction the omission missed. C3: the guard covering this only knew about index ADDITION, so a removal or an AllowMultiple flip corrupted SV data the same way. Rather than widen the list of causes — which is never provably complete, and the old AllowMultiple count is not recorded per archetype anyway — CollectPreMigrationPositions now checks the invariant: a live cluster slot always carries a non-zero entity id, because spawn and the rebuild both write the tail. Reading zero at an occupied slot proves the geometry is wrong whatever the cause, and the open fails loudly instead of silently zeroing. This is also the check C2 lacked; two of the four criticals shared one missing assertion. C4: KeyBytes8.FromPointer copied FieldSize bytes into an 8-byte struct — 64 for a String64 indexed field — smashing the stack over the ChunkAccessor locals beside it and crashing the host. The destroy twin already carried both the fix and an explanatory comment (Transaction.ECS.cs:1393); the migration path never got it. fieldPtr goes straight to the tree at all four call sites. SchemaEvolutionDiskWalTests covers the axis that hid C1: TestBase defaults to InMemoryWalFileIO, which leaves the WAL directory empty, so the whole branch was unreachable from the test suite. It overrides CreateWalFileIO to a real WalFileIO and pairs the migrating case with a non-migrating control, which isolates the defect to the migration path rather than the backend. Mutation-verified: reverting the C1 gate fails the migrating test and leaves the control green. IndexTestHelpers.AssertIndexMatchesData walks live cluster occupancy, derives the key each entity actually holds, and checks the B+Tree against it. It exists because the suite's index coverage asserted the wrong thing: every mutation test checked the QUERY RESULT, and queries take the SoA scan, which reads component data and never consults the tree — so the index could be arbitrarily wrong while 4000 tests passed. Spawn and destroy had index-level assertions; update did not. Wired into the failing case and into a passing control, it root-causes #675's first blocker: not a stale index, but a UNIQUE index asked to hold two entities at one key. AllowMultiple fields and keys wider than 8 bytes are skipped and say so rather than passing silently. TargetedQuery_AfterMutation_ReturnsUpdatedResults is left RED deliberately. It is an accurate failure and the regression net for whichever way the duplicate-key policy goes — reject at write time, or make those fields AllowMultiple. That call is not mine to make. Suite 4174 passed, 1 failed (the above). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EHeNfnyttwHccbZ4wRxQQ7
…nd green the three doc gates M1: RebuildClusterFromChains re-derived EnabledBits for every non-Versioned slot and forced them enabled, so a slot the caller had explicitly disabled came back enabled after a migration. It now reads the pre-migration cluster's own bits when they are available, and defaults to enabled only when nothing better exists — the Transient case, which has no persisted bytes in either home. Unreachable until C1 was fixed: the crash branch swallowed this whole pass on precisely the migrating opens where an old cluster exists, which is why the review said the two ship together. The old-cluster ChunkAccessor moved out of CopyPreMigrationSlot to the caller in the same edit. It was constructed per entity on a path that already walks every entity — correct, but O(entities) accessor construction for no reason, and M1 needed the accessor one scope higher anyway. M2: DatabaseFormatRevision 4 -> 5. The comment carries the reasoning rather than just the number, because the danger is not that a v4 file fails to open — it is that it opens and answers wrongly. None of the three changes is self-describing: a v4 EntityMap record read as a cluster record finds ClusterChunkId where Location[0] lived, and a v4 index leaf read as a ClusterLocation resolves to a plausible but wrong cluster slot. Pre-alpha owes no migration path; it does not license silent corruption. M13: all three doc gates were failing and the PR would not have passed CI. Five failures, one root cause — IndexMaintainer.cs and PublishStagedFlatEntry are gone with #629. The four ViewSystem and transaction-overview citations now name Transaction.ReconcileClusterIndexAndViews, CM-03's scope drops the flat publish path, and the user-facing batched-index-maintenance page gets a historical note instead of a silent repoint: the batching it describes still applies, but the maintenance moved off the deleted maintainer type. check-doc-links, check-doc-drift and check-rule-scopes all pass. Suite 4175 passed, 1 failed — the B1 oracle, still red on purpose pending the duplicate-key policy decision. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EHeNfnyttwHccbZ4wRxQQ7
… the index in both directions C.0 — EngineAxes.cs. The option space is multiplicative (storage shape x durability x index kind x reopen kind is 216 cells before any workload axis) while example-based fixtures are additive, which is why line coverage stayed high on this branch while the matrix stayed mostly empty. Every defect found here was a single untested cell, not a missing test of a well-covered path. Pairwise covering keeps the case count near the number of axis VALUES rather than their product, on the empirical result that most defects are triggered by one parameter or an interaction of two. Generation is the standard greedy loop over uncovered t-tuples; greedy is not minimal, but it IS deterministic here, which matters more — a source returning a different set per run makes a failure impossible to reproduce. Every case is named after its cell, because "case 13 of 18" is not a repro. Generalises TestBase.BuildNoiseCasesL1/L2, which is this idea hard-coded for two axes. C.1 — IndexDataOracle.cs, strict and BIDIRECTIONAL. Data->index catches a shortfall: an entity whose current value is missing from the tree. Index->data catches an over-population and, more importantly, a MIS-POINTED leaf — one resolving to an unoccupied slot, or to a slot holding a different entity. That second case is exactly what a wrong-slot copy during a re-cluster produces, and presence-only checking cannot see it: the key IS present, it just names the wrong entity. It replaces three helpers the branch wrote three times, one of which was lenient enough to accept a leaf naming an unoccupied slot — three implementations of one invariant is three chances to write the lenient one, and the lenient one is the one that passes when the code is broken. The one-directional helper added two commits ago is superseded and deleted; its two call sites now use this. C.2 — SchemaEvolutionMatrixTests, driven by EngineAxes.PairwiseWhere. Seven cases, 624 ms, 200 entities each with per-entity distinctive payloads on every field, so entities span more than one cluster at any ClusterSize in [8,64] and ClaimSlot plus the EntityMap-rewrite loop are genuinely exercised. The acceptance criterion the review set is met, and the contrast is the point. Against the M6 mutant (oldPos.SlotIndex pinned to 0 in CopyPreMigrationSlot) the new fixture fails 7 of 7 while the four hand-written single-entity tests pass 4 of 4 — with one entity the only correct destination slot IS 0, so the placement half of the re-cluster was a tautology and the old tests could not have caught a wrong-slot copy. Mutant reverted. Axes deliberately not covered are stated in the fixture rather than silently skipped: the shape axis is restricted to the three compositions that have schema pairs, pure-Transient has no persisted bytes to migrate, and ReopenKind.None is excluded because a migration is a reopen. Widening the shape axis needs new component pairs, not new test logic. Suite 4182 passed, 1 failed — the B1 oracle, still red pending the duplicate-key policy call. All three doc gates green. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EHeNfnyttwHccbZ4wRxQQ7
…rwriting it B1 root cause, corrected twice on the way to this: not a stale index, and not "updates are never maintained". Updates ARE maintained. What fails is a UNIQUE index asked to hold two entities at one key. The underlying primitive is AddOrUpdate, so admitting the duplicate does not fail — it OVERWRITES the incumbent, which then exists in the data but is unreachable through the index. The two disagree permanently and nothing notices, because queries take the SoA scan and read component data rather than the tree. Three options existed and only one is honest. Silently overwriting corrupts. Auto-promoting the field to AllowMultiple would change a declared constraint at run time and cost every unique index 4 bytes per entity plus a buffer indirection. So the engine now enforces what the attribute already promises: IndexAttribute documents AllowMultiple=false (the default) as "one entity per key", and a field whose values genuinely repeat has to say so. Guarded at all three write sites, and the third is the one that mattered. The commit-path Add and Move sites were the obvious ones; guarding only those left the collision fully reachable, because a SingleVersion component has no revision chain and its index maintenance happens at the TICK-FENCE SHADOW DRAIN instead. That is the path the failing test actually took. Blast radius across the whole suite: one test, the one that exposed the defect. The fear that fixtures broadly rely on duplicates in unique indexes was unfounded. ClIdxHealth.Current was declared unique and holds a health total — two units at 100 HP is the normal case, not a conflict — so the declaration was simply wrong and now says AllowMultiple. That is the fix surfacing a misuse, which is the point of enforcing a constraint rather than tolerating it. Cost is one extra optimistic descent per unique-index write. Not free on a commit path, and removable later by surfacing the InsertArguments.Added flag AddOrUpdateCore already computes — the check sits at the call sites rather than inside Add because that method's body is contractually throw-free. Suite 4183 passed, 0 failed — green for the first time on this branch. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EHeNfnyttwHccbZ4wRxQQ7
Deletes the XML block documenting RejectUnrecoverableClusterMigration, which was removed in 90e06baa when the SingleVersion migration replaced the rejection. It had come to rest on top of CollectPreMigrationPositions, leaving that method carrying two summary tags and a description of behaviour that no longer exists. Adds the width guard at the view-delta insert site in Transaction.ECS.cs. This is the same construct as C4 — KeyBytes8 is 8 bytes and FromPointer is a raw CopyBlockUnaligned of FieldSize, which is 64 for an indexed String64 field — so it smashes the stack over whatever locals follow. I ranked it as follow-up hardening earlier and that was wrong: its twin at the update site already carried the guard, and a guarded twin is evidence the condition is reachable rather than theoretical. Skipping the delta is the honest behaviour, since truncating the key to its first eight bytes would emit a view notification naming the wrong value. Suite 4183 passed, 0 failed. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EHeNfnyttwHccbZ4wRxQQ7
…ng answers switching it on exposed Path A (ScanPerArchetypeBTreeSelective) has been unreachable since #629 pinned SelectPrimaryStream and SelectFullScanStream to -1, so every indexed query has been an O(N) cluster scan with zone maps as the only pruning. The issue named two blockers. One was already fixed; the other was not what the issue said; and reading the path before switching it on found four more, two of which the un-pinning itself would have introduced. The endpoints were never the problem. [float.MinValue bits, float.MaxValue bits] round-trips exactly and a float field's index is a BTree<float> with typed comparisons. What was wrong is the INTERSECTION arithmetic: SelectPrimaryStream combined two predicates on one field with signed long >/< over raw IEEE bits, so >= -20f && <= 20f widened to [float.MinValue, 20f] — the reported 71 rows where 41 are correct. New Querying/internals/KeyRange.cs now owns bound computation, comparison and intersection in the encoded domain. It replaces two copies, in PlanBuilder and EcsQuery, which had already drifted — only one handled Bool. That is harmless while one of them is unreachable and a wrong answer the moment both run, which is exactly what un-pinning does. ScanPerArchetypeBTreeSelective had no MVCC born/died gate. Path B grew one for #674; Path A emitted straight from the occupancy word. Un-pinning would have re-opened on Path A the phantom read #629 had just closed on Path B, and chosen between the two by an ESTIMATE. Same IsVisibleAtSnapshot call at both emit sites now. Bool and String64 have no case in CollectClusterLocationsFromBTree or ArchetypeSortedStream.Create, and a ULong index is an L64BTree<long>, so its keys are stored reinterpreted as signed and the full range [0, ulong.MaxValue] encodes to [0, -1], which is empty. The planner would have proposed all three and each would have answered silently empty. KeyRange.IsStreamable rejects them — the SoA scan is correct for any key type — and both switches now throw on an unhandled type so the guard and the switches cannot drift apart quietly. ULong's storage encoding is a separate fix, filed as #676. ExecuteOrderedViaSortFallback typed its stream from plan.PrimaryKeyType but bounded it from evaluators[0].KeyType. Those are two different fields once selection is live, and while it was pinned PrimaryKeyType was default (Bool), which no typed tree matches, so the stream came back empty and every entity silently sorted by EntityKey instead of by the ordered field. Both now come from the OrderBy field. Two zone-map defects, both pre-existing and unrelated to #675. DoubleToOrderedLong was monotone under UNSIGNED comparison while both consumers compare SIGNED, so every positive double encoded negative and sorted below every negative one — pruning skipped whole clusters of positive doubles, and the fixture that found it lost 93 of 143 matching rows. The float twin escapes this only because a 32-bit result widens into the positive half of a long. FloatToOrderedLong also encoded -0.0f one below +0.0f though the two are numerically equal, so a cluster holding only -0.0f failed to overlap the bounds of field == 0.0f. They are fixed here rather than filed because the new fixture fails without them, and the alternative — excluding double from the matrix — is precisely the skipped cell that counts as coverage. QueryPathEquivalenceTests, 27 cases, runs key type x operator x threshold sign x two-sided window through BOTH paths and against a set computed from the spawn function. Differential and absolute, because a pure differential passes when both paths are wrong the same way. The path is FORCED via the new QueryPathProbe rather than provoked by a selective predicate: the choice is made from an estimate, so a hopeful test degrades into a second Path B test the day a statistic moves, still green. Every Path A case additionally asserts a selective scan actually ran, so the fixture going quiet is itself a failure. KeyRangeTests, 57 cases, checks the encodings directly against IComparable.CompareTo on each value's own CLR type — an oracle that shares no code with what it audits. IndexDataOracle read the data side with a Buffer.MemoryCopy into a zeroed long, which ZERO-extends. Every fixture that existed used non-negative keys; the first one with negative keys reported all 240 entities as mis-pointed, because the data side read int -120 as 4294967176 while the tree read -120. It now reads through the tree's own key type. Mutation-verified, all five caught: signed Math.Max/Min in KeyRange.Intersect (3 failures), the old DoubleToOrderedLong (2), dropping the -0.0f normalisation (1), bypassing Path A's visibility gate (1), and making the forced Path A silently fall back to Path B (16). The performance benefit is NOT measured, and that is worth stating plainly. Path A is planner-selected for a point query on an indexed field, confirmed by the probe counters, so the un-pinning demonstrably took effect. But at the largest entity count the harness allows (40 000, above which the test-mode page cache hits back-pressure) both paths measure within noise at ~150 us/query and the time does not rise with N at all — a fixed per-query cost that swamps the scan entirely at these sizes, filed as #677. One caveat belongs with the O(N) -> selective claim too: Path A is not O(log n + k). It range-scans into a per-cluster bitmap and then walks every active cluster to find the marked ones, so a point query is O(N/64). That is 64x better than Path B and not the same thing as a tree lookup. Suite 4267 passed, 0 failed. All three doc gates green. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EHeNfnyttwHccbZ4wRxQQ7
…ps probing the EntityMap per match H1 from the pre-merge review, and the last thing standing between this branch and the speedup it claims. The #674 phantom-read gate is correct and not removable — it IS the fix — but it does an EntityMap point-read for EVERY matched entity, measured at 166-241 ns each against ~27 ns for the entire rest of the scan. The cost is not a data miss; the map is L2/L3-resident. It is the fixed per-lookup machinery: XxHash32 full avalanche so consecutive dense keys land in unrelated buckets, three chunk-address resolutions per TryGet, and a 32-slot accessor window whose miss path costs two or three Interlocked ops plus a clock-sweep bump. The gate stays exactly as it is. What goes away is running it per match. Two arrays keyed by clusterChunkId on ArchetypeClusterState — ClusterMaxBornTsn and the ClusterAnyDied bitmap — answer "was every entity in this cluster committed before this snapshot, and has none died?" from one sequential read. A cluster that passes skips the probe for all 64 slots; one that fails keeps today's per-entity check verbatim, so correctness is unchanged. In steady state almost every cluster was committed before any live reader's snapshot, so the probe count collapses to near zero. Applied to BOTH scan paths, because #675 gave Path A the same probe and applies it to a set the tree has already narrowed — where it is a larger share of the remaining work than on a full scan. Conservative in one direction only, and that is the whole design rather than an implementation detail. The summary may say PROBE when probing was unnecessary (slower, still correct) and must never say CLEAN when an entity could be invisible. So every value starts at the pessimistic end (VisibilityUnknown), and an absent or too-short array reads as "this reader cannot tell" rather than "nothing died" — the first version of IsClusterFullyVisibleAt returned clean when the died bitmap was out of range, which is exactly a phantom. The ClusterAnyDied bit is never cleared: proving no tombstone remains would need the full re-scan the summary exists to avoid. Five sites associate an entity with a cluster and all five fold into the summary — spawn commit, WAL replay, and the two reopen rebuilds, plus SPATIAL CLUSTER MIGRATION. That last one is the one that is easy to miss and the one that matters most: it moves an entity between clusters of the same archetype WITHOUT changing its BornTSN, so a destination cluster that was clean silently acquires an entity younger than a live reader's snapshot. It is folded by capturing the record's own TSNs inside ClusterLocationUpdater.Update, under the same bucket write lock that patches the location, and applied only when TryUpdateInPlace actually succeeded. That required dropping readonly from the struct, which is noted where it is declared. Publication ordering is stated where it is relied on rather than assumed. The growth path publishes the resized ClusterAnyDied before release-storing ClusterMaxBornTsn, and the reader takes them as acquire loads in that same order — reading them the other way round could pair a new maxBorn with a stale short died array, and a missing died bit reads as clean. The reader also consults the summary only AFTER the acquire-ordered read of the cluster's occupancy word: the summary is published by the same commit that sets the occupancy bit, so a reader that cannot see the bit cannot be misled by a summary that predates it. Same hazard as M3/M4/M5 in the review, handled the same way. Measured, controlled A/B on one machine in one session, median of 3 runs each, 20 000 entities, Release: query.pureV.indexed.equality 462 us -> 167.2 us (2.8x) query.pureV.indexed.range 1633 us -> 484.9 us (3.4x) query.mixed.equality.CONTROL 414 us -> 123.4 us (3.4x) The H1-OFF column independently reproduces the review's own 453.3 / 1571.5 us, which is what licenses comparing the two measurement sessions. Against the flat baseline the headline is now 4.3x on equality and 6.0x on range — the design doc's Results table is restored rather than annotated, and H2 closes with it. Equality lands AT the gate-ablated ceiling the review measured (172.1 us), meaning the probe is gone from the common case rather than merely reduced; range sits about 19% above its ceiling, which is the summary read itself plus the clusters that legitimately fail it. Mutation-verified: forcing IsClusterFullyVisibleAt to return true fails NeitherPathEmitsAPhantom on BOTH Selective and FullScan. That fixture came from #675 and was written for a different reason entirely — it turned out to be the exact guard this change needed, which is the argument for writing the phantom test when a path is enabled rather than when someone finally suspects a phantom. One limit, stated rather than hidden: the summary is maintained at five sites and validated at none, so a sixth born-site added later would produce a phantom no test catches. The C3 lesson from this review says the answer is an invariant check, not a longer list — RunStorageIntegrityCheck() should recompute both arrays from the EntityMap and compare. Not done here; it is now the first item of the post-merge sprint. Suite 4268 passed, 0 failed. All three doc gates green. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EHeNfnyttwHccbZ4wRxQQ7
…should have in tests A unique [Index] promises "one entity per key" with no archetype qualifier. It is enforced per leaf archetype. Two entities in different archetypes of the same tree can hold the same key, and a point lookup then returns both — reproduced as A) same archetype rejected, B) two archetypes ACCEPTED, C) query returns 2. This is not the fix. The fix needs a subtree-scoped persisted structure with WAL participation, crash recovery, rebuild and checkpoint interaction — a feature, tracked as #678 with the design in claude/design/Indexing/index-scope-and-uniqueness.md. What this commit does is stop the branch shipping a promise it does not keep, which is a merge-blocking difference from shipping a known gap. Where it came from, because it changes how the gap should be read. Before #629 there were two index homes and therefore two uniqueness scopes: a flat-stored component was indexed at ComponentTable level — one ComponentTable per component NAME — so unique meant every archetype using it; a cluster-stored one was already per archetype. Removing the flat home made the per-archetype scope universal. For a clustered component the gap predates this branch; for a flat-stored one this branch narrowed a guarantee that was being kept. The target scope is the DECLARING ARCHETYPE'S SUBTREE, which is a decision rather than a restoration — narrower than the old flat behaviour, wider than today's, and the only scope the schema can already state, since queries are polymorphic over a subtree. doc/feature-set/.../unique-secondary-index.md now says so in both places a reader would rely on it: the mechanics section gets the scope note where the duplicate check is described, and the guarantees list splits the promise into the within-one-archetype case that holds and the across-archetypes case that does not. Both point at #678. A user reading the previous text was told a duplicate always throws. UniqueIndexScopeTests is the acceptance suite for #678, written now while the reproduction was in hand rather than later with the fix. One control that runs today — same archetype, duplicate key, throws — because if that ever goes red the constraint is not enforced at all, which is a different bug. Four [Ignore]d tests for the scope it should have: ancestor/descendant, two siblings, separate transactions (a fix that only de-duplicates within one commit batch passes the others and fails this one), and the reader-side consequence that a point lookup on a unique key must return exactly one entity. Each of the four was verified to FAIL today before being marked [Ignore]d — three on the missing UniqueConstraintViolationException, the fourth on getting 2 rows where 1 is specified. An acceptance test that already passes documents nothing, and the check costs one build. Left deliberately undone: registration-time validation, which rejects a unique [Index] on a component declared by 2+ archetypes. It is cheap — the declaring set is always an antichain, so it reduces to counting declarers — but it rejects schemas that load today, and a schema-breaking change does not belong in a merge whose risk budget is already spent. It is step 1 of #678 and the first item of the post-merge sprint. Suite 4268 passed, 0 failed. All three doc gates green. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EHeNfnyttwHccbZ4wRxQQ7
This was referenced Aug 6, 2026
Closed
This was referenced Aug 6, 2026
Merged
Closed
6 tasks
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Retires the per-
ComponentTablesecondary index. Every archetype is now cluster-backed and every secondary index lives in exactly one place — the archetype — so no consumer branches on storage shape to find an index.src/is a net −133 lines despite the scope, because removing the second home deleted more than the consolidation added.What it delivers
VersioneddataMeasurement
Controlled A/B, one machine, one session, median of 3 runs each, 20 000 entities, Release:
The number moved twice during this work and both moves are recorded rather than smoothed over. The original table was measured one commit before the #674 phantom-read gate landed, so it claimed a speedup the branch had already stopped delivering — the pre-merge review caught that and restated it as 1.6–1.9×. H1 then removed the gate's per-match EntityMap probe (per-cluster visibility summary, correctness unchanged), which restored it. The intermediate 1.6–1.9× column is still in the design doc.
Review
The branch was reviewed against
claude/overview/,claude/design/,claude/rules/andclaude/adr/before this PR: 4 criticals, 2 highs, 31 mediums, every critical with a reproduced failure or a controlled measurement. All are fixed or sequenced. The review, its corrections, and the post-merge ordering are indesign/Indexing/index-ownership-consolidation-review.md.Two of the four criticals shared one missing assertion, and C3 was fixed by validating an invariant rather than enumerating causes — a live cluster slot always carries a non-zero entity id, so reading zero at an occupied slot proves the geometry being read through is wrong, whatever the cause. Had that existed, C2 would have been a loud error instead of silent data loss.
Suite: 4 268 passed, 0 failed (from 4 183 at the start of the review). All three doc gates green.
Notable finds, because they generalise
ZoneMapArray.DoubleToOrderedLongwas monotone under unsigned comparison while both consumers compare signed, so every positive double sorted below every negative one. Pre-existing, unrelated to Index ownership consolidation — retire the per-ComponentTable secondary index #629, found only because the new equivalence fixture refused to skip thedoublecell.[Ignore]d.What is deliberately not in this PR
BTree.Insert.csuntouched; theBTree.csdiff is directory identity only).Closes
Closes #629
Closes #655
Closes #656
Closes #657
Closes #658
Closes #659
Closes #660
Closes #661
Closes #662
Closes #663
Closes #664
Closes #665
Closes #666
Closes #670
Closes #671
Closes #673
Closes #675
#674 stays open — only its phantom half is fixed here; the value half (the SoA scan evaluates the committed HEAD, not the snapshot-visible version) is the top of the post-merge backlog and should be settled before the layout is locked in.
Companion
Docs are a separate repo:
log2n-io/typhon-claudebranchfeature-629— 15 commits.🤖 Generated with Claude Code
https://claude.ai/code/session_01EHeNfnyttwHccbZ4wRxQQ7