#1 [high] PR #659 subtraction lens — diff shape and key line numbers
PR #659 head 16e2247, +196/-33, 3 files (docs/runtime-core-design.md, helios/src/runtime_core/cache_memory.rs, helios/src/runtime_core/memory.rs).
New/changed code sites (verified by reading the diff + files at PR head):
- cache_memory.rs:60-66 Layout { alignment, fixed_bytes, sentinel_granules, chunks, aliases }
- cache_memory.rs:68-71
sentinel_saved_bytes(row_bytes, alignment) = (row_bytes/alignment).saturating_sub(1)*alignment - cache_memory.rs:81-112 handle_charge (new
fixed_chargeblock 82-102: nested checked_add/and_then, 4 sites of the sameinvalid("mapping handle count overflow")) - cache_memory.rs:259-262
let sentinel_granules = match row_bytes / row_alignment { n if n > 1 => n, _ => 0 }; - cache_memory.rs:484-488 pack_prefixes copies sentinel_granules into the new Layout
- cache_memory.rs:1416-1447 allocate_shared_cache:
if sentinel_granules > 1 { multi-address map_cache_chunk for g granules; if fixed_bytes > sentinel_bytes { map tail } } else { map fixed_bytes } - cache_memory.rs:1467-1488 the SAME three-branch structure repeated for zeroing (cuMemsetD8_v2)
- cache_memory.rs:1500-1534 map_cache_chunk(bytes, &[(name, addr, len)]) — already supports one handle mapped at many addresses, pushes each into Storage.mappings; physical handle released after mapping, so handles alive = #map_cache_chunk calls and mappings = sum of slice lens.
- cache_memory.rs:818-834 DCP16 fixture assertions now 494848 / 647816 / 518504
- cache_memory.rs:1366-1385 new CPU test sentinel_row_aliases_full_granules_onto_one_page
- cache_memory.rs:1210-1237 GPU test: row 0 special-cased to zeros in
expected, then.skip(1)on the upload loop - memory.rs:357-381 existing
bytes(core, capacity, units)(pads units*unit_bytes up to alignment) - memory.rs:383-414 new
row_backing_bytes— near-copy ofbytes - memory.rs:486, 510, 523, 1003, 1249 call sites switched to row_backing_bytes
- memory.rs:576-579 virtual span kept on bytes() (mapped = bytes(core,0,execution) + borrowed)
- memory.rs:2027-2049 new CPU test sentinel_row_savings_increase_kv_page_capacity
- docs/runtime-core-design.md:770-780 new spec paragraph; :829-833 518,504 handles / 5,784 / 1.1%
#2 [high] Arithmetic facts supporting the simplifications
Identities that make the new code collapsible:
-
sentinel_saved_bytes(row, align) = (row/align - 1)*alignIS the row padding: padded(row) - row = ceil(row/align)*align - row = align - row%align. For row%align == 0: saved = row - align = padded - row. For row%align > 0: saved = floor(row/align)*align = padded - row. So saved == padding(row) always. Consequence: for units >= 1,padded(units*row) - saved == (units-1)*row + alignfor every row (nounits > 1restriction needed: units=1 gives exactly align). ⟹row_backing_bytes(core, units) == bytes(core, 0, units) - Σ pad(s.unit_bytes, align)for units >= 1, and == 0 for units == 0 (bytes() also returns 0). ⟹ everything row_backing_bytes does (incl. theunits > s.maximumcheck and the overflow-checked padding) is already inbytes()at memory.rs:357-381; only the subtraction is new. -
Physical slices in allocate_shared_cache:
- aliased region = [row.address, row.address + min(sentinel_granules*alignment, fixed_bytes)), stride alignment, len min(alignment, fixed_bytes)
- tail = [row.address + min(sentinel_bytes, fixed_bytes), row.address + fixed_bytes), len fixed_bytes.saturating_sub(sentinel_bytes)
These two descriptions are valid for sentinel_granules <= 1 as well (sentinels = min(1, ...) = 1 granule of len min(align, fixed) covering the whole fixed span, tail empty) ⟹ the
elsebranches at cache_memory.rs:1438-1447 and 1483-1488 are dead derivable code. Row 0 always lies wholly inside the fixed span: fixed_bytes = padded(executionrow) >= row for execution >= 1 (capacities() requires execution >= 1; 1 + activewidth in memory.rs:1003).
-
handle_charge per row-0 region: each physical handle costs 1 handle + (#addresses in its map_cache_chunk slice) mappings. Aliased handle = 1 + sentinel_granules*row_readers; tail handle = 1 + row_readers; no-alias = 1 + row_readers. Current code (cache_memory.rs:82-102) hard-codes this instead of deriving it from the same decomposition.
#3 [high] Corrected arithmetic backing the two main simplifications
CORRECTION to my first arithmetic note (the "saved == padding" claim was WRONG; verified by hand below).
Let align=A, row = q*A + r with 0 <= r < A, units >= 1.
- span = padded(unitsrow) = ceil(unitsrow/A)*A (this is exactly what memory.rs:399-404 and bytes():371-376 compute)
- saved = (q - 1)*A for q >= 2; 0 otherwise (sentinel_saved_bytes, cache_memory.rs:69-71)
- row_backing_bytes returns span - saved. Examples verified: row = 82_143_488 (q=39, r=354_560), units=2 → span=165_675_008 (158 MiB), saved=38A=79_691_776, result 85_983_232 (82 MiB) — matches the new test at memory.rs:2037-2038 and the PR description. Physical backing actually created in allocate_shared_cache = 1 shared page (A) + tail (fixed_bytes - qA) = span - (q-1)*A ✓ consistent. units == 0 → 0 (code skips the subtraction; bytes() also returns 0). multiple capacity-0 allocations each subtract their own saved → identical fold.
⟹ row_backing_bytes(core,units) == bytes(core,0,units) - Σ_over capacity-0 allocs sentinel_saved_bytes(unit, alignment) (for units >= 1)
⟹ the whole body of row_backing_bytes (max check, checked_mul, +align-1, /align*A, overflow errors) is byte-for-byte the body of bytes() (memory.rs:357-381). Only the subtraction is new. Suggested replacement:
fn row_backing_bytes(core: &Core, units: u64) -> Result { if units == 0 { return Ok(0); } let saved: u64 = core.allocations.iter() .filter(|a| a.sizing.as_ref().is_some_and(|s| s.capacity == 0)) .map(|a| sentinel_saved_bytes(a.sizing.as_ref().unwrap().unit_bytes, a.alignment as u64)) .sum(); bytes(core, 0, units).map(|span| span - saved) } (span >= 2A whenever units >= 1 and q >= 1 because ceil(unitsrow/A) >= q+1; subtract can't underflow. Use saturating_sub if paranoid.)
SECOND CORRECTION (unified-slice claim): for row < A (q = 0) the shared page CANNOT be aliased because row 0's only granule also holds row 1's start — so sentinels == 0 must stay "one handle over the whole fixed span". The valid unification is:
let page = if sentinels == 0 { fixed_bytes } else { alignment }; // per-mapping length AND address stride
let count = sentinels.max(1);
map_cache_chunk(page, &(0..count).map(|i| (row.name, row.address + ipage, page)).collect::<Vec<_>>())?;
let tail = fixed_bytes - pagecount; // sentinels==0 → 0
if tail > 0 { map_cache_chunk(tail, &[(row.name, row.address + pagecount, tail)])?; }
Check: sentinels==0 → page=fixed, count=1, tail=0 → exactly one call over the whole span = old behaviour, same handle count. sentinels=n>=2 → n mappings of len A over [0,nA), tail = fixed - n*A >= 0. Zeroing collapses the same way (zero(page) once, zero(tail) once). This deletes the duplicated if sentinel_granules > 1 {…} else {…} blocks at cache_memory.rs:1417-1447 and 1468-1488 and the >1 vs >0 inconsistency.
#4 [high] Findings: row_backing_bytes dup, triplicated branch, GPU test churn
FINDING 1 (high). row_backing_bytes (memory.rs:383-414, 32 new lines) re-implements bytes (memory.rs:357-381) verbatim — same capacity filter, same units > s.maximum error, same checked_mul + (align-1) / align * align padding, same "cache allocation size overflow" — and differs only by the - saved subtraction.
Verbatim current (memory.rs:394-413):
.try_fold(0u64, |total, (a, s)| {
if units > s.maximum {
return Err(invalid("cache capacity exceeds its virtual extent"));
}
let align = a.alignment as u64;
let span = units
.checked_mul(s.unit_bytes)
.and_then(|n| n.checked_add(align - 1))
.ok_or_else(|| invalid("cache allocation size overflow"))?
/ align
* align;
let saved = if units > 0 {
super::cache_memory::sentinel_saved_bytes(s.unit_bytes, align)
} else {
0
};
total
.checked_add(span - saved)
.ok_or_else(|| invalid("cache allocation size overflow"))
})
vs bytes (memory.rs:367-380) with .filter(|s| s.capacity == capacity) and no saved.
Replace whole fn body with:
fn row_backing_bytes(core: &Core, units: u64) -> Result<u64> {
if units == 0 {
return Ok(0);
}
let saved: u64 = core
.allocations
.iter()
.filter_map(|a| a.sizing.as_ref().filter(|s| s.capacity == 0).map(|s| (a, s)))
.map(|(a, s)| super::cache_memory::sentinel_saved_bytes(s.unit_bytes, a.alignment as u64))
.sum();
bytes(core, 0, units).map(|span| span - saved)
}
Equivalence: identical fp0; span - saved cannot underflow for units>=1 (span >= row + align > saved). All 5 call sites (memory.rs:486, 510, 523, 1003, 1249) unchanged.
FINDING 2 (high). allocate_shared_cache writes the same three-case decomposition three times, and handle_charge a fourth:
- handle_charge cache_memory.rs:82-102 (21 lines, 4×
ok_or_else(|| invalid("mapping handle count overflow"))) - mapping cache_memory.rs:1416-1447 (32 lines,
if sentinel_granules > 1 { multi-map; if fixed > sentinel { tail } } else { one span }) - zeroing cache_memory.rs:1467-1488 (22 lines, same shape) One derived description replaces all three:
let count = layout.sentinel_granules.max(1); // shared handle's mapping count
let granule = if count > 1 { layout.alignment } else { layout.fixed_bytes }; // sentinels<=1 => whole span
let tail = layout.fixed_bytes - granule * count; // 0 for sentinels<=1
handle_charge equivalence (n = sentinel_granules, tail>0 ⟺ n>=2 && nA < fixed):
fixed_charge = 1 + tail? + row_readers * (count + tail?) reproduces today's 1+row_readers (n<=1) and 1+nrow_readers (+1+row_readers when tail) exactly.
FINDING 3 (medium). GPU test churn cache_memory.rs:1212-1225: row 0 special-cased INSIDE the pattern closure (+11 lines, nested if/else). Just:
let mut expected: Vec<Vec<u8>> = (0..7).map(/* original closure untouched */).collect();
expected[0] = vec![0; geometry.row.unit_bytes as usize]; // null sentinel row stays zero
keeps the .skip(1) upload and the single assert!(contents == expected[row]) check, -11/+2 lines, and the pattern stays one expression.
No dead flags/knobs/fallbacks introduced: every new symbol (sentinel_granules, sentinel_saved_bytes, both tests, both doc hunks) is used.
#6 [high] Research summary
Subtraction/Simplicity review of PR #659 done. The diff is honest and mostly lean (+196/−33, two new CPU tests, no flags/knobs/fallback layers, no AGENTS.md structural violation), but three concrete cuts are available, all recorded in the scratchpad with verbatim quotes.
-
row_backing_bytes(memory.rs:383-414) is a 32-line copy ofbytes(memory.rs:357-381) — same capacity filter, sameunits > s.maximumerror, samechecked_mul + (align-1) / align * alignpadding, same overflow messages; only the- savedterm is new. Replace the body withbytes(core, 0, units).map(|span| span - saved)plus asavedfold, keeping all five call sites. -
The null-row decomposition is written three times in one file —
handle_charge(cache_memory.rs:82-102, four identical overflow closures), the mapping block (1416-1447) and the zeroing block (1467-1488) each special-casesentinel_granules > 1/ tail / else. One derived description (count = sentinels.max(1),granule = if count > 1 { alignment } else { fixed_bytes },tail = fixed - granule*count) reproduces today's handle counts exactly (1 + row_readersforn <= 1;1 + n*row_readers [+ 1 + row_readers]otherwise) and collapses bothelsebranches, which are determinable code, not real cases. -
The GPU test edit adds a branch inside a closure (cache_memory.rs:1212-1225): row 0 is special-cased inside the pattern generator, +11 lines. Assigning
expected[0] = vec![0; …]after the unchanged closure is −11/+2 and keeps the singlecontents == expected[row]assertion.
Lower-value: the sentinel_* names are a second word for the repo's existing "null row" (docs already say "null row zero"), and sentinel_granules is derivable at its only allocation site. Nothing dead was introduced.
#7 [high] Verbatim quotes for finding 2 (triplicated decomposition) — needed to write the report
Finding 2 needs three verbatim quotes. All at PR head 16e2247.
(a) handle_charge, cache_memory.rs:81-102 (21 new lines):
fn handle_charge(&self, row_readers: u64, plane_readers: &[u64]) -> Result<u64> {
let fixed_charge = if self.sentinel_granules > 1 {
let sentinel_bytes = self.sentinel_granules * self.alignment;
let sentinel = 1u64
.checked_add(
self.sentinel_granules
.checked_mul(row_readers)
.ok_or_else(|| invalid("mapping handle count overflow"))?,
)
.ok_or_else(|| invalid("mapping handle count overflow"))?;
if self.fixed_bytes > sentinel_bytes {
sentinel
.checked_add(1)
.and_then(|n| n.checked_add(row_readers))
.ok_or_else(|| invalid("mapping handle count overflow"))?
} else {
sentinel
}
} else {
1u64.checked_add(row_readers)
.ok_or_else(|| invalid("mapping handle count overflow"))?
};
Replacement (one line, after introducing the two derived quantities below):
let fixed_charge = 1
+ u64::from(tail > 0)
+ row_readers * (count + u64::from(tail > 0));
(b) mapping, cache_memory.rs:1416-1447:
let sentinel_bytes = layout.sentinel_granules * layout.alignment;
if layout.sentinel_granules > 1 {
let mappings: Vec<_> = (0..layout.sentinel_granules)
.map(|i| {
(
geometry.row.name.as_str(),
geometry.row.address + i * layout.alignment,
layout.alignment,
)
})
.collect();
self.map_cache_chunk(layout.alignment, &mappings)?;
if layout.fixed_bytes > sentinel_bytes {
self.map_cache_chunk(
layout.fixed_bytes - sentinel_bytes,
&[(
geometry.row.name.as_str(),
geometry.row.address + sentinel_bytes,
layout.fixed_bytes - sentinel_bytes,
)],
)?;
}
} else {
self.map_cache_chunk(
layout.fixed_bytes,
&[(
geometry.row.name.as_str(),
geometry.row.address,
layout.fixed_bytes,
)],
)?;
}
Replacement:
let count = layout.sentinel_granules.max(1);
let granule = if count > 1 { layout.alignment } else { layout.fixed_bytes };
let mappings: Vec<_> = (0..count)
.map(|i| (geometry.row.name.as_str(), geometry.row.address + i * granule, granule))
.collect();
self.map_cache_chunk(granule, &mappings)?;
let tail = layout.fixed_bytes - granule * count;
if tail > 0 {
self.map_cache_chunk(tail, &[(geometry.row.name.as_str(), geometry.row.address + granule * count, tail)])?;
}
(c) zeroing, cache_memory.rs:1467-1488:
// Zero each physical byte once, before any graph or transfer can read an alias.
if layout.sentinel_granules > 1 {
self.driver.check(
"cuMemsetD8_v2",
(self.driver.zero)(geometry.row.address, 0, layout.alignment as usize),
)?;
if layout.fixed_bytes > sentinel_bytes {
self.driver.check(
"cuMemsetD8_v2",
(self.driver.zero)(
geometry.row.address + sentinel_bytes,
0,
(layout.fixed_bytes - sentinel_bytes) as usize,
),
)?;
}
} else {
self.driver.check(
"cuMemsetD8_v2",
(self.driver.zero)(geometry.row.address, 0, layout.fixed_bytes as usize),
)?;
}
Replacement: same granule / tail values, two unconditional-if calls:
self.driver.check("cuMemsetD8_v2", (self.driver.zero)(geometry.row.address, 0, granule as usize))?;
if tail > 0 {
self.driver.check("cuMemsetD8_v2", (self.driver.zero)(geometry.row.address + granule * count, 0, tail as usize))?;
}
NOTE for the report: in (b) and (c) granule/count/tail must be computed before the mapping block and reused by the zeroing block (which is ~20 lines later, same function, no ? in between other than map calls — so hoisting is trivial). In (a) the same count/tail can be computed as let count = self.sentinel_granules.max(1); let tail = self.fixed_bytes - if count > 1 { self.alignment * count } else { self.fixed_bytes };.
Careful wording: this is a maintainability proposal (one description of the null-row physical slices used by handle accounting, mapping and zeroing), NOT a correctness bug; do not present the > 1 vs > 0 boundary as a bug — n == 1 is already filtered to 0 at cache_memory.rs:259-262, so both spellings agree today.
#5 [medium] Lower-value notes: derivable field, naming drift, no AGENTS violations
Lower-value observations (mention briefly, not as headline findings):
- cache_memory.rs:259-262
let sentinel_granules = match row_bytes / row_alignment { n if n > 1 => n, _ => 0 };is a 4-line spelling of.max(2).filter-style logic; could beif row_bytes / row_alignment > 1 { row_bytes / row_alignment } else { 0 }or simply store nothing and derive. Deriving removes the field + the copy in pack_prefixes (cache_memory.rs:487) — but Layout::grouped already has row_bytes in scope; the field only exists because allocate_shared_cache doesn't get geometry.row.unit_bytes… actually it DOES (geometry.row.unit_bytes, used at 1214). So the field is redundant:let granules = geometry.row.unit_bytes / layout.alignment / ...hmm — careful:geometry.row.unit_bytes / alignmentequals row_bytes/row_alignment exactly (row_bytes := geometry.row.unit_bytes at cache_memory.rs:156). So sentinel_granules is fully derivable at the one allocation site and in handle_charge could be passed as an argument. Do NOT overclaim: handle_charge is called from compact paths with no geometry, so the field is the cheaper route; treat as low-value/nit. saturating_sub(1)at cache_memory.rs:70 is unreachable defensive code: callers only use it for continuation allocations with unit_bytes >= align? Not guaranteed — memory.rs:405-409 calls it for EVERY capacity-0 allocation, but those are validated to be exactly one (memory.rs:481-485rows.len() != 1error). So reachable with row < align (real: GPU test uses 3*A/2; unaligned test uses 81_464_576). Keep.- Naming drift: "sentinel" is new vocabulary for what the repo/docs call the "null row" (docs/runtime-core-design.md:772-778 says "null row zero"; the PR body says "null continuation row zero").
sentinel_granules,sentinel_saved_bytes,sentinel_row_*tests introduce a second name for the same object in the same file that already says "null". Renaming to null_row_* would align with existing prose. Minor. - No AGENTS.md structural violation found: no env var, no flag, no per-model branch, no new abstraction/fallback layer; compatibility claim matches (no format.rs/Protobuf/CLI/metric file touched). The diff is otherwise lean: +196/-33 with 2 new tests, and the shim/fall-through for sentinels<=1 is a determinable case, which is exactly finding 2.
- One duplication NOT introduced by this PR but relevant:
bytes(core, 0, …)at memory.rs:576/578 is the virtual-span arithmetic; if finding 1 is applied the pair (bytesfor virtual,bytes - savedfor physical) becomes 2 lines apart and obviously intentional — supports finding 1 rather than criticizing 576/578.