serve: the per-round checks over the whole token history examine only the tokens appended since the last round
Five passes over up to 262,144 i32 ran on the host every round: the controller's validate_current and the ledger's begin_window each compared `committed` with `consumed`, with_sampling authenticated them twice more and range-checked the whole tail, after_verified range-checked `consumed` once more. In the speedtrain-ab spans the host work outside the GPU grows linearly with the context: window.sampling_setup 0.021 ms at 45k to 0.112 ms at 247k, the un-spanned part of verify_commit 0.038 to 0.098 ms, of finish_round 0.024 to 0.068 ms (about 0.19 ms per round at 247k, 1.3 % of a round, all of it before a launch or after a read-back). `token_memo::PrefixMemo` remembers (address, length, first/middle/last token, criterion) of the buffer a check last passed over; the next check starts at that length, and every 32nd use examines everything again. `consumed` (reserved at the request's start) and `committed` only ever grow within a request, so a pass over the first n tokens stays true for them. Ledger, penalty history and controller each own a memo; a request has its own ledger and controller request, so nothing carries across requests. Output identity argument: these are assertions between two host copies of the same tokens. A passing check is the same answer as before; a new token that differs, a different length, another buffer or a rewritten first/middle/last token fails exactly as before; a rewrite of any other old token, which no owner can do (both vectors are append-only inside their owner), would be reported up to 32 rounds later instead of at once. Nothing the GPU runs reads these results. Tests: token_memo (tail-only examination, address/length/criterion/probe reset, periodic full pass, random growth against the slice comparison), ledger (100 rounds of growth, newest-token mismatch, length mismatch, rewritten old token found within FULL_EVERY, copy at another address), the existing controller/engine suites (99 tests) pass. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
3cf185a34a
commit
2f267df973
@@ -73,6 +73,8 @@ pub(crate) mod original_serve_engine;
|
||||
pub(crate) mod original_spec_draft;
|
||||
pub(crate) mod original_spec_policy;
|
||||
pub(crate) mod original_spec_suffix;
|
||||
// Per-round checks over the whole token history, proportional to what was appended since the last round.
|
||||
pub(crate) mod token_memo;
|
||||
|
||||
#[cfg(all(any(target_os="linux",target_os="windows"),target_arch="x86_64"))]
|
||||
pub(crate) mod original_cache_startup;
|
||||
|
||||
@@ -1061,7 +1061,7 @@ mod tests {
|
||||
let mut v=e.verify(2,&[a],&p[..2]).unwrap();
|
||||
let outs=e.outputs(&v).to_vec();e.commit_verified(&mut v,1).unwrap();
|
||||
let prep=DraftPreparation::new(4,3,VOCAB).unwrap();
|
||||
let batch=prep.after_verified(&mut e,&v,2,0,&outs,&p[..3],0.0,false).unwrap();
|
||||
let batch=prep.after_verified(&mut e,&v,2,0,&outs,&p[..3],&mut crate::qwen_forward::token_memo::PrefixMemo::new(),0.0,false).unwrap();
|
||||
assert_eq!(batch.produced(),3);
|
||||
assert_eq!(batch.ids()[0],model(outs[0]));
|
||||
e.drain_verified(v).unwrap();
|
||||
|
||||
@@ -328,7 +328,7 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> {
|
||||
let mut pool_error: Option<Error> = None;
|
||||
let mut driver_failure: Option<ServeFailure> = None;
|
||||
let Self { binding, session, history, pool, ledger, .. } = &mut *self;
|
||||
let committed = ledger.committed();
|
||||
let ledger = &*ledger;
|
||||
let result = history.with_sampling(
|
||||
binding,
|
||||
&**session,
|
||||
@@ -338,7 +338,7 @@ impl<'a, 'ctx> NativeServeHost<'ctx> for OriginalServeHost<'a, 'ctx> {
|
||||
params,
|
||||
path,
|
||||
enabled,
|
||||
|| if committed == consumed { Ok(()) } else { Err(Error::IdentityMismatch) },
|
||||
|| if ledger.agrees_with(consumed) { Ok(()) } else { Err(Error::IdentityMismatch) },
|
||||
|sampling| {
|
||||
history_span.stop();
|
||||
let _p = profile::span("window.verifier");
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
//! sequence plus the window state machine (`Idle -> Open -> Idle`) that decides when a restore must repair
|
||||
//! a physical owner. It mints nothing and certifies no numerics.
|
||||
use super::contract::{Error, Result};
|
||||
use super::token_memo::PrefixMemo;
|
||||
use std::cell::Cell;
|
||||
|
||||
const VOCABULARY: i32 = 248_320;
|
||||
|
||||
@@ -34,6 +36,9 @@ pub(in crate::qwen_forward) struct ServeLedger {
|
||||
/// published; the owners must be rolled back to the session's lineage before they are reused.
|
||||
dirty: bool,
|
||||
failed: bool,
|
||||
/// What `agrees_with` already compared: the controller's `consumed` and `committed` only grow, so each round compares the tokens
|
||||
/// appended since the last one (a full pass every `token_memo::FULL_EVERY` rounds) instead of both whole histories.
|
||||
agreed: Cell<PrefixMemo>,
|
||||
}
|
||||
|
||||
impl ServeLedger {
|
||||
@@ -45,7 +50,14 @@ impl ServeLedger {
|
||||
if committed.len() as u64 > limit {
|
||||
return Err(Error::InvalidPosition);
|
||||
}
|
||||
Ok(Self { committed, limit, window: Window::Idle, dirty: false, failed: false })
|
||||
Ok(Self { committed, limit, window: Window::Idle, dirty: false, failed: false, agreed: Cell::new(PrefixMemo::new()) })
|
||||
}
|
||||
/// `committed == consumed`, examining only the tokens appended since the last successful comparison of the same buffer.
|
||||
pub(in crate::qwen_forward) fn agrees_with(&self, consumed: &[i32]) -> bool {
|
||||
let mut memo = self.agreed.get();
|
||||
let equal = memo.equal(consumed, &self.committed);
|
||||
self.agreed.set(memo);
|
||||
equal
|
||||
}
|
||||
pub(in crate::qwen_forward) fn committed(&self) -> &[i32] {
|
||||
&self.committed
|
||||
@@ -86,7 +98,7 @@ impl ServeLedger {
|
||||
let position = u64::try_from(position).map_err(|_| Error::InvalidPosition)?;
|
||||
if position != session_position
|
||||
|| consumed.len() as u64 != position
|
||||
|| self.committed.as_slice() != consumed
|
||||
|| !self.agrees_with(consumed)
|
||||
|| !matches!(self.window, Window::Idle)
|
||||
{
|
||||
return Err(Error::IdentityMismatch);
|
||||
@@ -210,6 +222,42 @@ mod tests {
|
||||
assert_eq!(ServeLedger::new(vec![1; 11], 10).err(), Some(Error::InvalidPosition));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_comparison_examines_the_appended_tokens_and_still_refuses_every_different_history() {
|
||||
let mut l = ledger(&[1, 2, 3]);
|
||||
let mut consumed: Vec<i32> = Vec::with_capacity(64);
|
||||
consumed.extend_from_slice(&[1, 2, 3]);
|
||||
assert!(l.agrees_with(&consumed));
|
||||
// rounds: both histories grow by the committed tokens, the memo only needs the new ones
|
||||
for round in 0..100 {
|
||||
let t = [10 + round, 11 + round];
|
||||
l.committed.extend_from_slice(&t);
|
||||
consumed.extend_from_slice(&t);
|
||||
assert!(l.agrees_with(&consumed), "round {round}");
|
||||
assert!(l.validate_current(&consumed, 7, consumed.len() as i64, consumed.len() as u64).is_ok(), "round {round}");
|
||||
}
|
||||
// the controller's newest token differs from the ledger's, or its length does
|
||||
let n = consumed.len();
|
||||
consumed[n - 1] ^= 1;
|
||||
assert!(!l.agrees_with(&consumed), "newest token differs");
|
||||
consumed[n - 1] ^= 1;
|
||||
assert!(l.agrees_with(&consumed), "restored");
|
||||
assert!(!l.agrees_with(&consumed[..n - 1]));
|
||||
// an old token rewritten in place (no owner does this) is found by the periodic full pass
|
||||
consumed[n - 2] ^= 1;
|
||||
let found = (1..=crate::qwen_forward::token_memo::FULL_EVERY + 1).find(|_| !l.agrees_with(&consumed));
|
||||
assert!(found.is_some(), "the full pass must find the rewritten token");
|
||||
consumed[n - 2] ^= 1;
|
||||
assert!(l.agrees_with(&consumed));
|
||||
// another buffer with the same contents agrees, another buffer with different contents does not (whatever was remembered)
|
||||
let copy = consumed.clone();
|
||||
assert!(l.agrees_with(©));
|
||||
let mut other = copy.clone();
|
||||
other[0] = 99;
|
||||
assert!(!l.agrees_with(&other));
|
||||
assert!(l.agrees_with(©));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_published_window_appends_exactly_the_accepted_inputs_and_cleans_the_ledger() {
|
||||
let mut l = ledger(&[1, 2]);
|
||||
|
||||
@@ -6,6 +6,7 @@ use super::original_spec_draft::{DraftBatch,DraftPreparation,OriginalDraftEngine
|
||||
use super::original_spec_adaptive::{AdaptiveConfig,AdaptivePolicy,Choice,DraftPlan,Offer,Origin,SpecStats};
|
||||
use super::original_spec_policy::{DraftPolicy,MAX_T};
|
||||
use super::original_spec_suffix::SuffixDrafter;
|
||||
use super::token_memo::PrefixMemo;
|
||||
|
||||
/// `LELEKA_SPEC_TRACE`: one `DBG spec-trace` line per timed round (width, source, accepted, round ms, the policy's expectation).
|
||||
pub(crate) fn trace_enabled()->bool {
|
||||
@@ -130,6 +131,8 @@ struct Request {
|
||||
consumed:Vec<i32>,input:i32,position:i64,first_window:bool,
|
||||
produced:usize,max_new:usize,min_p:f32,eos:Vec<i32>,drafts:DraftBatch,
|
||||
pending_draft:bool,finished:bool,
|
||||
/// The part of `consumed` the draft stage already range-checked (`consumed` only grows within a request; see `token_memo`).
|
||||
vetted:PrefixMemo,
|
||||
}
|
||||
pub(crate) struct OriginalSpecController {
|
||||
config:SpecConfig,policy:DraftPolicy,suffix:SuffixDrafter,request:Option<Request>,rounds:u64,failed:bool,owner:Rc<()>,
|
||||
@@ -207,7 +210,7 @@ impl OriginalSpecController {
|
||||
self.plan=Some(pol.draft_plan());
|
||||
}
|
||||
self.request=Some(Request{consumed,input:prompt[prompt.len()-1],position:prompt.len() as i64-1,
|
||||
first_window:true,produced:0,max_new,min_p,eos,drafts:DraftBatch::empty(),pending_draft:false,finished:max_new==0});
|
||||
first_window:true,produced:0,max_new,min_p,eos,drafts:DraftBatch::empty(),pending_draft:false,finished:max_new==0,vetted:PrefixMemo::new()});
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn host_bytes(&self)->Result<usize> {
|
||||
@@ -394,7 +397,7 @@ impl OriginalSpecController {
|
||||
let result:SpecResult<Option<DraftBatch>>=match admission {
|
||||
Err(e)=>Err(e.into()),
|
||||
Ok(())=> {
|
||||
let r=self.request.as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
let r=self.request.as_mut().ok_or(Error::IdentityMismatch)?;
|
||||
if let Some(e)=round.bookkeeping_error {Err(e.into())}
|
||||
else if r.finished&&!self.final_draft {Ok(None)}
|
||||
else {
|
||||
@@ -414,7 +417,7 @@ impl OriginalSpecController {
|
||||
match (planned,preparation) {
|
||||
(Err(e),_)|(_,Err(e))=>Err(e.into()),
|
||||
(Ok(()),Ok(preparation))=>preparation.after_verified(engine,&round.verified,round.position,round.accepted,
|
||||
&round.outputs[..round.t],&r.consumed,floor,self.config.coupled).map(Some).map_err(Into::into),
|
||||
&round.outputs[..round.t],&r.consumed,&mut r.vetted,floor,self.config.coupled).map(Some).map_err(Into::into),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Original MtpDrafter::capture_round/draft scheduling. No target residual is invented here.
|
||||
use super::contract::{Error,Result};
|
||||
use super::original_spec_policy::MAX_T;
|
||||
use super::token_memo::PrefixMemo;
|
||||
|
||||
#[derive(Clone,Copy,Debug)]
|
||||
pub(crate) struct DraftPick {pub(crate) token:i32,pub(crate) probability:f32}
|
||||
@@ -54,11 +55,12 @@ impl DraftPreparation {
|
||||
/// Target receipts stay borrowed until catch-up, selection, chain and drain
|
||||
/// complete. Ordinary confidence truncation leaves the rest of IDs/probs 0.
|
||||
pub(crate) fn after_verified<V,E:OriginalDraftEngine<V>>(&self,engine:&mut E,verified:&V,
|
||||
p:i64,a:usize,outputs:&[i32],consumed:&[i32],min_p:f32,coupled:bool)->Result<DraftBatch> {
|
||||
p:i64,a:usize,outputs:&[i32],consumed:&[i32],vetted:&mut PrefixMemo,min_p:f32,coupled:bool)->Result<DraftBatch> {
|
||||
if outputs.is_empty()||outputs.len()>self.max_t||a>=outputs.len()||p<0||p.checked_add(outputs.len() as i64).is_none_or(|end|end>(crate::qwen_forward::contract::serving_cells() as i64))||!min_p.is_finite() {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
if outputs.iter().chain(consumed).any(|&v|v<0||v as u32>=self.vocabulary) {return Err(Error::InvalidToken);}
|
||||
// `consumed` only grows within a request: `vetted` remembers the part already range-checked (`token_memo`)
|
||||
if outputs.iter().any(|&v|v<0||v as u32>=self.vocabulary)||!vetted.in_range(consumed,self.vocabulary as i32) {return Err(Error::InvalidToken);}
|
||||
let result=(|| {
|
||||
if coupled {engine.stage_coupled_history(consumed,outputs[a])?;}
|
||||
engine.replay_target_kv(verified,p,outputs)?;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! allocation and one T*h upload per penalized window; disabled penalties lend
|
||||
//! no buffer. Token history is input data, never numerical/commit authority.
|
||||
use super::*;
|
||||
use crate::qwen_forward::token_memo::PrefixMemo;
|
||||
use crate::qwen_forward::session::{QwenSession,TargetStepOrigin};
|
||||
use leleka_cuda_driver::{DeviceBuffer,SamplerParams,SamplerPath};
|
||||
const HISTORY:usize=4096;
|
||||
@@ -11,6 +12,9 @@ const BYTES:usize=HISTORY*ROWS*4;
|
||||
pub(in crate::qwen_forward) struct OriginalNativePenaltyHistory<'ctx>{
|
||||
binding:BindingIdentity,context:&'ctx Context<'ctx>,device:Option<DeviceBuffer<'ctx>>,
|
||||
staging:Box<[u8]>,failed:bool,
|
||||
/// The part of the controller's `consumed` already range-checked (it only grows within a request): each window checks the tokens
|
||||
/// appended since, not the whole history again (`token_memo`).
|
||||
tail_checked:PrefixMemo,
|
||||
}
|
||||
impl<'ctx> OriginalNativePenaltyHistory<'ctx>{
|
||||
pub(in crate::qwen_forward) fn new(binding:&ModelBinding,context:&'ctx Context<'ctx>)->Result<Self>{
|
||||
@@ -18,7 +22,7 @@ impl<'ctx> OriginalNativePenaltyHistory<'ctx>{
|
||||
let mut staging=Vec::new();staging.try_reserve_exact(BYTES).map_err(|_|Error::InputAllocation)?;
|
||||
staging.resize(BYTES,0xff);
|
||||
let device=context.allocate(BYTES).map_err(driver)?;
|
||||
Ok(Self{binding:binding.identity(),context,device:Some(device),staging:staging.into_boxed_slice(),failed:false})
|
||||
Ok(Self{binding:binding.identity(),context,device:Some(device),staging:staging.into_boxed_slice(),failed:false,tail_checked:PrefixMemo::new()})
|
||||
}
|
||||
pub(in crate::qwen_forward) fn host_bytes(&self)->usize{self.staging.len()+std::mem::size_of::<Self>()}
|
||||
/// The closed caller authenticates its actual controller-consumed tail and
|
||||
@@ -38,7 +42,7 @@ impl<'ctx> OriginalNativePenaltyHistory<'ctx>{
|
||||
||!(1..=ROWS).contains(&window.len())||tail.len()as u64!=origin.next_position(){return Err(Error::IdentityMismatch);}
|
||||
params.validate().map_err(driver)?;
|
||||
let vocabulary=248320;
|
||||
if tail.iter().chain(window).any(|&id|id<0||id>=vocabulary){return Err(Error::InvalidToken);}
|
||||
if window.iter().any(|&id|id<0||id>=vocabulary)||!self.tail_checked.in_range(tail,vocabulary){return Err(Error::InvalidToken);}
|
||||
origin.next_position().checked_add(window.len()as u64).ok_or(Error::Overflow)?;
|
||||
let h=if params.penalty_last_n<=0{0}else{(params.penalty_last_n as usize).min(HISTORY)};
|
||||
if h>0{
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
//! Per-round checks over the request's whole token history, made proportional to what changed since the last round.
|
||||
//!
|
||||
//! The serve loop keeps the committed tokens of a request twice (the controller's `consumed` and the ledger's `committed`) and,
|
||||
//! every round, authenticated them against each other and range-checked all of them again: five passes over up to 262,144 `i32`
|
||||
//! per round (about 0.15 ms at 247k tokens, growing linearly with the context). Both sequences only ever GROW inside one request
|
||||
//! (a token is appended when a window commits; nothing rewrites a committed token), so a pass that succeeded over the first `n`
|
||||
//! tokens of a buffer stays true for them and only the tokens appended since need examining.
|
||||
//!
|
||||
//! A [`PrefixMemo`] records `(address, length)` of the buffer a check last passed over, plus three of its tokens (first, middle, last)
|
||||
//! as a cheap identity probe against a different buffer that happens to reuse the address. The next check starts at that length when
|
||||
//! it sees the same address, the same probe tokens and a buffer at least as long (a reallocated, shorter or different buffer starts
|
||||
//! over at 0), and every `FULL_EVERY`-th use examines everything again, so an in-place rewrite of an old token (nothing does this; the
|
||||
//! owners are append-only) would still be found within a bounded number of rounds. The checks are assertions: an answer that passes is the
|
||||
//! same answer as before; the only difference is that a corrupted old prefix, which cannot happen through the owners' interfaces,
|
||||
//! is reported up to `FULL_EVERY` rounds later instead of at once.
|
||||
|
||||
/// How many consecutive partial checks may pass before the whole history is examined again (about 1/32 of the former cost).
|
||||
pub(crate) const FULL_EVERY: u32 = 32;
|
||||
/// The `key` of an equality memo (a range memo is keyed by its vocabulary, which is positive).
|
||||
const EQUAL_KEY: i32 = -1;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
|
||||
pub(crate) struct PrefixMemo {
|
||||
address: usize,
|
||||
len: usize,
|
||||
partial: u32,
|
||||
probe: [i32; 3],
|
||||
/// What the remembered pass checked (the vocabulary of a range check): a pass for another criterion does not carry over.
|
||||
key: i32,
|
||||
}
|
||||
|
||||
fn probe_of(tokens: &[i32]) -> [i32; 3] {
|
||||
match tokens.len() {
|
||||
0 => [0; 3],
|
||||
n => [tokens[0], tokens[n / 2], tokens[n - 1]],
|
||||
}
|
||||
}
|
||||
|
||||
impl PrefixMemo {
|
||||
pub(crate) const fn new() -> Self {
|
||||
Self { address: 0, len: 0, partial: 0, probe: [0; 3], key: 0 }
|
||||
}
|
||||
/// The index the next check of `tokens` would start at: everything before it passed on an earlier use of the same buffer.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn start(&self, tokens: &[i32]) -> usize {
|
||||
self.start_for(tokens, self.key)
|
||||
}
|
||||
fn start_for(&self, tokens: &[i32], key: i32) -> usize {
|
||||
if self.len == 0
|
||||
|| self.key != key
|
||||
|| self.address != tokens.as_ptr() as usize
|
||||
|| tokens.len() < self.len
|
||||
|| self.partial >= FULL_EVERY
|
||||
|| probe_of(&tokens[..self.len]) != self.probe
|
||||
{
|
||||
0
|
||||
} else {
|
||||
self.len
|
||||
}
|
||||
}
|
||||
/// The check of `tokens[start..]` passed: the whole of `tokens` has now passed.
|
||||
fn passed_for(&mut self, tokens: &[i32], start: usize, key: i32) {
|
||||
self.key = key;
|
||||
self.partial = if start == 0 { 0 } else { self.partial + 1 };
|
||||
self.address = tokens.as_ptr() as usize;
|
||||
self.len = tokens.len();
|
||||
self.probe = probe_of(tokens);
|
||||
}
|
||||
/// A check failed: nothing about this buffer is remembered.
|
||||
pub(crate) fn forget(&mut self) {
|
||||
*self = Self::new();
|
||||
}
|
||||
/// `tokens` all lie in `0..vocabulary`, examining only what the memo has not seen.
|
||||
pub(crate) fn in_range(&mut self, tokens: &[i32], vocabulary: i32) -> bool {
|
||||
let start = self.start_for(tokens, vocabulary);
|
||||
if tokens[start..].iter().any(|&t| !(0..vocabulary).contains(&t)) {
|
||||
self.forget();
|
||||
return false;
|
||||
}
|
||||
self.passed_for(tokens, start, vocabulary);
|
||||
true
|
||||
}
|
||||
/// `a == b`, examining only what the memo has not seen. The memo follows `a` (the longer-lived buffer is the caller's choice);
|
||||
/// `b` is the other owner's buffer, only appended to as well.
|
||||
pub(crate) fn equal(&mut self, a: &[i32], b: &[i32]) -> bool {
|
||||
if a.len() != b.len() {
|
||||
return false;
|
||||
}
|
||||
let start = self.start_for(a, EQUAL_KEY);
|
||||
if a[start..] != b[start..] {
|
||||
self.forget();
|
||||
return false;
|
||||
}
|
||||
self.passed_for(a, start, EQUAL_KEY);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_first_use_examines_everything_and_a_grown_buffer_only_its_new_tail() {
|
||||
let mut v: Vec<i32> = Vec::with_capacity(64);
|
||||
v.extend(0..10);
|
||||
let mut m = PrefixMemo::new();
|
||||
assert_eq!(m.start(&v), 0);
|
||||
assert!(m.in_range(&v, 100));
|
||||
v.extend(10..14);
|
||||
assert_eq!(m.start(&v), 10, "only the four appended tokens");
|
||||
assert!(m.in_range(&v, 100));
|
||||
assert_eq!(m.start(&v), 14, "an unchanged buffer needs no examination");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_address_a_shorter_buffer_or_a_failure_starts_over() {
|
||||
let mut v: Vec<i32> = (0..10).collect();
|
||||
let mut m = PrefixMemo::new();
|
||||
assert!(m.in_range(&v, 100));
|
||||
let w = v.clone();
|
||||
assert_eq!(m.start(&w), 0, "another buffer with the same contents is not the remembered one");
|
||||
assert_eq!(m.start(&v[..5]), 0, "a shorter view of the same address");
|
||||
v.truncate(4);
|
||||
assert_eq!(m.start(&v), 0);
|
||||
let mut m = PrefixMemo::new();
|
||||
assert!(m.in_range(&w, 100));
|
||||
assert!(!m.in_range(&w, 5), "tokens 5.. are out of range");
|
||||
assert_eq!(m.start(&w), 0, "a failed check is not remembered");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_different_buffer_at_the_same_address_is_caught_by_the_probe() {
|
||||
let mut v: Vec<i32> = vec![1, 2, 3, 4, 5, 6, 7, 8];
|
||||
let mut m = PrefixMemo::new();
|
||||
assert!(m.in_range(&v, 100));
|
||||
// the same allocation now holds other tokens (as a freed and reused buffer would): first, middle or last differ
|
||||
for at in [0usize, 4, 7] {
|
||||
let saved = v[at];
|
||||
v[at] = 99;
|
||||
assert_eq!(m.start(&v), 0, "probe position {at}");
|
||||
v[at] = saved;
|
||||
}
|
||||
assert_eq!(m.start(&v), 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_examined_tail_finds_a_bad_token_and_a_bad_old_token_waits_for_the_next_full_pass() {
|
||||
let mut v: Vec<i32> = Vec::with_capacity(4096);
|
||||
v.extend(0..100);
|
||||
let mut m = PrefixMemo::new();
|
||||
assert!(m.in_range(&v, 1000));
|
||||
// a bad token appended: found at once
|
||||
v.push(-1);
|
||||
assert!(!m.in_range(&v, 1000));
|
||||
v.pop();
|
||||
assert!(m.in_range(&v, 1000));
|
||||
// an old token rewritten in place (no owner does this): found at the next full pass, within FULL_EVERY uses
|
||||
v[3] = 5000;
|
||||
let mut found_after = None;
|
||||
for round in 1..=(FULL_EVERY + 2) {
|
||||
v.push(7);
|
||||
if !m.in_range(&v, 1000) {
|
||||
found_after = Some(round);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let round = found_after.expect("the full pass must find it");
|
||||
assert!(round <= FULL_EVERY + 1, "found after {round} rounds");
|
||||
assert!(round > 1, "a partial pass does not re-read the old prefix");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equality_examines_the_tail_and_agrees_with_the_slice_comparison_on_random_growth() {
|
||||
let mut x = 0x2545F4914F6CDD1Du64;
|
||||
let mut next = move || {
|
||||
x ^= x << 13;
|
||||
x ^= x >> 7;
|
||||
x ^= x << 17;
|
||||
x
|
||||
};
|
||||
for case in 0..50 {
|
||||
let mut a: Vec<i32> = Vec::with_capacity(5000);
|
||||
let mut b: Vec<i32> = Vec::with_capacity(5000);
|
||||
let mut m = PrefixMemo::new();
|
||||
for round in 0..200 {
|
||||
let grow = 1 + (next() % 7) as usize;
|
||||
for _ in 0..grow {
|
||||
let t = (next() % 1000) as i32;
|
||||
a.push(t);
|
||||
b.push(t);
|
||||
}
|
||||
// a different token appended to one side only is a mismatch of the examined tail
|
||||
if round % 17 == 5 {
|
||||
let n = a.len();
|
||||
b[n - 1] ^= 1;
|
||||
assert!(!m.equal(&a, &b), "case {case} round {round}: the new tail differs");
|
||||
b[n - 1] ^= 1;
|
||||
}
|
||||
assert!(m.equal(&a, &b), "case {case} round {round}: equal buffers");
|
||||
assert_eq!(m.equal(&a, &b), a == b);
|
||||
// lengths differ: never equal, whatever was remembered
|
||||
b.push(1);
|
||||
assert!(!m.equal(&a, &b));
|
||||
b.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_pass_every_fixed_number_of_uses_bounds_the_work() {
|
||||
let mut v: Vec<i32> = Vec::with_capacity(1 << 16);
|
||||
v.extend(0..1000);
|
||||
let mut m = PrefixMemo::new();
|
||||
let mut examined = 0usize;
|
||||
for _ in 0..(FULL_EVERY as usize * 4) {
|
||||
v.push(1);
|
||||
let s = m.start(&v);
|
||||
examined += v.len() - s;
|
||||
assert!(m.in_range(&v, 10_000));
|
||||
}
|
||||
// 128 uses over a history of 1,000..1,128 tokens: one full pass per FULL_EVERY+1 uses, one new token otherwise
|
||||
assert!(examined < 5 * 1200 + 128 * 2, "examined {examined} tokens");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user