Status: normative. This document is the contract. The Rust side and the Java side are implemented independently against it, and a runtime manifest check proves they agree. If this document and the code disagree, the code is wrong.
This is the most misunderstood property of the design, so it is stated first.
extern "C" in Rust and Linker.nativeLinker() in Java do not involve the C
language. They name a machine calling convention:
| Thing | What it actually is | What it is not |
|---|---|---|
extern "C" (Rust) |
"use this target's standard C-family calling convention" — on this box, the System V AMD64 psABI; on ARM64, AAPCS64 | C source, a C compiler, a C runtime |
#[repr(C)] (Rust) |
"use this target's standard aggregate layout rule" (field order, padding, alignment) | a C struct declaration |
Linker.nativeLinker() (Java) |
a JVM-internal implementation of that same psABI (SysVx64Linker) |
a C bridge, a JNI shim |
Consequences, all load-bearing:
- No
.hheader exists anywhere in this project, and none will. - No C toolchain is required to build or consume this.
cargoandjavacare the entire toolchain. - No
cbindgen. Its output is a C header; we have no consumer for one. - No
jextract. jextract's only input is a C header. With no header there is nothing to extract. This is not "we chose not to use the generated bindings" (though that would also be true) — the tool has no input. - No JNI, and no JNI-shaped use of Panama (see §6).
A C header is a text file that claims what the compiled artifact looks like. It can drift from the artifact silently — the classic ABI break. We do the opposite: the compiled artifact describes itself at runtime, and Java verifies that description against its own compiled-in expectations before the first real call.
Rust cdylib Java
─────────── ────
lgj_abi_manifest() ──── returns ptr ───▶ read LgjAbiManifest
(a static, versioned │
#[repr(C)] struct ▼
describing sizeof/ cross-check EVERY
alignof of every size & align against
ABI type, endianness, this Java build's own
the compiled SIMD MemoryLayout constants
backend) │
▼
mismatch ⇒ hard fail at load
(never silent corruption)
The manifest is strictly stronger than a header: a header describes what someone intended to compile; the manifest is emitted by the compiled artifact, so it cannot disagree with itself.
The ABI is a machine membrane. It is not the product. The product is the Java
semantic API (see architecture.md). Therefore:
- It is small — currently 31 symbols (minor 13's one addition — a plan folded to one scalar with no mask — is argued in §21; 30 at minor 12, whose one addition — the grouped sum that never builds a selection — is argued in §20; 29 at minor 11, whose three additions are argued in §19, and the same section argues the SEVEN capabilities it deliberately did NOT spend a symbol on; 26 at minor 10, whose one addition — the columnar constructor — is argued in §18; 25 at minor 9, whose one addition is argued in §11: a reduction Java was performing on the wrong side of the membrane, moved to where the data is; 24 at minor 8, which adds manifest FIELDS and no symbol; the "14" this line carried at minor 1 was arithmetic drift — the §7 list it referred to already enumerated 15). Growth is a design smell to be argued for, not a default; minor 2's three additions are argued in §11, minor 3's one addition in §12, minor 4's two additions in §13.
- It is bulk-only. Every call must be capable of doing work proportional to
n_rows(see §6 — the anti-JNI rule). - It speaks resource, lane, view, mask, operation, descriptor, status,
epoch — not
Node, notEdge, notPerson. - It is versioned and refuses to operate across a version mismatch.
- It never allocates on the Java side's behalf without a paired release, and never hands out a pointer whose lifetime it cannot state.
LGJ_ABI_MAJOR = 0 // incompatible change ⇒ bump; Java refuses to load
LGJ_ABI_MINOR = 14 // additive change ⇒ bump; older Java may still load
LGJ_MAGIC = 0x4C_47_4A_5F_41_42_49_00 // "LGJ_ABI\0" big-endian-read
Rule: Java requires major to match exactly and minor to be >= what it
was compiled against. A major mismatch is a hard failure, not a warning.
The magic doubles as an endianness probe: read as a u64 little-endian it yields
a known constant; anything else means the library was built for a different byte
order and every subsequent read would be garbage.
§2's additive-minor promise ("an older Java build against a newer .so always
loads") has a second direction the promise itself does not cover: a newer Java
against an older .so. That case is governed by Abi.requireMinor(N), whose
contract is to fail before the feature's downcall is attempted, naming the
minor.
The load gate itself requires only the manifest's BASE PREFIX — everything
through build_profile, 104 bytes, the field set minor 1 defined
(Layouts.MANIFEST_BASE_BYTES). Requiring the full layout this Java build knows
about would make every future manifest field a hard incompatibility with every
older artifact, in flat contradiction of the promise above. It was written that
way until minor 8 grew the struct and the contradiction became reachable;
measured, restoring the full-layout gate makes all four historical libraries
fail to load outright. Fields past the base prefix are read only when the
library's own size_of_manifest covers them AND its minor is high enough — both
conditions, because a manifest that claims a minor it is too short to carry is a
broken artifact and reading it would produce plausible garbage.
That guard was defeated by eager class initialization until 2026-08-25.
Every downcall handle was resolved in Downcalls.<clinit>, so a single absent
symbol broke the whole class and the guard never ran. Measured with the Java of
that day against real libraries built from this repo's own history:
| library | SmokeTest (uses nothing newer than minor 1) died on |
|---|---|
| minor 1 | lgj_rowstore_open — a minor-2 symbol |
| minor 2 | lgj_rowstore_open_with_edges — minor 3 |
| minor 3 | lgj_mask_andnot — minor 4 |
| minor 4 | lgj_reduce_facet_sum — minor 5 |
Note the severity: against the minor-1 library, minor-1 operations could not run either.
The fix is one lazy holder class per minor (Minor2/Minor3/Minor4/Minor5
in Downcalls), initialised on first access. The minor-1 base surface stays
eager deliberately — a library missing any of it is not an older library, it is
a wrong one, and that failure should be immediate and total.
OldAbiCompatTest is the falsifier. It takes
-Dlgj.oldlibrary=… and checks each minor in whichever direction the loaded
library calls for: available ⇒ the feature must actually work; absent ⇒
AbiMismatchException naming that minor, never a bare missing-symbol failure
and never a failure of some other minor's feature. Both directions are
required — a gate that rejected everything would satisfy a rejection-only test.
- Minor 12 (2026-09-22) —
lgj_plan_group_sum_i32(§20): the fused plan run STRAIGHT INTO a grouped-sum terminal. Every reduction before this minor paid for a selection first —lgj_plan_evalinto a mask, then algj_reduce_*over it — and aGROUP BYpaid it once per group (thebricksconsumer measured 32 crossings for 16). One symbol lowers the plan andGROUP BY key SUM(val)as ONEmask_risc::Programwhose accumulator is tile-local scratch and whose only answer-sized state is the caller'si64per group; a second table's key may be read THROUGH this table's key lane (via_res/via_lane) with no partner-side mask. One crossing for any number of groups and any number of rows. No new status; no manifest growth; a minor-11 Java loads and sees none of it. - Minor 11 (2026-09-14) — the masking-op completion (§19): the ndarray
masking facade finished growing, and this minor consumes what it grew.
Three symbols and seven op-codes for fifteen capabilities, which is the
whole argument:
lgj_mask_ternlog(§19.1) makes every 3-input Boolean function of three masks an IMMEDIATE rather than a symbol, so XOR, NOT and MAJ3 arrive without one each;lgj_op_ternary_match(§19.2) is the first bitwise-over-payload predicate this ABI has carried, and the only new capability whose parameter (24 bytes) genuinely does not fit an op-code;lgj_reduce_i32(§19.3) is the PARAMETERISED reduction §15 mandated in advance rather than the second and third reduce symbols §1 warns about. The comparison family (ne_u32,eq/ne/lt/le/ge_i32) and theu32TCAM cost no symbol at all —LgjOpDesc.opis the generalisation vehicle this ABI already carries for predicates. No new status; no manifest growth; a minor-10 Java loads and sees none of it. - Minor 10 (2026-08-27) —
lgj_rowstore_open_columnar(§18): the facet-major columnar store. A layout is a SCHEMA over the same 512 bytes per row (R11), so it is a CONSTRUCTOR, not a resource kind: every mask, hop and count op takes the handle unchanged and answers identically (pinned: the 10 → 19 → 29 hop on both layouts, byte-identical facet-match buffers). The lane table grows 33 → 97 (payload lo64 + hi32 lanes join classid), so a consumer reads EVERY field through a served descriptor — which is what lets Java stay layout-blind. New status-18(UNSUPPORTED_LAYOUT) for the register-sweep family on a facet-major store. Measured through this ABI at 65 536 rows, all 32 facets: hop 3.3–4.8× over AoS at every frontier arm. - Minor 9 (2026-08-27) —
lgj_rowstore_facet_match_count(§11): the total(row, facet)slot count for a classid, computed natively. The operator's placement rule made explicit as ABI: Java hands the question through Panama and receives ONE number; the decomposition (32 facet predicates, popcount, sum) never crosses. Exists because the reduction was found executing in Java twice — first as a segment loop, then as 32 composed mask counts summed Java-side — each lawful-looking, each still Java holding a moving part. No new status. - Minor 2 (2026-08-17) — the SoA row store (§11).
- Minor 3 (2026-08-18) — the edge-bearing row store (§12).
- Minor 4 (2026-08-18, D-LGJ-W8) —
lgj_mask_andnot(mask complement) andlgj_hop(one-hop graph traversal, gated by thelance-graph-contractClassView/FieldMaskLAW — §13). - Minor 8 (2026-08-25) — the manifest carries the register groupings as
DATA (§17):
carving_count+carvings. No new symbol and no new status; it is the first growth of the manifest STRUCT, which is why it is also the change that made Java's load gate require only the base 104-byte prefix rather than the full layout. - Minor 7 (2026-08-25) —
lgj_row_layout_probe(§16): the whole-row alignment answer, all 32 facets in one crossing. No new status. - Minor 6 (2026-08-25) —
lgj_reduce_facet_sum_resolved(§15): the same sweep, but under the grouping the POPULATION resolves to viaClassView::cascade_shape, rather than one the caller asserts. One new status:UNRESOLVED_CARVING(-17). - Minor 5 (2026-08-25) —
lgj_reduce_facet_sum(§14): the mask path's missing EXECUTION half. The build half (lgj_op_eq_classid) has existed since minor 2; nothing could consume a mask against the 12-byte facet register until now. Two new statuses:UNSUPPORTED_CARVING(-15) andSUM_OVERFLOW(-16). - Minor 13 (2026-11-12) —
lgj_plan_scalar(§21): the fused plan folded straight into a count or a sum for a caller that asked for no mask.lgj_plan_evalis unchanged. No new status, no manifest growth. - Minor 14 (2026-11-12) — no new symbol. A mask is accepted only against the resource it was created over, in every export that takes one (§3.1). Nine mask arguments that checked only the row count now check the parent. This narrows accepted input; §3.1 states the compatibility effect.
Every function returns i32. 0 is success; all failures are negative. There
are no error strings across the membrane and no errno dependence.
| Value | Name | Meaning |
|---|---|---|
0 |
OK |
success |
-1 |
NULL_ARGUMENT |
a required out-pointer was null |
-2 |
INVALID_HANDLE |
handle malformed, closed, or generation-stale |
-3 |
WRONG_RESOURCE_KIND |
e.g. a mask handle passed where a pattern was required |
-4 |
INVALID_LANE |
lane_id out of range for this resource |
-5 |
LANE_KIND_MISMATCH |
op's element type ≠ lane's element type |
-6 |
MASK_LENGTH_MISMATCH |
the mask does not belong with the resource or masks it is used with: another parent, or another row count (§3.1) |
-7 |
PARENT_CLOSED |
child (mask) outlived its parent resource |
-8 |
VERSION_MISMATCH |
caller's ABI version incompatible |
-9 |
LENGTH_OVERFLOW |
requested size overflows usize/allocation limit |
-10 |
UNKNOWN_OPCODE |
plan contained an opcode this build does not implement |
-11 |
EMPTY_PLAN |
a plan with zero ops was submitted |
-12 |
ALLOCATION_FAILED |
the allocator refused |
-13 |
READ_ONLY |
write attempted against a read-only lane |
-14 |
UNSUPPORTED_DECODE_MODE |
lgj_hop called with a decode_mode this build does not yet implement (§13, ABI minor ≥ 4) |
-15 |
UNSUPPORTED_CARVING |
lgj_reduce_facet_sum called with a carving outside 0..=2 (§14, ABI minor ≥ 5) |
-17 |
UNRESOLVED_CARVING |
lgj_reduce_facet_sum_resolved's population does not resolve to one grouping — mixed classes, an unanswerable classid, or empty (§15, ABI minor ≥ 6) |
-18 |
UNSUPPORTED_LAYOUT |
the operation needs a byte arrangement this store's layout does not provide — the 12-byte-register sweeps (§14/§15) and the whole-row probe (§16) are row-major operations, and a facet-major store (§18) splits the register into per-field regions. A deferral stated as a status, never a silently wrong sum (ABI minor ≥ 10) |
-16 |
SUM_OVERFLOW |
lgj_reduce_facet_sum's accumulator exceeded i64; out_sum is NOT written (§14, ABI minor ≥ 5) |
INVALID_HANDLE is deliberately the response to use-after-close, not a crash.
See §4.
A mask may be read or written only against the resource it was created
over. Every export that takes a mask beside a resource compares the mask's
parent with that resource by registry identity. Equal row count, equal
resource kind and equal contents are not identity: two resources opened from
the same (rows, seed) are two populations.
The checks, in order, for each mask argument:
- the handle is live and is a mask (
INVALID_HANDLE,WRONG_RESOURCE_KIND); - its parent is still open (
PARENT_CLOSED); - its parent is the resource of this call, and its row count matches
(
MASK_LENGTH_MISMATCH).
A refusal happens before any output is written: the destination mask and every scalar or buffer output hold what they held before the call.
MASK_LENGTH_MISMATCH is kept for the third check. The mask algebra (§7) and
the register sweeps (§14 to §16) already report a foreign parent with this
code, and it is the one status whose meaning is "these do not belong
together". No status is added.
What changed at minor 14. Until then nine mask arguments were checked for
row count only: lgj_op_eq_u32, lgj_op_gt_i32, lgj_plan_eval,
lgj_reduce_sum_i32, lgj_reduce_i32, lgj_op_eq_classid,
lgj_op_ternary_match, and the source and the destination of lgj_hop. This
document stated that reading as deliberate. It allowed a predicate evaluated on
resource B to land in a mask belonging to resource A, and A's values to be
summed over it, with status OK and a number that answered neither.
Compatibility. This narrows accepted input; it is not an additive change.
- A caller that only ever pairs a mask with the resource it was created over
sees no difference. Every Java build in this repository is such a caller:
the facade creates a mask from its owner and uses it with that owner only.
With the rule applied,
AllTests, the four consumer mains and the TinkerPop harness pass unchanged. - A raw-ABI caller that used a mask across two equally sized resources now
receives
MASK_LENGTH_MISMATCHwhere it receivedOK. - §2 reserves the major for incompatible change. The major is not bumped here: doing so would make every existing Java build refuse to load a library that serves it correctly, for the sake of a pairing no shipped caller makes. The minor is bumped instead, so the stricter rule is visible in the manifest and a caller can test for it. This is a deliberate exception to the letter of §2, recorded here rather than left implicit.
What the rule does not restrict: several masks over one resource, one mask used with several lanes or facets of its resource, a mask aliased as source and destination, and any number of schemas or class readings over one resource. Those all share one parent.
Pinned by native/lgj-abi/src/exports/tests/provenance.rs: twelve exports
against five mask origins.
This is the part of the design that Java cannot get from Rust for free. Inside
Rust, &self borrows make a view-outliving-its-owner a compile error. Across
the membrane there is no borrow checker, so the invariant must be enforced at
runtime.
A handle is not a pointer. It is an opaque u64:
63 32 31 0
┌────────────────────────┬────────────────────────┐
│ generation │ index │
└────────────────────────┴────────────────────────┘
indexselects a slot in a Rust-side registry.generationis bumped every time a slot is freed.
A lookup validates generation against the slot's current generation. So:
| Java does | Result |
|---|---|
| uses a live handle | works |
uses a handle after lgj_close |
INVALID_HANDLE — not use-after-free |
| closes twice | second returns INVALID_HANDLE |
fabricates a handle (0, 0xDEADBEEF, …) |
INVALID_HANDLE |
| uses a mask whose parent was closed | PARENT_CLOSED |
There is no code path in which a stale handle dereferences freed memory. That is the single most important safety property of this ABI, and §H of the test plan falsifies it directly rather than assuming it.
| Question | Answer |
|---|---|
| Who owns this memory? | Rust. Always. Java never allocates a lane. |
How long does a MemorySegment remain valid? |
Until lgj_close on the owning handle. ⚠ Java does not model this with a scope. A lane/mask window is MemorySegment.ofAddress(addr).reinterpret(len) (Engine.windowOf) — an unbounded-lifetime segment that cannot observe its resource closing. (The Arenas in the facade back output scratch, e.g. RowStore's result buffer; they never back a lane window, so an earlier claim that segment lifetime is "nested inside" a resource's arena was wrong.) What actually detects staleness is re-asking the substrate: Mask.words() re-describes through lgj_mask_describe on every use of its cache and compares the returned epoch with the stamp it holds. RowStore's cached lanes do not do this — see ISS-LGJ-EPOCH-UNCHECKED, and The sole-closer contract below. |
| What invalidates a view? | Closing the owner, or closing the owner's parent. |
| Can native storage relocate? | No. Lanes are allocated once at lgj_pattern_open and never reallocated, resized, or moved while the resource is alive. This is a hard ABI guarantee; any future growable lane requires a major bump. |
| Can Java mutate it? | Only where LGJ_FLAG_WRITABLE is set on the descriptor. Pattern lanes are read-only; mask words are writable. |
| What happens when the resource closes? | Its lanes are freed, its generation is bumped, its children fail with PARENT_CLOSED. |
| Can a child view outlive the parent? | It can exist but not work — every operation that resolves the child with its parent (resolve_mask_with_parent: mask_count, mask_describe, mask_and, …) returns PARENT_CLOSED. Two exclusions, both deliberate and both covered by tests: lgj_resource_info resolves the child's own slot, which is still live, and returns OK; and lgj_close(child) on an orphan also returns OK, since the child is still a real resource to release. ⚠ Nor does any of this cover a descriptor address Java has already cached and reads directly — that read resolves nothing, so no status is returned at all. See The sole-closer contract below. |
| How are errors represented? | Negative i32 status. Never a panic across the boundary (§9). |
The registry is a RwLock holding Arc<ResourceEntry> values; each entry has its
own inner lock over its payload. A call takes a short read lock on the
registry to resolve and clone the Arc, releases it, then locks only the entry.
So bulk ops on distinct resources run concurrently, and only
open/close serialize globally. Stated honestly: this has not been benchmarked
under contention, and the POC's Java layer is single-threaded.
A resource handle has exactly one closer: the facade object that owns it. Closing a handle by any other route, or from any other thread, is outside this ABI version's contract, and the result is undefined behaviour rather than an error status.
This is a documented contract, not an enforced one, and the distinction is load-bearing — three facts make it unenforceable from the Java side, so a caller who violates it gets no diagnostic:
Engine.close(long)is reachable outside the owning facade object, so nothing structurally prevents a second closer.Engine.windowOfbuilds an unbounded-lifetimeMemorySegmentfrom a descriptor address. The segment cannot observe its resource closing; it has no FFM scope tied to the resource's lifetime.- The facade's own
closedflags are plain non-volatile booleans, so they carry both a check-then-act race and a visibility race across threads.
Why the generation-checked registry does not close this. It fails closed on
every handle resolve, which is why every operation that resolves a child with
its parent returns PARENT_CLOSED once that parent is gone (the exclusions are
in the resource table above: lgj_resource_info and lgj_close resolve the
child's own slot and return OK). But a cached descriptor read resolves nothing:
Java holds the address, reads through it, and the registry is never consulted.
Re-authorising the cached address before each use (as Mask.words() does, via
lgj_mask_describe) narrows the window — the probe's read is a native
acquire through the registry RwLock — and does not close it, because a close
landing between the probe's return and the segment read is still unguarded.
So the contract's scope is precisely the residue: single-closer, and no concurrent close against a live reader. A concurrent Java writer would need a documented protocol, which this ABI version does not define.
Tracked as ISS-LGJ-CACHED-DESCRIPTOR-CROSS-THREAD-WINDOW. It closes when the
ABI defines a concurrent access protocol that makes this enforceable rather than
merely stated.
Java's public API never sees an address. Internally, LgjLaneDesc is the
bounded description that the FFM layer turns into a MemorySegment:
#[repr(C)] // 56 bytes, align 8
pub struct LgjLaneDesc {
pub addr: u64, // physics — never surfaced in the public Java API
pub len_elems: u64,
pub byte_len: u64, // exact covered span: (len-1)*stride + elem_bytes; 0 when empty
pub owner: u64, // owning resource handle
pub epoch: u64, // liveness stamp; Java re-checks before use
pub elem_kind: u32, // LgjElemKind
pub elem_bytes: u32,
pub stride_bytes: u32, // == elem_bytes when contiguous
pub flags: u32, // bitfield, below
}Flags: READABLE = 1<<0, WRITABLE = 1<<1, CONTIGUOUS = 1<<2.
Element kinds start at 1, so a zeroed struct is detectably invalid rather than
silently meaning U8:
U8=1 I8=2 U16=3 I16=4 U32=5 I32=6 U64=7 I64=8 F32=9 F64=10 MASK_WORD=11
MASK_WORD is a u64 of 64 packed row bits, LSB = lowest row index.
#[repr(C)] // 32 bytes
pub struct LgjResourceInfo {
pub kind: u32, // 1 = Pattern, 2 = Mask
pub lane_count: u32,
pub n_rows: u64,
pub epoch: u64,
pub parent: u64, // 0 = none
}#[repr(C)] // 24 bytes, align 8
pub struct LgjOpDesc {
pub op: u32, // LgjOpCode
pub lane_id: u32,
pub operand: i64, // needle / threshold, sign-extended
pub combine: u32, // 0 = AND (narrow), 1 = OR (widen)
pub _reserved:u32, // must be 0
}#[repr(C)]
pub struct LgjAbiManifest {
pub magic: u64,
pub abi_major: u32,
pub abi_minor: u32,
pub size_of_manifest: u32,
pub size_of_lane_desc: u32,
pub size_of_op_desc: u32,
pub size_of_resource_info: u32,
pub align_of_lane_desc: u32,
pub align_of_op_desc: u32,
pub align_of_resource_info: u32,
pub pointer_bytes: u32,
pub endianness: u32, // 0 = little
pub simd_backend: u32, // LgjSimdBackend
pub simd_backend_name: [u8; 32], // NUL-terminated, human-readable
pub build_profile: [u8; 16], // "release" | "debug"
// ── minor 8; everything above is the 104-byte BASE PREFIX the load gate
// requires, and all a pre-minor-8 artifact carries (§17) ──
pub carving_count: u32,
pub carvings: [u16; 8], // (groups << 8) | group_bytes, wire order
}simd_backend: SCALAR=0 AVX2=1 AVX512=2 NEON=3 WASM=4. It is reported, not
negotiated — Java does not select a backend. Which backend is compiled in is
ndarray's business (§7).
Panama makes it easy to write JNI-shaped code: one downcall per element. That is forbidden here. The rule:
Every ABI function must do work proportional to
n_rows, or be lifecycle.
Explicitly prohibited, and each of these would be a design failure rather than a performance nit:
- one call per node / per edge / per element
- one upcall per element
- Java-side hydration of a
Node/Edge/Personobject per row - any serialization: no JSON, no protobuf, no
byte[]bounce buffer - a Java-owned mirror of the native data
The fused-plan call (§7, lgj_plan_eval) exists precisely so that
.where(...).where(...).count() is one crossing regardless of how many
predicates or rows are involved. The unfused per-predicate ops are retained only
so the fused path can be benchmarked against something and so parity can be
checked predicate-by-predicate.
All symbols are prefixed lgj_. All return i32 status except the manifest
getter. out_* parameters are written only on OK.
const LgjAbiManifest* lgj_abi_manifest(void)
Never fails, never allocates, returns a pointer to a 'static. The one symbol
that does not return a status, because there is no failure mode.
i32 lgj_pattern_open(u64 n_rows, u64 seed, u64* out_handle)
i32 lgj_close(u64 handle)
i32 lgj_resource_info(u64 handle, LgjResourceInfo* out)
lgj_pattern_open builds the generic SoA fixture deterministically from seed
(see architecture.md §fixture). Deterministic generation is what lets the Java
test assert exact counts without shipping a data file.
i32 lgj_lane_describe(u64 handle, u32 lane_id, LgjLaneDesc* out)
Pattern lanes: 0 = ids (U64), 1 = classes (U32), 2 = values (I32).
All READABLE | CONTIGUOUS, never WRITABLE.
i32 lgj_mask_create(u64 parent, u32 initial, u64* out_handle) // initial: 0=empty, 1=all
i32 lgj_mask_describe(u64 mask, LgjLaneDesc* out) // MASK_WORD lane, WRITABLE
i32 lgj_mask_and(u64 a, u64 b, u64 dst)
i32 lgj_mask_or(u64 a, u64 b, u64 dst)
i32 lgj_mask_andnot(u64 a, u64 b, u64 dst) // ABI minor ≥ 4, see §13
i32 lgj_mask_ternlog(u64 a, u64 b, u64 c, u64 dst, u8 imm) // ABI minor ≥ 11, see §19.1
i32 lgj_mask_count(u64 mask, u64* out_count)
dst may alias a or b for lgj_mask_and/lgj_mask_or. All three must
share the same parent and row count. lgj_mask_andnot permits the same
aliasing but is NOT commutative (a & !b ≠ b & !a) — its full aliasing and
tail-clearing rules are §13's, not repeated here.
i32 lgj_op_eq_u32(u64 res, u32 lane_id, u32 needle, u64 dst_mask)
i32 lgj_op_gt_i32(u64 res, u32 lane_id, i32 threshold, u64 dst_mask)
Each overwrites dst_mask with the predicate's result. Composition is the
caller's job via lgj_mask_and.
Minor 11 adds no symbol here. The six further comparisons (ne_u32,
eq/ne/lt/le/ge_i32) and the u32 TCAM are LgjOpDesc OP-CODES, so
they are reached through the fused plan below — and n_ops = 1 is the unfused
form, because the accumulator starts all-set and all ∩ op0 = op0. §19.4 is
the argument for spending op-codes rather than symbols.
i32 lgj_plan_eval(u64 res, const LgjOpDesc* ops, u32 n_ops,
u64 dst_mask, u64* out_count)
Semantics: accumulator starts as all rows set; each op is evaluated and
combined into the accumulator per its combine field; the result lands in
dst_mask and its popcount is written to out_count. With every combine = AND
the result is monotonically narrowing by construction:
V0 = all
V1 = V0 ∩ op0 V1 ⊆ V0
V2 = V1 ∩ op1 V2 ⊆ V1 ⊆ V0
This single call is what makes the Java fluent chain cost one crossing.
i32 lgj_reduce_sum_i32(u64 res, u32 lane_id, u64 mask, i64* out_sum)
i32 lgj_reduce_facet_sum(u64 res, u32 facet, u32 carving,
u64 mask, i64* out_sum) // ABI minor >= 5, see §14
i32 lgj_reduce_facet_sum_resolved(u64 res, u32 facet, u64 mask,
i64* out_sum, u32* out_carving) // minor >= 6, §15
i32 lgj_reduce_i32(u64 res, u32 lane_id, u32 reduce_op, u64 mask,
i64* out_value, u32* out_present) // minor >= 11, §19.3
Sums the I32 lane over set mask bits into a widened i64 (no overflow for
n_rows ≤ 2^32 on i32 inputs).
i32 lgj_plan_group_sum_i32(u64 res, const LgjOpDesc* ops, u32 n_ops,
u32 group_lane, u32 val_lane,
u64 via_res, u32 via_lane,
i64* out_sums, u64 n_groups) // minor >= 12, §20
GROUP BY group_lane SUM(val_lane) over the rows the plan selects, in ONE
crossing and ONE program — no selection is evaluated first and no mask handle
is involved. out_sums[g] for g < n_groups; a key past n_groups is
dropped. n_ops == 0 is legal and means every row. via_res != 0 reads the
group key THROUGH group_lane into via_res's via_lane (the fk-keyed form).
i32 lgj_plan_scalar(u64 res, const LgjOpDesc* ops, u32 n_ops,
u32 fold, u32 val_lane, i64* out_value) // minor >= 13, §21
The plan folded to one count (fold = 0) or one I32 sum (fold = 1) in ONE
crossing, with no mask handle. n_ops == 0 is legal and means every row.
lgj_plan_eval remains the symbol for a caller that demands the mask.
i32 lgj_plan_eval_scalar(u64 res, const LgjOpDesc* ops, u32 n_ops,
u64 dst_mask, u64* out_count)
Identical semantics to lgj_plan_eval but forced down the scalar reference path.
Exists only so SIMD-vs-scalar parity is falsifiable through the membrane,
which is where the Java tests live. Not for production use.
i32 lgj_hop(u64 store, u32 edge_classid, u64 facet_mask, u32 decode_mode,
u64 src_mask, u64 dst_mask)
i32 lgj_op_ternary_match(u64 res, u32 facet,
const u8* pattern, const u8* care, u64 dst_mask)
TCAM over a facet's 12-byte V3 register: ((register ^ pattern) & care) == 0,
one bit per row. AosRows only (UNSUPPORTED_LAYOUT otherwise). §19.2 is the
full normative statement.
Overwrites dst_mask with the one-hop reachable set from src_mask over
store's edge_classid-matching facets, gated by the lance-graph-contract
ClassView/FieldMask LAW. §13 is the full normative statement (effective
participation, decode modes, the snapshot-then-write aliasing discipline,
bounds-before-cast).
Every kernel behind these symbols routes through ndarray::simd and nothing
else. Specifically prohibited in this crate:
core::arch::*intrinsics,_mm*,vld1q_*, any raw platform intrinsic#[cfg(target_feature)]/#[cfg(target_arch)]SIMD selectioncore::simd/std::simd/ portable-simd (nightly)pulp,SimSIMD,wide, or any other SIMD crate- a locally-written SIMD abstraction layer
If a primitive is missing, it is added to ndarray::simd under that repo's
W1a consumer contract (all backends + scalar + parity test) and consumed from
here. That is not a workaround; it is the architecture. ndarray::simd is the
permanent hardware membrane for the whole Ada stack, and this project is one more
consumer of it — not an exception to it.
Every extern "C" function wraps its body in catch_unwind. A panic becomes a
negative status, never an unwind into JVM frames (which would be UB). The
Cargo.toml additionally does not set panic = "abort", because
catch_unwind requires unwinding to be available.
Named so their absence is a decision on record rather than an oversight:
- No strings across the boundary except the two fixed-size NUL-terminated
name fields in the manifest. No
char*in, ever. - No callbacks / upcalls. An upcall per element is the JNI anti-pattern in disguise; a bulk op needs no callback.
- No variadics.
- No
errno/captureCallState. Nothing here is a syscall wrapper. - No growable or relocatable lanes (§4).
- No
lgj_lane_read_element. There is intentionally no way to read one row across the membrane. If Java wants element access it reads theMemorySegmentdirectly, in-process, with no crossing at all. - No
ClassView/WideFieldMaskyet. The first slice is the generic fixture on purpose (seearchitecture.md§"generic is not toy"). Wiring the reallance-graphtypes is the next slice, and their shapes are already ABI-compatible:WideFieldMask's canonical[u64]chunks are this ABI'sMASK_WORDlane, andNodeRow's16|16|480#[repr(C, align(64))]layout is already a legal lane description.
The substrate layout the whole stack converges on — operator-stated reference (2026-08-17): 64K rows × 512 bytes per row, 32 facet lanes of 16 bytes each (4-byte little-endian classid + 12-byte payload), the lance-graph V3 content-blind facet shape, enforced everywhere on the Rust side. The Java side's view may differ; these bytes are the substrate truth. One buffer, zero serialization: every access — Rust kernel or Java segment read — is a reading of the same bytes.
LGJ_RESOURCE_ROWSTORE = 3
i32 lgj_rowstore_open(u64 n_rows, u64 seed, u64* out_handle)
Deterministic generator (normative; two SplitMix64 draws per facet, a then
b, 64 draws per row — full statement in rowstore.rs's doc):
classid = (a >>> 33) & 0xF // same recipe as the fixture's class lane
payload = le64(b) ++ le32(a & 0xFFFFFFFF)
anticipated this since minor 1)
| lane id | what | kind | stride | flags |
|---|---|---|---|---|
0 |
the raw buffer, n_rows * 512 bytes |
U8 |
1 | READABLE | CONTIGUOUS |
1 + f (f in 0..32) |
facet f's classid column |
U32 |
512 | READABLE |
byte_len is the exact covered span (len_elems - 1) * stride_bytes + elem_bytes (0 when empty) — for a strided facet lane this deliberately does
NOT round up to len * stride, because the lane's base sits f*16 into the
buffer and a full-stride final window would let Java bound a segment past the
allocation's end. For contiguous lanes the formula reduces to
len * elem_bytes, unchanged from minor 1.
i32 lgj_op_eq_classid(u64 res, u32 facet, u32 needle, u64 dst_mask)
i32 lgj_row_facet_match(u64 res, u32 needle, u32* out, u64 out_len_elems)
lgj_op_eq_classidoverwritesdst_maskwith the row maskclassid(facet, row) == needle.facetis a facet index0..32, not a lane id. The result is an ordinary mask:lgj_mask_createaccepts a row store as parent (masks may parent onto a pattern OR a row store — both are read-only row-shaped resources), and the whole §7 mask algebra (and/or/count/describe) applies unchanged.lgj_row_facet_matchwrites, for every row, au32bitset of which of its 32 facets carryneedleas classid — into the caller's buffer (a Java-arena segment; zero-copy out, nothing serialized). Capacity is checked BEFORE anything is written (MASK_LENGTH_MISMATCHon a short buffer).
lgj_op_eq_classid routes through ndarray::simd::eq_u32_strided_to_mask
(scalar strided loads — at stride 512 each element is on its own cache line,
so the walk is memory-bound and SIMD earns its keep in the 16-wide compare).
lgj_row_facet_match wraps the store's bytes in
ndarray::simd::MultiLaneColumn (an Arc refcount bump, no copy) and answers
four facets per 64-byte chunk with one U32x16::eq_bitmask.
The buffer base is u8-aligned (Arc<[u8]>; stable Rust promises no more).
Rows are 512-byte strided within it. Nothing in this slice needs more — Java
reads via JAVA_INT_UNALIGNED-class layouts, and every ndarray::simd load
is a register fill. The 64-byte-aligned base guarantee arrives with the real
NodeRow (#[repr(C, align(64))]) wiring.
consumer-graph-traversal-v1.md's falsifiers need a 1-2 hop BFS that is
non-vacuous — plain lgj_rowstore_open's payload is uniform noise, so any
hop over it saturates to nearly every row within one or two steps
(.claude/harvest/graph_density_probe.rs's own measurement). This is an
alternative constructor, not a new resource kind, new lane shape, or new
mask op — LGJ_RESOURCE_ROWSTORE and the whole §11 lane/operation surface
apply to its output unchanged.
i32 lgj_rowstore_open_with_edges(u64 n_rows, u64 seed,
u32 edge_classid, u64 edge_gate_mask,
u32 edge_radius, u64* out_handle)
Reuses §11's classid stream byte-for-byte — same two SplitMix64 draws per
facet, same classid = (a >>> 33) & 0xF. For a facet whose classid equals
edge_classid AND whose draw clears the sparsity gate (a & edge_gate_mask == 0), the 12-byte payload instead carries a structured target row:
span = 2 * edge_radius + 1
offset = (b % span) - edge_radius // signed, |offset| <= edge_radius
target = (row + offset) mod n_rows // bounded-local-neighbourhood
payload_lo64 = target as u64 // hi32 forced to 0 (the flag
payload_hi32 = 0 // a hop reads to know "structured")
Every other facet (classid mismatch, or gate not cleared) is byte-identical
to lgj_rowstore_open's plain draw (payload = le64(b) ++ le32(a & 0xFFFFFFFF)) — so an out-of-range edge_classid (one that never occurs
in the classid stream, e.g. 16) reproduces lgj_rowstore_open exactly,
which is how RowStore::generate_with_edges's own test suite proves the two
generators share one code path rather than drifting apart.
Density is governed by edge_gate_mask: the gate probability is
1 / (16 * (edge_gate_mask + 1)) (16 candidate classids × the mask's extra
selectivity), so edge_gate_mask = 0 is the densest edge-bearing setting.
edge_radius must be < n_rows (an unsatisfiable bound is
LGJ_ERR_LENGTH_OVERFLOW, matching every other overflow-shaped rejection in
this generator family).
⊘ SUPERSEDED (2026-08-18, D-LGJ-W8). The Java-side composition described below is exactly the row-population-hydration shape the mask-native navigation correction (
.claude/plans/mask-native-navigation-correction-v1.md) demotes: per-rowpayload_lo64decode + a Java-side scatter loop is a materialised-population execution path, not a mask-native one. The shipped path — required, not merely preferred (spec §3.8: consumers cannot reach the segment surface at all;ApiSurfaceTestwalls offinternal.ffm) — is the native §13lgj_hop, ABI minor ≥ 4. This subsection is kept, not deleted, as the record of the D1a composition it replaces.
A hop is lgj_row_facet_match(edge_classid) (§11, unchanged) to find which
of a row's facets carry the edge classid, followed by a Java-side decode
of each matched facet's payload_lo64 as the target row and a scatter into
the next mask via lgj_mask_describe's WRITABLE lane (§7) — one crossing per
hop, zero new ABI surface. See consumer-graph-traversal-v1.md Decision D1a.
A native lgj_hop symbol (D1b) remains a future ABI minor if Java-side
scatter measurably dominates; it is not part of this minor.
The generator's per-facet loop is scalar (SplitMix64 is inherently
sequential per draw); the sparsity gate and target-row arithmetic are cheap
integer ops on that same sequential stream — no new SIMD kernel, matching
RowStore::generate's own scalar generation loop.
Two additions, both consuming the class_view_provider::edge_participation
seam (.claude/plans/mask-native-navigation-correction-v1.md, D-LGJ-W8,
§3.3): lgj_mask_andnot closes a real gap in the mask algebra — no
and-not/complement op existed anywhere in the mask/registry system before
this minor — and lgj_hop is the FIRST symbol in this ABI whose semantics
are governed by the lance-graph-contract crate rather than by this
crate's fixture alone: a facet only participates in a hop if BOTH the
caller's facet_mask and the class's ClassView-resolved
edge_participation agree it should.
Both are bulk (§6): lgj_mask_andnot does work ∝ n_rows / 64 words;
lgj_hop does work ∝ n_rows · popcount(effective participation) — at
most n_rows · 32 facet-classid compares, plus one scalar decode+scatter
per matched (row, facet) pair.
i32 lgj_mask_andnot(u64 a, u64 b, u64 dst)
dst = a & !b, word-wise. Same parent/row-count compatibility rule as
lgj_mask_and/lgj_mask_or (§7): all three masks must share the same
parent and row count, or MASK_LENGTH_MISMATCH.
dst may alias a, b, or both — unlike AND/OR, ANDNOT is not
commutative, so aliasing dst == b is NOT the same case as dst == a
with the roles swapped: the kernel snapshots b's value into a scratch
buffer before it is overwritten whenever dst aliases b, so the result
is always a & !b as evaluated BEFORE the call, regardless of which
argument dst aliases.
Tail rule (normative). Bits at row index >= n_rows in the final word
are always zero on return, re-established as a distinct, defensive step
after the complement — never merely inherited from well-formed inputs. A
corrupted operand's tail bits (bits set past n_rows by an out-of-band
write) are silently REPAIRED, not merely preserved: !b's tail naturally
sets bits wherever b's own tail is zero (the well-formed case), so a
version of this kernel without the explicit clear would leak a corrupted
a's stray tail bits straight into dst.
Kernel: ndarray::simd::{mask_andnot, mask_andnot_assign} (§8 SIMD
provenance, unchanged rule) — never ndarray::simd_int_ops directly.
i32 lgj_hop(u64 store, u32 edge_classid, u64 facet_mask, u32 decode_mode,
u64 src_mask, u64 dst_mask)
store must be a LGJ_RESOURCE_ROWSTORE (§11); src_mask and dst_mask
must each belong to it (§3.1): a mask over any other resource, equally
sized or not, is MASK_LENGTH_MISMATCH. The two masks are checked
separately. Until minor 14 only the row count was checked.
Semantics. dst_mask is OVERWRITTEN with the one-hop reachable set:
for every row r set in src_mask, for every facet f in the effective
participation where classid(r, f) == edge_classid, if the selected
decode mode yields a valid target t < n_rows, bit t is set in the
result.
Effective participation is facet_mask ∩ edge_participation(edge_classid) — the caller's requested facets narrowed
by what the class's ClassView provider
(class_view_provider::edge_participation, D-LGJ-W8 §3.3) says this
class's edges actually occupy. facet_mask is the wire form of the
contract's FieldMask: a u64 whose bits >= 32 are ignored (this store
has 32 facets).
Decode modes. decode_mode = 0 is the §12 fixture convention:
payload_hi32 == 0 marks a structured edge, payload_lo64 is the LE
target row. Modes 1..=3 are RESERVED — mirroring `EdgeCodecFlavor as u32
- 1
(canonical_node.rs) — and return the new statusLGJ_ERR_UNSUPPORTED_DECODE_MODE = -14until real class data lands. This check runs FIRST, beforestore/src_mask/dst_maskare even resolved, sodst_maskis provably untouched (out_*` write-only-on-OK, §7) on a rejected call regardless of whether the other arguments would themselves have been valid.
Aliasing. src_mask is snapshotted (its words copied into an owned
buffer) under a READ lock that is fully RELEASED before dst_mask's
WRITE lock is taken. This is a DIFFERENT discipline from
lgj_mask_and/lgj_mask_or/lgj_mask_andnot's dedup-before-lock scheme
(registry.rs lock_masks_ordered, needed there because those calls hold
two or three mask locks simultaneously): lgj_hop never holds more than
one mask lock at a time, so dst_mask == src_mask aliasing carries zero
deadlock risk by construction, not by case analysis.
Bounds-before-cast (normative). The decoded target t is compared
against n_rows as a u64 BEFORE any t as usize cast — the ordering is
part of the contract, not an implementation detail, so an out-of-range
u64 target can never reach an indexing operation.
Kernel composition. Selection is mask algebra —
src ∧ class_f ∧ struct_f per participating facet, accumulated into dst:
| operand | how it is produced |
|---|---|
class_f |
facet f carries the edge class |
struct_f |
facet f's payload_hi32 == 0, i.e. a structured edge |
src |
the caller's frontier, snapshotted under a read lock |
Both predicates are the SAME sanctioned primitive at two offsets into the
16-byte facet — kernels::simd_rowstore_u32_eq_mask,
ndarray::simd::eq_u32_strided_to_mask (the kernel lgj_op_eq_classid also
uses, §11) — with first_offset = f*16 + 0, needle = classid for the class
and first_offset = f*16 + 12, needle = 0 for the gate. The ANDs are
ndarray::simd::mask_and_assign, word-parallel over 64 rows at a time. Two
scratch word buffers are REUSED across every participating facet, never
reallocated per facet.
No row is examined to decide whether it participates. Only the
resulting set-bit walk + payload decode + scatter is scalar, and only
because the destination row index is DECODED from the selected row's
payload: that is the operand of a permutation, not a decision about
membership. There is no ndarray::simd primitive for decode-scatter, and
duplicating either predicate in scalar Rust would be exactly the polyfill
bypass §8 forbids.
The structured-edge gate was an
ifinside the row walk until 2026-08-27 — in every earlier shape of this function, including the first mask-shaped one. It was always this call; the kernel already took an arbitraryfirst_offset.
Neither symbol is lifecycle, and neither is a fixed-cost call: a caller
that doubles n_rows observes roughly double the work in both — for
lgj_mask_andnot, twice the mask words; for lgj_hop, twice the rows
scanned per participating facet. Both therefore satisfy §6's anti-JNI rule
by the same test every existing symbol satisfies it by: work proportional
to n_rows, never one crossing per element.
One symbol, and it is the execution half of a mask path whose build half has
existed since minor 2. That framing matters more than the addition: before
this minor the membrane could already turn a classid column into a mask
(lgj_op_eq_classid → ndarray::simd::eq_u32_strided_to_mask, §11) and could
already compose masks (and/or/andnot/count, §7/§13) — what it could not
do was consume a mask against the 12-byte facet register. That gap is why a
consumer wanting the shape had to leave the membrane.
i32 lgj_reduce_facet_sum(u64 res, u32 facet, u32 carving,
u64 mask, i64* out_sum)
Sums every group of facet's 12-byte register, under carving, over the rows
mask selects. Cost is O(mask_words + popcount × groups) — the mask-word
scan is unconditional, so an empty mask costs one pass over the mask rather than
nothing. §6's bulk-or-lifecycle rule holds either way: no term is
per-crossing-per-element.
i64 is not closed under this reduction. Under the quads reading one row
contributes up to 3 × (2³² − 1) = 12 884 901 885, so i64::MAX is exceeded
after ~715 827 882 maximum-valued selected rows — about 341 GiB of 512-byte
rows, which is inside the scale this substrate contemplates rather than safely
beyond it. The kernel accumulates in i128 (which cannot overflow: the per-row
bound × u64::MAX rows still fits) and range-checks once, returning
LGJ_ERR_SUM_OVERFLOW with out_sum untouched. A silent wrap would be exactly
the plausible-but-wrong answer this ABI otherwise works to prevent.
carving selects one of le-contract.md §3's three readings of the same 12
bytes:
| wire | reading | groups × bytes |
|---|---|---|
0 |
rails | 6 × (u8:u8), LE u16 |
1 |
SPO triplets | 4 × (u8:u8:u8), LE u24 zero-extended |
2 |
odoo quads | 3 × (u8:u8:u8:u8), LE u32 zero-extended |
Since minor 8 this table is DESCRIPTIVE, not normative — see §17. The
encoding is derived from the contract's CascadeShape::ROTATIONS (group count,
descending) and SERVED in the manifest; a reader that needs the authoritative
answer reads carvings, and this row set is what that derivation currently
produces. Before minor 8 it was one of three hand-written copies, which is the
problem §17 exists to remove.
Anything else is LGJ_ERR_UNSUPPORTED_CARVING (-15), checked first,
before the store or mask are resolved, so out_sum is provably untouched on a
rejected call. An unknown reading must never alias a known one.
This follows lgj_hop's decode_mode precedent (§13, spec §3.4) rather than
edge_participation's ClassView consult. Re-resolving the reading per row
inside the sweep would put the question back in the hot loop — exactly what this
symbol exists to take out of it, and a per-row ClassView consult here would be
the mask-native law's own defect one layer down.
But be precise about what that does and does not establish. This symbol is a
RAW REINTERPRETATION primitive. It applies the carving it is handed to every
selected row; it does not — and cannot — verify that this is the reading those
rows' classes specify. A mask is an opaque population (it may be an
lgj_mask_or/import union spanning several classids), and the fixture
ClassView carries no carving resolver at all today. The Java surface is named
facetSumAs for exactly this reason: the caller supplies the reading and owns
its correctness.
The stronger shape binds the answer to the population ONCE, so the sweep receives an answer rather than a promise:
classid → ClassView → ResolvedCarving → (population + its carving) → sum
That keeps the property this path exists for (the ALU gets the answer, not the question) while making the binding checkable. It needs a real ClassView carving resolver upstream, which does not exist yet, so it is recorded here as the next rung — deliberately not faked with a per-row consult.
The mask must belong to this store, not merely match its row count — an
equal-length mask over a different resource is a different population wearing
the right size. Rejected with LGJ_ERR_MASK_LENGTH_MISMATCH, matching the mask
algebra's own parent check (lgj_mask_and) rather than minting a second
spelling for the same rejection.
This kernel is scalar, deliberately, and the vector form is a NAMED GAP.
ndarray::simd has no primitive for "gather a sub-word group out of a
512-byte-strided register under a runtime grouping and widen-accumulate":
masked_sum_i32 is contiguous i32, and eq_u32_strided_to_mask reads one
aligned u32 per row, not six unaligned u16s. Writing raw intrinsics here
would create precisely the second SIMD surface §8 exists to prevent, so the
scalar form is the in-bounds implementation and the vector form belongs in
ndarray::simd under the W1a consumer contract — added there and consumed
here, never re-implemented at this layer.
Sub-word loads are byte-wise rather than u16/u32 reads because a group's
offset is facet*16 + 4 + g*group_bytes, which is not guaranteed aligned for
the 3-byte reading, and an unaligned wide read is UB in Rust even where the
hardware tolerates it.
valhalla-lab/reproducers/R8_EntropyBoundary.java (merged PR #24) measured the
alternatives on identical bytes with checksum-identical results. Under a
random classid distribution, a generic sweep that re-derives the carving per
row collapses, while both a materialised index-list partition and a mask-driven
sweep recover ~4.8×. The mask is the lawful of the two — an index list is a
materialised population, which the root CLAUDE.md forbids as internal
currency — and it is also the cheaper: building it via
eq_u32_strided_to_mask was an order of magnitude cheaper than a scalar
partition scan, moving break-even from ~120 passes to ~10. Obeying the law is
the fast path, not a tax on it.
The control leg is equally load-bearing: under a predictable classid pattern the same measurement shows specialization buying nothing. This symbol is worth calling when there is entropy to remove, and not otherwise.
§14 shipped lgj_reduce_facet_sum with an honest caveat: it applies a grouping
the caller asserts, and cannot check it, because a mask is an opaque
population and nothing on ClassView returned a grouping. That second half is
now false, and this section is the consequence.
i32 lgj_reduce_facet_sum_resolved(u64 res, u32 facet, u64 mask,
i64* out_sum, u32* out_carving)
For every selected row it resolves facet classid → ClassId → ClassView::cascade_shape and requires every row to agree, then sweeps
monomorphically under that answer, reporting the grouping back through
out_carving. The shape the §14 note named as the next rung, built:
classid → ClassView → ResolvedCarving → (population + its grouping) → sum
The question is asked once at the population's edge and never inside the
sweep. Resolution is O(mask_words + popcount); the sweep that follows carries
no per-row dispatch. Resolving per row would have been the defect this whole
path exists to avoid — the fix for "unverified" was never "consult more often".
CascadeShape (lance_graph_contract::facet) has carried the three groupings
— G6D2 rails, G4D3 triplets, G3D4 quads, each G·D = 12 — together with
the full algebra and its own statement that the grouping is "class-conditioned:
classid selects it from the inherited schema". What did not exist was a
ClassView method RETURNING one, which is why §14 minted a local Carving
enum and documented that it claimed no authority.
ClassView::cascade_shape (contract, 2026-08-25) is that missing accessor,
following the exact registry-resolution pattern of its four siblings
(edge_codec_flavor / rail_carving / band_reading / value_schema), with
G3D4 — CascadeShape's own "canonical GUID shape" — as the zero-fallback.
The local enum is now a pub type Carving = CascadeShape alias; only the u32
wire encoding stays local, because a #[repr] discriminant is not part of
the contract's promise. That mapping is pinned by group count, so a variant
reorder upstream cannot silently re-map the wire.
This also required widening the G11 contract-import fence by one module —
facet, alongside class_view/canonical_node/ontology. Deliberate and
recorded, not incidental.
LGJ_ERR_UNRESOLVED_CARVING (-17) covers three causes and one fact — the
population spans classes that read the register differently, a row's classid has
no ClassView answer, or the population is empty. Zero rows carry zero
classes, so reporting the zero-fallback there would be inventing an answer.
Neither output is written.
FixtureClassView::cascade_shape returns class % 3 rather than the trait's
constant zero-fallback. That is a fixture choice, stated as one: a constant
answer makes every population trivially homogeneous, so the "does this resolve
to ONE grouping" guard could never fire and a test for it would pass for an
implementation that never checked. Varying makes both outcomes reachable on real
fixture data — a lgj_op_eq_classid mask is single-class and resolves; a union
across classids with different groupings is refused; and a union across classids
that share a grouping still resolves, which is the paired half that stops the
refusal from being "reject everything".
lgj_reduce_facet_sum_resolved is the one to reach for. §14's
lgj_reduce_facet_sum remains as the deliberate reinterpretation escape hatch —
for a caller that means to read the register under a grouping the class does not
sanction — and its Java name (facetSumAs) says so.
Recorded because §1 makes symbol growth a design smell that needs justification, and §14's justification was weak: the operation came from a benchmark's checksum. It is retained, with a better reason and a falsifiable condition to revisit.
The reason: it is the only mask-CONSUMING operation over the register. Without
it the mask path has a build half and no execution half, and a consumer wanting
that shape must leave the membrane — which is the pressure §6's anti-JNI rule and
the Missing-capability STOP rule both exist to relieve. sum is additionally the
cheapest operation that cannot be faked from the outside: any correct
implementation must visit exactly the selected rows and decode exactly the
resolved grouping, which is why it doubles as the parity oracle for both.
The condition to revisit, stated so it can actually fire: if a second
reduction is ever needed (min/max/count-distinct/histogram), do NOT add a second
symbol. That is the point at which the operation should be generalised — an
op-code parameter on one reduce symbol, mirroring how lgj_plan_eval's
LgjOpDesc already generalises predicates — and sum becomes op-code 0. Two
reduction symbols would be the smell §1 warns about; one parameterised symbol is
the shape this ABI already uses elsewhere.
Resolution is a per-CLASS fact consulted over a population, so it is cacheable at two different lifetimes and both are wired.
Per dataset — classid → grouping. RowStore carries a OnceLock table
built on first resolved sweep: class_id_for narrows a u32 classid to u16,
so the table is 65 536 one-byte entries (0 = no ClassView answer, else the
wire value plus one). 64 KiB, 65 536 ClassView calls once, then never again.
That trade is the right way round — the table is bounded and one-off, while the
per-row consult it replaces is unbounded in sweeps. A OnceLock rather than a
LazyLock because the resolver is supplied by the caller; the first caller wins
and every later one reads.
Per population — the resolved grouping itself. The memo lives inside
MaskWords, so it is read under the same lock that guards the words: a
resolution can never be observed against a population it was not computed from.
Three properties make it safe rather than merely fast:
- Keyed by facet, not merely cached. Different facets of the same rows carry different classids and can resolve differently. A memo holding only "the grouping" would answer a question about facet 3 with facet 7's answer — wrong, not stale.
- Invalidation cannot be forgotten. It happens in
write_mask()andlock_masks_ordered()— the only two ways to obtain the right to mutate a mask. Any writer invalidates whether or not it changes a bit: conservative, and impossible for a new mask-mutating op to skip. - Filled under the READ guard. The obvious alternative — compute under read,
upgrade to write, store — is wrong twice: it would clear the very memo it is
storing (that is what a write guard means here), and between dropping the read
and taking the write another thread could change the population, so the stored
value would describe rows that no longer match. Holding the read guard is
exactly the interval in which the population is stable, so the fill belongs
there. Hence an atomic field rather than a plain
Option.
The encoding carries an explicit present bit, so facet 0, grouping 0 is a real
answer rather than reading as an empty memo.
A test-only counter (RESOLUTIONS) makes the memo's behaviour observable rather
than asserted: the first sweep resolves, five repeats over the same population do
not, a different facet does, and a rewritten population does.
i32 lgj_row_layout_probe(u64 res, u64 mask, u8* out, u64 out_len)
For every facet, the SET of register groupings its selected rows carry. One crossing covers all 32 — asking per facet would be 32 crossings, and is how a consumer drifts into the per-element loop §6 forbids.
Each output byte is a 3-bit set (bit w = some row resolves to grouping w)
plus bit 3 for "some row's classid has no ClassView answer". Then:
aligned(facet) ⟺ popcount(byte) == 1 && byte & UNANSWERABLE == 0
One or per (row, facet), no comparison and no early exit, so cost does not
depend on the data. An OR-accumulated set is exact where cheaper accumulators
are not: a sum of wire values cannot tell {0,2} from {1,1}, and an XOR
cannot tell {1,1} from {}. The set forgets multiplicity, which is precisely
the information the question does not need.
0 means the EMPTY set — no row selected — and is deliberately distinguishable
from disagreement. Conflating them would report "misaligned" for a population
that simply is not there.
A mask from lgj_op_eq_classid(facet 3, …) constrains facet 3 only; the
other 31 facets of those rows carry whatever classids the generator gave them.
Measured on the fixture: 1 of 32 facets aligned. A test asserting
isFullyAligned() there failed, and the expectation was wrong rather than the
code — which is exactly the confusion a whole-row probe exists to remove.
Note what this says about placement: the canon makes classid the key's
prefix precisely so key-ordered placement clusters a class into a range. The
fixture generates classids uniformly at random instead — measured mean run
length 1.07, mean gap ~17 rows. Clustering is worth doing, and measured at
this stride it is worth ~2× (12.6 vs 25.6 ns/row for the same population size,
contiguous vs every-16th-row) — not from cache-line count, which is one line per
row either way at a 512-byte stride, but from stride-predictable prefetch and TLB
locality.
The classid → grouping table is process-global (LazyLock, 64 KiB, built
once), not per dataset: the same classid means the same class in every SoA, so
the resolution is dataset-independent. An earlier version put it on RowStore,
which was wrong in shape rather than output — the answers were right, but the
placement implied two datasets could disagree about what a classid carves into,
which the address space does not permit.
And the table captures layout only. Meaning, RBAC, ontology category and render template are separate resolutions off the same address; none belong in it and none can be inferred from it.
The manifest grew two fields. No symbol, no status, no call:
u32 carving_count // populated entries in `carvings`
u16 carvings[8] // entry w = wire value w, packed (groups << 8) | group_bytes
Entries past carving_count are zero, so a reader that trusts the count and one
that scans for a terminator agree. The struct is 128 bytes (108 + 16 = 124,
rounded to its 8-byte alignment).
The wire encoding of §14's carving parameter was hand-written in three
places — a Rust match, a Java enum, and §14's own table — with nothing that
would fail if they disagreed. Three copies of one fact is not a documentation
problem; it is a correctness problem with no falsifier, and the specific failure
it invites is silent: a grouping added or reordered upstream re-maps one copy and
not the others, and a sweep then reads the same 12 bytes under the wrong reading
and returns a plausible number.
So the fact now has one source and two derivations:
- The contract owns the SET.
lance_graph_contract::facet::CascadeShape::ROTATIONS. - This ABI derives the ENCODING from it — group count, descending
(
kernels::CARVING_ORDER, aconst). A variant REORDER upstream cannot re-map the wire, because position is computed fromgroups()rather than from declaration order. A variant ADDED upstream appears automatically, in its group-count place, with no edit. - The manifest SERVES the result, and Java reads it rather than restating it.
CARVING_ORDER is deliberately a const and not a LazyLock: the manifest is
const-initialised, and a runtime-initialised order could not be reached from it.
The manifest already exists so Java can discover the ABI's SHAPE instead of
declaring it — sizes, alignments, pointer width, byte order. A wire encoding is
exactly such a shape. Serving it here costs no symbol, no crossing at call time,
and no lifetime question (a fixed u16[8] rather than a pointer), and it arrives
on the same read Java already performs at load.
Carving's ARITY stays declared: RAILS_6X2 named anything other than 6 × 2
would be a lie in its own name. What is no longer declared is its wire value —
that is looked up in the served table by arity. Meaning is declared; encoding is
served.
- Rust,
the_manifest_serves_exactly_the_derived_carving_order— the served bytes against the derived order, including that each entry decodes back to its own shape, so a table that is internally consistent but wrongly ORDERED fails. - Rust,
the_derived_order_is_strictly_descending_by_group_count— a future variant that TIED on group count would make the sort order-dependent again, which is the property the derivation exists to remove. - Java,
CarvingTableTest— membership both ways. A grouping served that Java cannot name (an addition upstream) and a grouping Java names that is not served (a removal, or a locally invented constant). Neither direction is redundant: without them, either mismatch would surface only when a particular row happened to resolve to it — on someone's data, not in the build.
Verified red-then-green: swapping the packed axes fails the Rust serve test; reversing the sort direction fails the order test and two others; changing one Java constant's arity fails both membership directions.
A library predating minor 8 serves no table. Java falls back to the encoding
those artifacts actually used, in one clearly-named compatibility shim
(CarvingTable.PRE_MINOR_8) rather than back in the enum — so exactly one place
in the build carries a literal encoding, and its name says it is history rather
than the current answer.
A layout is a schema over the same content (R11's finding, executed):
lgj_rowstore_open_columnar(n_rows, seed, edge_classid, edge_gate_mask, edge_radius, out_resource) opens a store whose LOGICAL content is
byte-for-byte the AoS constructors' (same generator, same draws), arranged
field-major over the (row × facet) plane:
[0 .. 128n) classid facet f at f*4n, stride 4, contiguous
[128n .. 384n) lo64 facet f at 128n + f*8n, stride 8, contiguous
[384n .. 512n) hi32 facet f at 384n + f*4n, stride 4, contiguous
Still 512 bytes per row; still one buffer; still the same resource kind — every mask, hop and count symbol accepts the handle unchanged and must answer identically (pinned by the cross-layout equivalence tests, including the 10 → 19 → 29 hop regression on BOTH layouts). What changes is only that every single-field sweep becomes CONTIGUOUS, which is what the mask algebra's cost model wants: measured through this ABI, the hop runs 3.3–4.8× faster than AoS at every frontier arm (65 536 rows, all 32 facets, equivalence asserted before timing).
The lane table is how consumers survive the change. Minor 10 grows it
from 33 to 97 lanes — 1 + f classid (as before), 33 + f payload-lo64
(U64), 65 + f payload-hi32 (U32) — and the descriptors carry the
layout's own offsets and strides (AoS: stride 512; facet-major: stride 4/8,
contiguous). A consumer that reads through descriptors is layout-blind by
construction; the Java facade now holds NO spelling of the row geometry at
all (disable-verified: hard-coding stride 512 in its accessors fails the
columnar store at the first row where the layouts' addresses diverge, and
only there).
What refuses, and why that is honest. The register-sweep family —
lgj_reduce_facet_sum (§14), lgj_reduce_facet_sum_resolved (§15),
lgj_row_layout_probe (§16) — reads the 12-byte payload as ONE contiguous
register. A facet-major store deliberately splits that register into
per-field regions, so these return UNSUPPORTED_LAYOUT (-18) rather than
gathering it back together per row (which would be the serialization this
ABI exists to forbid) or summing scrambled bytes (which would be worse).
The gate discriminates by layout: the same calls succeed on AoS, pinned
two-sided.
Alignment, stated honestly (matching §11's own statement): the base
pointer is u8-aligned (Arc<[u8]>). The three region bases (0, 128n,
384n) are multiples of 64 for any n_rows. The per-facet BLOCK offsets are
not: classid and hi32 blocks start at f*4n (plus the region base), all
multiples of 64 exactly when n is a multiple of 16; lo64 blocks start at
128n + f*8n, all multiples of 64 exactly when n is a multiple of 8. At
n = 257, block 1 starts at byte 1028, and 1028 % 64 == 4. Nothing is
padded. No kernel and no Java read requires alignment: the kernels use
unaligned loads (and give identical mask words at base offsets 1, 3 and 7),
and Java reads with *_UNALIGNED layouts. Pinned by
facet_major_alignment_holds_exactly_when_n_is_a_multiple_of_16 and
strided_eq_mask_is_independent_of_the_base_alignment. An earlier text of
this paragraph claimed "any n_rows" for the block offsets; that was false.
The carvings' own contract is untouched: every
CascadeShape group is ≤ 4 bytes — half the JEP 401 flattening budget —
and 512 = 8 × 64 keeps the row stride cache-line-quantised (both pinned
in rowstore.rs, the substrate half of what R4/R10 measured from the
Valhalla side).
Three alignment facts, never merged, none inferred from the row width. The row width (512) is a multiple of 64, and nothing follows from that about where any lane starts.
- Logical geometry: a lane's offset from the store base, stride, element
size, exact covered span
(len-1)*stride + elem, last element in bounds, span ending at or before512n. No address is involved. - Actual base alignment: the real address of the store base (
as_ptr()in Rust, the raw lane's descriptor address in Java) modulo 8, 64 and 128. RECORDED, never asserted to a value: the allocation isArc<[u8]>and the promise isu8alignment only. Measured bases here were always 16-aligned, withbase % 64observed as 0, 16, 32 and 48, varying between allocations, runs and between the Rust and Java processes; that is an allocator accident, not a contract. - Per-lane alignment:
(base + lane_offset) % elem_bytesand% 64, from the actual address. Measured consequence: on a base that is a multiple of 8, the 32 row-majorlo64lanes sit at offsetf*16 + 4, so none is 8-aligned, while all 64u32lanes and (facet-major) all 32u64lanes are element-aligned. Element alignment is decided by the base, never byn; 64-alignment of facet-major blocks is decided bynAND the base (atn = 257, 8 of 96 lanes are 64-aligned relative to the base; atn = 16all 96 are, and the actual-address count is then 0 or 96 depending on the measured base).
Pinned by rowstore::tests::alignment_is_three_separate_facts_geometry_then_base_then_per_lane,
...::at_257_an_odd_based_copy_has_misaligned_u32_and_u64_lanes_and_still_reads_equal
(every u32 and u64 lane misaligned in both layouts, every read and mask
still equal, tails clear), ...::byte_order_is_little_endian_at_the_documented_positions_in_both_layouts
(fixture asymmetric: the big-endian read differs), and Java's
AlignmentFactsTest, which also fails if alignment is simplified to
rowStride % 64 == 0. Each prints one table per layout.
Two shape contracts, not interchangeable. (a) The layout addressing of 32
x 16-byte facets, row-major and facet-major, is owned HERE. (b) ndarray's FACET
STRIDE positional rule (a 128-bit facet is sixteen byte positions, read by the
load that brought it in) and its DR512 lut9 presence/polarity rule are owned
by ndarray. Applicability in this repository:
| invariant | exercised here | layout | test |
|---|---|---|---|
| lane geometry, strided access | yes | both | layout_parity.rs, AlignmentFactsTest, DescriptorParityTest |
| 12-byte register match, carvings | yes | row-major only | existing kernel tests |
all sixteen positions (ternary_match_strided16_to_mask), test-only use |
exercised in tests, not by production | row-major | positional_parity::the_sixteen_position_match_equals_a_byte_wise_oracle_over_the_row_major_store |
| the same rule on facet-major | not applicable: the sixteen bytes are not contiguous; the equivalent is three per-field passes conjoined, equal to the row-major mask | facet-major | positional_parity::the_sixteen_position_rule_has_no_facet_major_form_and_its_equivalent_is_three_passes_conjoined |
lut_u8, lut9, DR512 presence/polarity |
not applicable: no DR512 lane, no presence plane, none called | none | tests/dr512_not_adopted.rs (fails if production code starts using them) |
| contract cascade ladder against lgj carving byte order | compared; they differ | row-major | positional_parity::contract_cascade_byte_is_lgj_carving_register_index_xor_1_and_g4d3_group_sets_differ |
Open finding, no resolution here. lance_graph_contract::facet
FacetCascade::tier_bytes() lists each tier hi before lo, so
cascade_byte(shape, g, l) names register byte (g*D + l) XOR 1. lgj's
carvings read register byte g*D + l in storage order (little-endian within a
group; a sum cannot name a group, so the group is inferred from where the
observed level resets). For G6D2 and G3D4 the two readings name the same byte
set per group in swapped order; for G4D3 the group sets themselves differ
(contract group 0 is bytes {0,1,3}, lgj's is {0,1,2}). Neither side was
changed.
ndarray's masking facade finished growing (src/simd_masking_ops.rs, the
ergonomic tier of the three-layer SIMD contract). This minor consumes what it
grew — and the interesting half of the change is what it did not spend a
symbol on.
Fifteen facade capabilities landed in this crate. Three became symbols
(29 total, up from 26); seven became LgjOpDesc op-codes, which cost
nothing; five are substrate-tier kernels with no membrane exposure at all,
each with a stated reason and a stated condition for revisiting. §1 makes
symbol growth "a design smell to be argued for, not a default", so every row
below is the argument rather than a changelog.
| facade capability | how it lands | why |
|---|---|---|
mask_ternlog / mask_ternlog_assign |
symbol lgj_mask_ternlog |
the family's general member (§19.1) |
mask_xor / mask_xor_assign |
immediate 0x3C to that symbol |
a 3-input table subsumes it |
mask_not / mask_not_assign |
immediate 0x0F to that symbol |
likewise |
ternary_match_strided_to_mask |
symbol lgj_op_ternary_match |
24 bytes of parameter; no op-code fits (§19.2) |
masked_min_i32 / masked_max_i32 |
symbol lgj_reduce_i32 |
§15 mandated ONE parameterised reduce symbol (§19.3) |
ne_u32_to_mask |
op-code 3 |
LgjOpDesc.op already generalises predicates (§19.4) |
eq_i32 / ne_i32 / lt_i32 / le_i32 / ge_i32 |
op-codes 4–8 |
likewise |
ternary_match_u32_to_mask |
op-code 9, packed operand |
two u32s are exactly 64 bits |
ternary_match_u64_to_mask |
kernel only | 128 bits of parameter (§19.5) |
mask_any / mask_all |
kernel only | exactly derivable from lgj_mask_count (§19.5) |
blend_i32 |
kernel only | no resource carries two I32 lanes (§19.5) |
Every one of the fifteen has a kernel wrapper in kernels.rs regardless of
exposure. That is the Missing-capability STOP rule read in its own direction:
the substrate tier is where a capability lands first, and a symbol is a NAME
for something a backend already does (root CLAUDE.md, E5). A capability that
exists in the kernel and not at the membrane is a decision; one that has to be
invented at the membrane is the failure the rule prevents.
i32 lgj_mask_ternlog(u64 a, u64 b, u64 c, u64 dst, u8 imm)
dst = ternlog::<imm>(a, b, c), word-wise. imm is the 8-bit truth table in
the VPTERNLOG convention (index (a<<2)|(b<<1)|c, result bit
(imm >> index) & 1). Every value 0..=255 is legal, so there is no
unknown-immediate rejection path and no status for one.
| function | imm |
|---|---|
a & b |
0xC0 |
a | b |
0xFC |
a ^ b |
0x3C |
a & !b |
0x30 |
!a |
0x0F |
a & b & c |
0x80 |
| majority of three | 0xE8 |
Why this instead of lgj_mask_xor + lgj_mask_not + lgj_mask_maj3 + …
Because the alternative has no stopping point. XOR and NOT are the two the
mask algebra visibly lacked; MAJ3, (a&b)|c, (a|b)&c and 250 others are
equally real Boolean functions of three masks, and a membrane that mints a
symbol per truth table is a membrane that grows without bound. One symbol whose
parameter IS the truth table closes the family. This is also the op
.claude/plans/mask-risc-lowering-v1.md D-MRL-1a names, consuming
ogar_loco::TERNLOG = FnIndex(0x86)'s semantics — no mint, per that plan's
own v4.1 amendment.
The immediate is runtime at the membrane and compile-time at the facade,
and closing that gap is the implementation's only interesting decision. The
crate carries a 256-entry table of function pointers, one per monomorphisation
of ndarray::simd::mask_ternlog_assign::<IMM>. The tempting alternative —
decompose the immediate into its eight minterms and OR them word-wise — is
wrong on both counts that matter: it evaluates the truth table HERE, in ~24 word
ops instead of one VPTERNLOGQ per 512 bits, and it is a locally-written SIMD
abstraction, which §8 forbids outright. ndarray's POLYFILL LAW puts
truth-table specialisation inside the backend file; reaching the const generic
is what keeps it there.
Aliasing. dst may be any of a, b, c, or none, and every operand is
read as it was BEFORE the call. The mechanism is lgj_hop's, not
lgj_mask_and's: each operand is snapshotted under a READ lock that is fully
RELEASED before the next lock is taken, and only then is the single WRITE lock
on dst acquired. Never more than one lock at a time, so every aliasing case is
deadlock-free by construction rather than by case analysis — which is what
four handles need, where lgj_mask_andnot's three could be enumerated.
registry::lock_masks_ordered is deliberately not used: it holds at most three
entries, and more decisively it takes a WRITE guard on every one, which is how a
mask's memoised carving (§15) is invalidated — reading a/b/c through it
would silently discard three memos this operation does not touch.
The snapshots are a real cost, stated rather than hidden: up to three
mask-sized copies plus one pass. lgj_mask_and/or/andnot are therefore NOT
removed and NOT reimplemented on top of this — removal would not be an additive
minor, and each keeps a two-mask analysis that is cheaper for its own function.
Call them for AND/OR/ANDNOT; call this for everything else.
Tail. Bits at row index >= n_rows are zero on return, and here that clear
is load-bearing rather than defensive. The facade's contract is exact: the
result's tail is imm & 1 replicated, because every conforming input's tail is
zero and index 0 is the all-zero-inputs row of the table. So an odd imm
— NOT_A = 0x0F among them — sets every tail bit before the clear. A test
asserts that it does, so the clear is a measured requirement and not a
precaution that could be removed without anything going red.
Compatibility. All four masks must share the same parent and row count, or
MASK_LENGTH_MISMATCH — the same reading lgj_mask_and uses, extended from
three handles to four. The rule is unchanged; only the arity is.
i32 lgj_op_ternary_match(u64 res, u32 facet,
const u8* pattern, const u8* care, u64 dst_mask)
Overwrites dst_mask with ((register(row, facet) ^ pattern) & care) == 0
over the 12-byte content-blind register that follows each facet's classid.
This is the first bitwise-over-payload predicate this ABI has ever carried.
Every predicate before it compares a whole scalar field — a classid, a value, an
id — and .claude/plans/mask-risc-lowering-v1.md §1 records that absence
explicitly ("all scalar-valued, none bitwise over the payload"). care is what
makes the difference structural rather than incremental: it selects which BITS
must agree, so setting the leading bytes and clearing the rest turns the op into
a PREFIX test, and prefix containment is ancestry (OGAR CLAUDE.md's 3×4 canon;
rail_geometry.rs:178's is_ancestor_of). One call, one mask, the whole
subtree — which is the vertical axis that plan's mask trie stands on.
care all-zero matches every row (a deliberate total, not an error); care
all-ones is exact register equality.
Why a symbol and not an op-code. Its parameter is 24 bytes — a 12-byte
pattern and a 12-byte care mask. LgjOpDesc.operand is 64 bits. Widening the
descriptor would not be an additive change, and packing a pointer into an
integer operand would put a lifetime across a struct the plan evaluator copies.
It is the only capability in this minor whose parameter genuinely does not fit.
Layout. AosRows only. A facet's register is 12 CONTIGUOUS bytes there,
which is what makes one strided pass possible; FacetMajor (§18) deliberately
splits it into a lo64 region and a hi32 region far apart in the buffer.
Gathering it back per row would be the serialization this ABI exists to forbid,
so the answer is UNSUPPORTED_LAYOUT (-18) — the same deferral-stated-as-a-
status the register-sweep family already uses. Checked BEFORE the mask is
resolved, so dst_mask is provably untouched on a refusal.
The mask must belong to this store (§3.1), as for every export that takes a
mask beside a resource. Until minor 14 this predicate checked only the row
count, matching lgj_op_eq_classid as it then was.
Kernel. ndarray::simd::ternary_match_strided_to_mask, which lowers the
test to one ternlog::<XOR_AND> per 16 records plus a compare-against-zero —
never an XOR, then an AND, then a compare. The primitive owns bounds checking
(overflow-safe, up front) and the trailing-bits-zero guarantee, exactly as
eq_u32_strided_to_mask does for lgj_op_eq_classid.
i32 lgj_reduce_i32(u64 res, u32 lane_id, u32 reduce_op, u64 mask,
i64* out_value, u32* out_present)
reduce_op: 0 = SUM, 1 = MIN, 2 = MAX. Anything else is
UNKNOWN_OPCODE, never a silent fall back to SUM — an unknown reduction must
not alias a known one, the same argument §14 makes for an unknown carving.
§15 wrote this shape down before the need arose, and naming that is the point rather than a flourish:
if a second reduction is ever needed (min/max/count-distinct/histogram), do NOT add a second symbol. That is the point at which the operation should be generalised — an op-code parameter on one reduce symbol, mirroring how
lgj_plan_eval'sLgjOpDescalready generalises predicates — andsumbecomes op-code 0. Two reduction symbols would be the smell §1 warns about; one parameterised symbol is the shape this ABI already uses elsewhere.
Min and max ARE that second reduction. So this is one symbol, sum is op-code
0, and a future count-distinct or histogram is one more arm rather than
one more symbol.
lgj_reduce_sum_i32 is retained unchanged. Removing it would not be an
additive minor and a minor-1 Java is still entitled to it; reduce_op = 0
answers identically, pinned by a test so the two cannot drift. The §15 rule's
letter ("sum becomes op-code 0") is honoured; its one impossible clause
(retroactively deleting a shipped symbol) is not, and that substitution is
recorded here rather than left to be noticed.
out_present is not a formality. Min and max over an EMPTY population have
no answer, and every in-band sentinel is wrong: i32::MAX is a value a real
population can contain, and 0 is worse. out_present = 0 means "nothing
selected; *out_value is 0 and means nothing". SUM is always present,
because the sum of an empty population is 0 and that IS the answer — the same
distinction §15 draws when it refuses to report a zero-fallback carving for an
empty population.
Both outputs are written on LGJ_OK and neither on any failure, matching
lgj_reduce_facet_sum_resolved's two-output precedent. Widening to i64 is
the SUM's contract and exact for an i32 extremum, so one return type carries
all three without a lossy case.
Cost: O(mask_words + popcount) for every op. The mask-word scan is
unconditional, so an empty mask costs one pass rather than nothing — the cost
shape §14 already states for the register sweep, and §6's bulk rule holds by
the same reading.
LGJ_OP_NE_U32 = 3 // U32 lane
LGJ_OP_EQ_I32 = 4 // I32 lane
LGJ_OP_NE_I32 = 5
LGJ_OP_LT_I32 = 6
LGJ_OP_LE_I32 = 7
LGJ_OP_GE_I32 = 8
LGJ_OP_TERNARY_MATCH_U32 = 9 // U32 lane
Each is an LgjOpDesc.op value, reached through lgj_plan_eval /
lgj_plan_eval_scalar. Two consequences, both wanted:
- Fused for free. Six new predicates compose with each other and with the
existing two in ONE crossing, which is the property §6 exists to protect. Six
new
lgj_op_*symbols would have given the unfused form only, and a caller chaining them would pay a crossing each. - Unfused for free too.
n_ops = 1IS the unfused form: the accumulator starts all-set, soall ∩ op0 = op0exactly. Nothing is lost by not minting the symbols.
LGJ_OP_TERNARY_MATCH_U32 packs both halves into operand:
operand as u64 is (care << 32) | pattern. That is exact — two u32s are
exactly 64 bits — and it is a new reading of an existing field for a NEW op-code
only; every pre-existing op-code's reading of operand is untouched.
Both plan symbols gained scalar arms. An op-code with no scalar
implementation would make lgj_plan_eval_scalar answer UNKNOWN_OPCODE for
exactly the ops the plan evaluator was extended to cover — an asymmetry between
two symbols §7 says have "identical semantics", and it would quietly hollow out
the parity escape hatch. Each scalar arm is written as the predicate's own
definition (v <= t), never as a complement of its neighbour, so a facade that
lowered ge as a buggy complement is caught rather than agreed with.
Named so their absence is a decision on record rather than an oversight — §10's own convention, applied to this minor.
mask_any / mask_all — exactly derivable, so they buy nothing.
any is lgj_mask_count > 0; all is lgj_mask_count == n_rows, and a Java
Mask already holds its row count. Both cost ONE crossing either way, and both
are O(mask_words) either way — the facade's mask_any does not short-circuit,
it ORs every word, exactly as popcount_batch_u64 sums every word. A symbol
that is a rename of an existing answer at identical cost is the growth §1 names
as a smell. The kernels ship (a future fused plan's EXISTS terminal will want
the early-out shape); the membrane does not.
blend_i32 — no resource has two I32 lanes. A blend needs two of them.
The pattern fixture has exactly one (LANE_VALUES); the row store has none
(U8 raw, U32 classid, U64 lo64, U32 hi32). Every legal call would be
blend(m, values, values), which is values — a symbol whose only reachable
invocation is the identity. Condition to revisit, stated so it can fire: a
resource that carries two I32 lanes, or a measured need for the
constant-fallback form (dst[i] = mask[i] ? lane[i] : k), which is a different
primitive and would be named as one.
ternary_match_u64_to_mask — 128 bits of parameter. Its pattern + care
needs twice what LgjOpDesc.operand carries, so it cannot be an op-code without
growing the descriptor, which would not be additive. Nor does it earn the symbol
lgj_op_ternary_match earns: that one answers over the 12-byte V3 register,
which is where the prefix/ancestry question lives; a u64 TCAM would answer over
the ids lane, for which no caller exists. Condition to revisit: a caller
with a real care-masked query over a U64 lane — at which point the honest shape
is a pointer-taking symbol like §19.2's, not a widened descriptor.
mask_xor / mask_not — already reachable. Immediates 0x3C and 0x0F to
§19.1. A dedicated symbol for each would save one snapshot on the XOR path and
nothing at all on NOT, against two more symbols forever.
None of the three is lifecycle, and none is fixed-cost. A caller that doubles
n_rows observes roughly double the work in each: lgj_mask_ternlog twice the
mask words (and twice the snapshot bytes); lgj_op_ternary_match twice the
records scanned; lgj_reduce_i32 twice the mask-word scan and, on average,
twice the popcount. The seven op-codes inherit lgj_plan_eval's own
conformance unchanged. Same test every existing symbol passes.
Every guard this minor adds was verified by breaking it and watching the named test fail, then restoring. Seven runs:
| what was disabled | test that went red | observed |
|---|---|---|
the tail clear in mask_ternlog_impl |
an_odd_immediate_leaves_no_tail_bit_behind |
counted 127 of 130 rows instead of 65 — the 62 dead bits of the last word |
the 256-table index, transposed ([imm & 15][imm >> 4]) |
the_ternlog_dispatch_table_agrees_with_the_truth_table_for_all_256_immediates |
FAILED |
the AosRows gate in lgj_op_ternary_match |
ternary_match_rejects_null_bad_facet_wrong_kind_and_a_facet_major_layout |
FAILED |
out_present hardcoded to 1 |
reduce_i32_reports_an_empty_population_instead_of_inventing_an_extremum |
FAILED |
one op-code's scalar arm (le_i32 → UNKNOWN_OPCODE) |
every_minor_11_opcode_runs_on_both_plan_paths_and_they_agree |
FAILED |
| the packed TCAM operand's halves, swapped | the_tcam_opcodes_packed_operand_decodes_both_halves |
FAILED |
the a seed in mask_ternlog_impl (never snapshot a) |
mask_ternlog_answers_the_truth_table_in_every_aliasing_shape |
FAILED at imm=0x01, distinct dst |
Two of the seven passed on the first attempt, and both were defects in the CHECK rather than evidence about the guard. Recorded because the repo's own rules name this trap and it fired anyway:
- The tail disable inserted
if false { clear_tail_bits(…) }beside the real call instead of removing it. Theassert count == 1fired, so the EDIT happened — but the edit did not remove the guard. "A disable that does not apply is indistinguishable from a guard that is not load-bearing." - The aliasing disable flipped
if Arc::ptr_eq(&ed, &ea)toif false, which makes the code snapshotaALWAYS — strictly more conservative, so nothing could break. The knob did not bind.
Both were corrected to disables that provably apply (each now asserts the guard is textually ABSENT from the function body afterwards, not merely that a replacement occurred), and both then went red. The lesson is the one already on record and worth one more instance: assert what the disable REMOVED, never only that an edit landed.
i32 lgj_plan_group_sum_i32(u64 res, const LgjOpDesc* ops, u32 n_ops,
u32 group_lane, u32 val_lane,
u64 via_res, u32 via_lane,
i64* out_sums, u64 n_groups)
Every reduction this ABI carried until minor 11 consumed a mask: lgj_plan_eval
landed the plan's answer in a mask handle, and lgj_reduce_sum_i32 /
lgj_reduce_i32 / the register sweeps read that handle. Java never HELD the
selection — it lived natively — but it was still a population-sized thing that
existed only to be consumed by the very next fold, which is the intermediate
materialisation the fold algebra exists to remove (lance-graph #1256's ruling:
any intermediate population is prohibited if an addressable projection can be
consumed directly by the next fold). A GROUP BY multiplied it by the group
count: where(key.eq(g)).sumOf(value) per g, measured in the bricks
consumer at 32 crossings for 16 groups.
The plan is lowered exactly as lgj_plan_eval lowers it — the prefix rewrite
and the survivor skip of plan_lower — but the program ends in
Terminal::GroupSumI32 { mask: acc, key, val } instead of Terminal::Keep. The
executor runs it tile by tile over SLOTS × tile_words_for(rows) words of
scratch; for each tile the terminal folds val[i] into out_sums[key[i]] for
every selected row and moves on. Nothing population-sized exists at any point:
the accumulator is a tile, the sink is n_groups integers, and the crossing
returns when the last tile has folded.
via_res != 0 is the fk-keyed form. group_lane is then a foreign KEY into
via_res (another pattern resource) and the group of row i is
via_lane[group_lane[i]] — SUM(line.amount) GROUP BY partner.country in one
program, Terminal::GroupSumViaI32, with the indirection fused inside the
terminal: no partner-side mask, no remapped key lane, no second program. A key
that names no row of via_res drops the row (zero fallback at both hops,
mask_risc's contract). via_res may equal res.
n_ops == 0 is legal here and means every row. lgj_plan_eval refuses an
empty plan because its caller can fill the destination mask itself; a grouped
sum has no destination mask, so the whole-lane case is a program — the one
Pred::Range this crate emits, always 0..n_rows, pinned by
the_group_sum_range_is_the_whole_lane_and_nothing_else so that
exec_error_to_status's RangeOutOfBounds arm stays an internal-bug mapping.
out_sums[g] = Σ val_lane[i]over selected rowsiwith keyg, forg < n_groups; a selected row whose key is>= n_groupsnames no group and is dropped, never an error. Every element is written onOK(zero for a group no row names); none on any failure —execute_intovalidates the whole program before its first write.group_lanemust be aU32lane ofres,val_laneanI32lane ofres,via_laneaU32lane ofvia_reswhen given.- Statuses:
NULL_ARGUMENTfor a nullout_sums, a nullopswithn_ops > 0, orn_groups == 0(a zero-length sink is no sink);INVALID_HANDLE/WRONG_RESOURCE_KINDforresor a non-zerovia_resthat is not a live pattern; every plan defect aslgj_plan_evalreports it;INVALID_LANE/LANE_KIND_MISMATCHfor the three lanes;LENGTH_OVERFLOWpast2^32 - 1rows (Pred::Rangeand the sum carry are bothu32-bounded). No new status. - Bulk (§6):
O(rows)in one pass over the predicate lanes plus one read of the key and value lanes for the selected rows. No per-row and no per-group crossing.
The plan surface (LgjOpDesc) is reused unchanged, so the whole cost of the
capability is the terminal, and the terminal's two shapes (local key / key
through a second table) are one parameter (via_res) rather than two symbols
— the shape §15 mandated for the reductions. There is no
lgj_plan_group_sum_i32_scalar: parity is falsified in the crate against
mask_risc's row-at-a-time reference executor on the identical lowered
program (both key shapes, multi-tile), and through the membrane against the
two-crossing path it replaces — which runs a different kernel behind a
different terminal, so agreement is evidence rather than a tautology.
View.sumByGroup(key, value, groups) → GroupTotals, and
View.sumByGroupVia(key, via, viaKey, value, groups). GroupTotals is
addressed by key (total(g), groups()) and exposes no array — it is sized
by the question the caller typed, never by the data, which is the eighth named
materialisation site (Engine.groupSumI32's toArray, pinned in
DoctrineFenceTest). Measured: one crossing at 1,024 and at 65,536 rows
for 16 groups, beside the per-group path measured at 32 in the same run.
| what was disabled | test that went red |
|---|---|
the via key silently downgraded to the local key |
via_reads_the_second_table_through_the_key_lane |
the all-rows range emptied to 0..0 |
an_empty_plan_and_an_all_or_plan_both_group_every_row, the_group_sum_range_is_the_whole_lane_and_nothing_else, grouped_sums_agree_with_quack_over_the_combine_sweep |
the n_groups == 0 guard removed |
every_refusal_is_a_status_and_leaves_out_sums_untouched (mask-risc's own refusal surfaced as ALLOCATION_FAILED instead) |
Java: the toArray pin reverted to 1 |
DoctrineFenceTest — "UNFENCED MATERIALIZATION: Engine.java|.toArray( 2 (pinned 1)" |
Java: requirePositiveGroups made a no-op |
GroupSumTest — groups = 0 reached the membrane and came back as the ABI's NULL_ARGUMENT, not the Java exception |
Java: Engine passes viaResource = 0 always |
GroupSumTest — every via group g |
Each restored from the commit (the disable cycle runs only against committed
work) and re-run green. The compatibility direction was run for real, not
assumed: OldAbiCompatTest against a minor-11 library built from 07e044f
reports "View.sumByGroup (minor 12) reports an ABI mismatch, not a missing
symbol (threw AbiMismatchException)", with every minor-11 feature still
working beside it.
i32 lgj_plan_scalar(u64 res, const LgjOpDesc* ops, u32 n_ops,
u32 fold, u32 val_lane, i64* out_value)
lgj_plan_eval answers two things: it lands the selection in dst_mask and
returns its count. A caller that wants only a number still pays for the mask:
one bit per row written into a destination that is read once. A sum pays a
second crossing (lgj_reduce_sum_i32) to read that mask back. §20 removed this
for the grouped sum; the plain count and sum were still on the mask path.
lgj_plan_eval is unchanged. It remains the symbol for a caller that
demands the mask, and it still returns the count with it.
The plan lowers exactly as lgj_plan_eval lowers it: plan_lower::lower_scalar
reuses lower_plan's ops unchanged (pinned by
the_scalar_sum_range_is_the_whole_lane) and replaces only the terminal.
fold |
terminal | *out_value |
|---|---|---|
LGJ_FOLD_COUNT (0) |
Terminal::Count |
rows selected; val_lane ignored |
LGJ_FOLD_SUM_I32 (1) |
Terminal::MaskedSumI32 |
Σ val_lane[i] over selected rows, 0 if none |
The accumulator is a tile of scratch and the terminal folds each tile into the
running scalar (Out::None). No mask handle is named or written.
n_ops == 0 is legal and means every row, as in §20. A count over every row
(an empty plan, or one whose every combine is OR) is answered from the row
count without a program. A sum over every row uses the whole-lane
Pred::Range, 0..n_rows, the second and last Range this crate emits.
*out_valueis written only onLGJ_OK.- Statuses:
NULL_ARGUMENTfor a nullout_value, or a nullopswithn_ops > 0;UNKNOWN_OPCODEfor an unknownfold;INVALID_HANDLE/WRONG_RESOURCE_KINDforres; every plan defect exactly aslgj_plan_evalreports it (pinned againstlgj_plan_evalitself, defect by defect);INVALID_LANE/LANE_KIND_MISMATCHforval_laneunder a sum;LENGTH_OVERFLOWfor a sum past2^32 - 1rows. No new status. - Bulk (§6): one pass,
O(rows).
There is none. View.count() and View.sumOf(field) keep their signatures and
call this symbol when the loaded library reports minor ≥ 13. Against an older
library they keep the mask path, so neither is gated: both answer on every
minor. Run against a minor-12 library built from this repo's history and
against minor 13, OldAbiCompatTest reports the same three numbers (count 71,
filtered sum 6257, whole-lane sum 111296), in 2 crossings and 1.
Parity: scalar_fold.rs compares the symbol with the mask path, with
mask-risc's row-at-a-time reference on the same program (several tiles), and
with a hand walk over the fixture arrays, across the {AND, OR}^n sweep at
1,000 and 65,536 rows.
| mask path | scalar fold | |
|---|---|---|
crossings, count() |
1 | 1 |
crossings, sumOf() |
2 | 1 |
| mask bytes written per call | 8 × ceil(rows / 64) (8 KiB at 65,536 rows) |
0 |
native mask resources count()/sumOf() need |
a scratch mask, and an all-rows mask for an unfiltered sum | none |
| Rust allocation per call (3 ops) | 240 B, independent of rows | 240 B, independent of rows |
Native latency, examples/plan_scalar_cost.rs, medians of 201, two runs, no JVM
in the numbers:
| rows | plan | count: mask → fold | sum: mask → fold |
|---|---|---|---|
| 1,024 | class==7 AND value>100 |
389–463 → 328–407 ns | 464–564 → 340–406 ns |
| 65,536 | same | 12.4–16.1 → 12.3–17.0 µs | 14.5–18.8 → 14.1–18.3 µs |
| 65,536 | value>100 |
4.8–6.3 → 4.7–6.1 µs | 14.3–19.1 → 13.9–17.3 µs |
| 1,048,576 | class==7 AND value>100 |
386–514 → 467–481 µs | 647–664 → 607–623 µs |
| 1,048,576 | value>100 |
186–187 → 181–183 µs | 413–423 → 313–337 µs |
The count is not faster within run-to-run noise: the predicate pass dominates and the mask write is small beside it. The sum is 3–25% faster. What this symbol removes is the undemanded mask write, the second crossing of a sum and the two helper mask resources; it is not a large speed-up.
| what was disabled | test that went red |
|---|---|
the all-rows Range emptied to 0..0 |
an_empty_plan_and_an_all_or_plan_fold_every_row, count_and_sum_match_the_mask_path_and_the_hand_walk, the_scalar_sum_range_is_the_whole_lane |
the all-rows count answered 0 |
an_empty_plan_and_an_all_or_plan_fold_every_row, count_and_sum_match_the_mask_path_and_the_hand_walk |
out_value written before validation |
every_refusal_is_a_status_and_leaves_out_value_untouched |
the fold check removed |
every_refusal_is_a_status_and_leaves_out_value_untouched |
| the sum lowered to a count terminal | count_and_sum_match_the_mask_path_and_the_hand_walk, an_empty_selection_is_zero_not_absent, the_scalar_sum_range_is_the_whole_lane |
| plan validation skipped | plan_defects_are_reported_as_lgj_plan_eval_reports_them |
The last row was green on its first run: the executor refuses most defective
plans by itself, with the same status. The test that pins it compares statuses
with lgj_plan_eval for a lane index past u16 and an undefined combine,
which only the shared validation catches.