Retain cache-hit assertions with generation-triggered source revalidation

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
This commit is contained in:
atharvranjan committed 2026-11-24 22:10:24 -06:00
1 parent b5b646a58d
commit 44ac976291
4 files changed
+42 -28

No files matched your search

+1 -1
View File
@@ -33,7 +33,7 @@ remains unsupported.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Fixed
- Replaced per-byte DBT cache validation with a constant-time executable-generation token that distinguishes cloned address spaces and changes on executable mappings and writes, including loader bypass writes. Non-executable data writes keep translations cached. The differential harness restores data within one address space for its warm-cache checks, preserving its state and cache assertions. Same-dispatch self-modification and reclamation of discarded native blocks remain unsupported; regression tests pin cache exhaustion.
- DBT cache hits now compare an executable-generation token instead of rereading every instruction byte. Address-space or executable-memory changes trigger byte and execute-permission revalidation before a translation can be reused; changed code is retranslated. Ordinary data writes retain the fast path. Tests cover cloned spaces, loader bypass writes, split writes, remapping and bounded cache exhaustion. Same-dispatch self-modification and discarded-code reclamation remain unsupported.
- The DBT no longer runs a stale translation after the guest rewrites its own code or runs against a different address space (#84). Each cached block now keeps the guest bytes it was translated from and is compared with the current executable bytes on every lookup; a mismatch, or bytes that are no longer readable, discards the block and translates it again, counted in the new `DbtMetrics::blocks_invalidated`. This makes the `cpu_known_answers` self-modifying-code case pass for the DBT, so it is no longer ignored as a known defect, and regression tests cover a rewritten block, a rewritten final byte, a budget-limited block and a second address space. The discarded native code stays in the JIT cache until cache reclamation exists (#99), and a store into a block's own later instructions during the same dispatch is not detected. Local verification only; not independently reviewed.
- Non-canonical 64-bit guest data addresses now raise `#GP` instead of a memory fault in both the interpreter and native DBT, including accesses that cross the canonical-address boundary. The synthetic architectural test is enabled again.
- Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing.
+31 -10
View File
@@ -29,8 +29,8 @@ pub struct DbtMetrics {
pub blocks_compiled: usize,
pub cache_hits: usize,
pub cache_misses: usize,
/// Cached blocks discarded after their address space or executable-memory
/// generation changed. Each also counts as a cache miss.
/// Cached blocks discarded because their guest bytes or executable mappings
/// changed. Each also counts as a cache miss.
pub blocks_invalidated: usize,
pub native_bytes_emitted: usize,
pub dbt_dispatches: usize,
@@ -44,17 +44,30 @@ pub struct DbtMetrics {
///
/// Guest stores into executable memory (Intel SDM Vol. 3A 11.6), executable
/// mapping changes and another address space invalidate the retained token.
/// Checking it is constant-time and does not reread every instruction byte.
/// An unchanged token takes a constant-time check. After a generation or address
/// space change, bytes and execute permissions are revalidated once before an
/// identical translation may be reused in that generation.
/// Validation occurs at dispatch boundaries: a store into the currently running
/// block's later instructions still needs a separate dispatch-boundary design.
struct CachedBlock {
code: *const u8,
generation: Arc<()>,
start: u64,
source: Box<[u8]>,
}
impl CachedBlock {
fn is_current(&self, memory: &GuestMemory) -> bool {
memory.code_is_current(&self.generation)
fn is_current(&mut self, memory: &GuestMemory) -> bool {
if memory.code_is_current(&self.generation) {
return true;
}
if !self.source.iter().enumerate().all(|(offset, &byte)| {
matches!(memory.fetch_instruction_byte(self.start.wrapping_add(offset as u64)), Ok(current) if current == byte)
}) {
return false;
}
self.generation = memory.code_generation();
true
}
}
@@ -264,7 +277,7 @@ impl DbtEngine {
block_limit: usize,
) -> Result<*const u8, ExitReason> {
if block_limit == MAX_BLOCK_INSTRUCTIONS {
if let Some(cached) = self.block_cache.get(&rip) {
if let Some(cached) = self.block_cache.get_mut(&rip) {
if cached.is_current(memory) {
self.metrics.cache_hits += 1;
return Ok(cached.code);
@@ -280,7 +293,7 @@ impl DbtEngine {
// Keep budget-limited blocks separate so they cannot shorten a later run.
let key = (rip, block_limit);
if let Some(cached) = self.limited_block_cache.get(&key) {
if let Some(cached) = self.limited_block_cache.get_mut(&key) {
if cached.is_current(memory) {
self.metrics.cache_hits += 1;
return Ok(cached.code);
@@ -378,10 +391,16 @@ impl DbtEngine {
.map_err(|_| ExitReason::JitCacheExhausted)?;
self.metrics.blocks_compiled += 1;
self.metrics.native_bytes_emitted += asm.instructions().len() * 4;
let source = (0..rip.wrapping_sub(start_rip))
.map(|offset| memory.fetch_instruction_byte(start_rip.wrapping_add(offset)))
.collect::<Result<Box<[u8]>, _>>()
.map_err(ExitReason::MemoryFault)?;
self.decoded_blocks.push(insns);
Ok(CachedBlock {
code: emitted,
generation: memory.code_generation(),
start: start_rip,
source,
})
}
}
@@ -1655,7 +1674,7 @@ mod tests {
}
#[test]
fn cloned_address_spaces_have_independent_code_generations() {
fn cloned_address_spaces_diverge_when_executable_code_changes() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
let mut cloned = memory.clone();
@@ -1663,8 +1682,10 @@ mod tests {
memory.write_u8(ENTRY + 1, 7).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut cloned, 16), 1);
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 7);
assert_eq!(engine.metrics.blocks_compiled, 3);
assert_eq!(engine.metrics.cache_hits, 1);
// A deep clone shares the proven identical executable snapshot. The
// write in the original space must still force retranslation there.
assert_eq!(engine.metrics.blocks_compiled, 2);
assert_eq!(engine.metrics.cache_hits, 2);
}
#[test]
+5 -4
View File
@@ -121,9 +121,10 @@ impl MappedRegion {
/// Guest virtual memory address space.
#[derive(Default)]
pub struct GuestMemory {
// A retained token identifies both this address space and its executable
// generation. Cached translations retain their token, so allocator address
// reuse cannot make an obsolete generation compare equal to a new one.
// A retained token identifies a validated executable snapshot. Independent
// address spaces get distinct tokens. A deep clone may share its identical
// snapshot; an executable mutation detaches only the changed address space.
// Cached translations retain tokens, preventing allocator-address reuse.
executable_generation: Arc<()>,
regions: Vec<MappedRegion>,
private_heaps: std::collections::BTreeSet<u64>,
@@ -137,7 +138,7 @@ pub struct GuestMemory {
impl Clone for GuestMemory {
fn clone(&self) -> Self {
Self {
executable_generation: Arc::new(()),
executable_generation: Arc::clone(&self.executable_generation),
regions: self.regions.clone(),
private_heaps: self.private_heaps.clone(),
private_heap_serial: self.private_heap_serial,
+5 -13
View File
@@ -200,24 +200,16 @@ impl Case {
compare("DBT (1 step)", result, &translated_memory, 1, offset);
}
// Exercise native block lowering, then reuse the same address space
// with its data restored. A new address space is intentionally a cold
// cache input, even when it has identical code at identical addresses.
// Exercise native block lowering and then reuse those blocks with a
// fresh copy of the guest input and memory at the same addresses.
let mut dbt = DbtEngine::new(128 * 1024).unwrap();
let mut memory = self.memory();
let result = Interpreter::new(self.initial.cpu.clone(), &mut memory, BUDGET).run();
compare("interpreter", result, &memory, BUDGET, 0);
let mut translated_memory = self.memory();
let mut run_full = |engine| {
translated_memory
.write_bytes(DATA, &self.initial.data)
.unwrap();
let result = dbt.run(
&mut self.initial.cpu.clone(),
&mut translated_memory,
BUDGET,
);
compare(engine, result, &translated_memory, BUDGET, 0);
let mut memory = self.memory();
let result = dbt.run(&mut self.initial.cpu.clone(), &mut memory, BUDGET);
compare(engine, result, &memory, BUDGET, 0);
dbt.metrics
};
let cold = run_full("DBT (cold)");