Skip to content

#816 Cluster SoA span APIs strided by the field extent instead of sizeof(T) - #818

Merged
nockawa merged 1 commit into
mainfrom
bug/816
Aug 15, 2026
Merged

nockawa merged 1 commit into
mainfrom
bug/816

Conversation

@nockawa

@nockawa nockawa commented Aug 15, 2026

Copy link
Copy Markdown
Collaborator

Fixes #816.

The bug

A component column was laid out with lastField.Offset + lastField.Size, but every accessor over it hands out a Span<T> or a ref T, and those step by sizeof(T). The two disagree by whatever trailing padding the compiler adds to keep the struct's alignment inside an array — struct { long A; int B; } was stored at 12 bytes per slot and read at 16.

Slot 0 aliased correctly and everything after it did not: reads ran off the end of the column into the next component's, and a whole-struct write stamped the neighbouring slot. Nothing detected it — the bytes were structurally valid, the CRC covered what was written, and the flat per-entity view kept reading correctly for interior slots, so the two views of the same memory disagreed with no error anywhere.

Three premises in the issue that did not hold

  1. The trigger is not [StructLayout(Size = …)]. Ordinary alignment padding does it. struct { EntityLink Owner; int Weight; } — Tests.ItemData, verbatim — is a 16-byte type with a 12-byte extent.
  2. Not "only Vitals in the repo". 14 components were already in that state, including the engine's own ArchetypeR1 (112/108) and SchemaHistoryR1 (176/172).
  3. EntityRef was not a correct counter-example. It addresses with ComponentSize(slot) but hands back a ref T that is sizeof(T) wide, so a whole-struct write overruns a too-short slot. The flat path was only correct for reads of interior slots.

What changed

Area Change
Fix DBComponentDefinition.Build takes the CLR size of the backing struct (rule SCHEMA-06). A definition with no backing type stays metadata-only; one that names a struct must fit inside it.
Guard ClusterRef.CheckStride<T> on all five accessors, inline-guarded so it folds away when strict mode is off.
TYPHON010 Warns when a component stores more than a 4-byte multiple of what it would measure at Pack = 4.
TYPHON011 Errors when a component's managed and marshalled layouts differ (bool / char).
Generator No longer uses Marshal.OffsetOf — measures each field against a stack probe with Unsafe.ByteOffset, so generated specs carry managed offsets.
Reopen gate Refuses a database whose component gained padding, instead of silently reading it at the new stride.
Callers 24 components swept to Pack = 4; 2 AntHill demo components left alone (already a 4-byte multiple).

No on-disk format change. Every component that would have grown carries Pack = 4, which removes the 8-byte rounding without moving a field offset — verified field by field for both system structs — so the persisted stride is unchanged and BK_SystemSchemaRevision stays at 2 (SCHEMA-05).

Why the baseline is Pack = 4 and not the last field

Tail padding is a fact about field order, not about waste. { long; int } and { int; long } are both 16 bytes carrying 12 bytes of payload and both pack to 12 — measuring the distance to the end of the last field reports only the first.

Evidence

  • Mutation proof. Reverting the one-line fix kills 5 of 6 new tests, with Cluster SoA span APIs stride by sizeof(T) instead of the layout's component size — silent cross-column corruption #816's exact symptoms (Expected: 1000001 But was: 0 on neighbour-slot corruption).
  • SCHEMA-06 carries a [RuleMutant]. It re-addresses a real column at the field extent and requires the verifier's own per-slot assertion to fail. Pointing it at the correct stride makes it report "the verifier ACCEPTED a scenario that violates the rule" — so it can reject.
  • The guard actually runs. The suite has Checks:Enabled=true, so CheckStride executed across all 5,453 tests without firing.
  • Two independent reviewers verified the Pack = 4 offset-neutrality with their own runtime probes.

The same bug, found twice more

SchemaCatalogReader.cs:504 already carried a remark explaining that ArchetypeR1 "is 108 bytes on disk and 112 in memory … so a direct MemoryMarshal.Read<T> reads four bytes it does not own". Someone hit this exact divergence in the integrity scanner, wrote a tolerant reader, and moved on. And ArchetypeR1_SizeOf_Compact asserted sizeof == 112 — documenting the waste as correct.

Verification

Gate Result
Solution build 0 errors, 0 TYPHON010/011
Typhon.Engine.Tests 5,453 / 0 — two consecutive clean runs
Typhon.Workbench.Tests 677 / 0
Typhon.Analyzers.Tests 29 / 0
pre-push.sh --policy 7 / 7

Docs land in Log2n-io/Typhon-Claude on the matching bug/816 branch.

Known follow-up

The reflection schema path (CreateFromAccessor(Type), AssemblySchemaLoader) still reads Marshal.OffsetOf; it holds only a Type and cannot measure the managed layout. TYPHON011 covers anything compiled against the analyzer, and Build now refuses a definition whose fields overrun its struct, but an assembly loaded at runtime that was never compiled with the analyzer is outside both nets.

…eof(T)

A component column was laid out with `lastField.Offset + lastField.Size`, but every accessor over it hands out a `Span<T>` or a `ref T`, and those step by `sizeof(T)`. The two disagree by whatever trailing padding the compiler adds to keep the struct's alignment inside an array, so `struct { long A; int B; }` was stored at 12 bytes per slot and read at 16. Slot 0 aliased correctly and everything after it did not: reads ran off the end of the column into the next component's, and a whole-struct write stamped the neighbouring slot. Nothing detected it — the bytes were structurally valid and the flat per-entity view kept reading correctly for interior slots, so the two views of the same memory disagreed with no error anywhere.

`DBComponentDefinition.Build` now takes the CLR size of the backing struct, so the stride a column is laid out at is the stride its accessors address it by (rule SCHEMA-06). A definition with no backing type stays metadata-only and keeps the field extent — it never backs a column — while one that names a struct must fit inside it, which is refused loudly rather than repaired silently.

The trigger was never the explicit `[StructLayout(Size = …)]` the issue blamed. Ordinary alignment padding does it, and 14 components in this repository were already in that state including the engine's own `ArchetypeR1` and `SchemaHistoryR1`. Those now carry `Pack = 4`, which removes the 8-byte rounding without moving a single field offset — verified field by field — so the persisted stride is unchanged and no `BK_SystemSchemaRevision` bump is due.

TYPHON010 reports a component storing more than a 4-byte multiple of what it would measure at `Pack = 4`. The baseline is the packed size rather than the end of the last field, because tail padding is a fact about field ORDER: `{ long; int }` and `{ int; long }` are both 16 bytes carrying 12 bytes of payload and both pack to 12, and only one has its padding at the end.

TYPHON011 is the same class on the other axis. Field offsets came from `Marshal.OffsetOf`, which describes the marshalled layout, while every accessor reads the managed one; they agree for ordinary blittable primitives and part company for `bool` and `char`. The generator no longer uses `Marshal.OffsetOf` at all — it measures each field against a stack probe with `Unsafe.ByteOffset`, so a generated spec carries managed offsets — and TYPHON011 covers the reflection fallback, which holds only a `Type` and cannot do the same. It stays silent when the layouts genuinely agree, including under `CharSet.Unicode` and an explicit `[MarshalAs]`.

Reopening a database whose component gained padding is now refused. `SchemaDiff` compares names, types, offsets and sizes; the per-instance stride is none of those, so a padding-only change reported Identical, skipped every migration branch, and the cluster segment was reopened at the new geometry with every row after the first read at the wrong offset.

SCHEMA-06 carries a verifier and a mutant: the mutant re-addresses a real column at the field extent and requires the verifier's own per-slot assertion to fail, and was itself checked by pointing it at the correct stride to confirm it can reject.
@nockawa
nockawa merged commit 683001d into main Aug 15, 2026
17 checks passed
@nockawa
nockawa deleted the bug/816 branch August 15, 2026 20:32
yhcedpn added a commit to yhcedpn/Typhon that referenced this pull request Aug 16, 2026
…9 豁免记录理由)

- Behavior [StructLayout(Sequential, Pack = 4)]:sizeof 16→12,每实体省 4 字节
  尾部 padding(字段偏移不变,SCHEMA-06 兼容;DB 启动重建无 reopen 包袱)
- MovementSystem 写 Hull:WriteSpatial V1 仅支持 AABB2F(AABB3F 抛异常),
  fence 空间维护按脏位批次重读簇字节,GetSpan 写语义等价 → pragma 豁免并注释
- ADR-0009 已记录跟进(docs/ 本地排除不入库)
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.

Cluster SoA span APIs stride by sizeof(T) instead of the layout's component size — silent cross-column corruption

1 participant