S048: per-version proof against a known sample, farm tests

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-26 14:13:53 -06:00
commit fc7f04ac03
6 changed files with 269 additions and 48 deletions

View file

@ -182,6 +182,13 @@ async fn fetch_whole(
Some(file) => resume(job, &task, file, parts, &link, compared, stop).await?,
None => start(shared, job, &task, probe, &link, stop).await?,
};
// What other versions of the same size are compared with.
if link.ranges
&& let Some(p) = parts.iter().find(|p| p.done > 0)
{
let n = p.done.min(fetch::SAMPLE);
link.known_sample(p.start, file.read_at(n as usize, p.start).await?);
}
if let Some(size) = link.version.size {
let reserving = file.clone();
blocking(move || reserving.reserve(size)).await?;
@ -203,7 +210,7 @@ async fn fetch_whole(
let Ended { live, learned, gave } = run.end();
let saved = job.checkpoint(&live, &file).await;
// So that a restart doesn't take its servers for another version.
if farm.load(std::sync::atomic::Ordering::Relaxed) && !was_farm {
if farm.is() && !was_farm {
job.run(move |s| Ok(s.edit_task(id, |t| t.farm = true)?)).await?;
}
if let Some(n) = learned {

View file

@ -6,8 +6,7 @@ use crate::disk::PartialFile;
use crate::limit::Flow;
use crate::part::LivePart;
use bytes::Bytes;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Instant;
/// Finished bytes read again and compared when a part goes on.
@ -15,7 +14,7 @@ pub const OVERLAP: u64 = 4096;
/// Finished bytes compared with a reply of another version of the same size, and on a farm when a part goes on.
pub const SAMPLE: u64 = 64 * 1024;
/// Replies asked for until one of the known version and one of another can be compared.
const PROOF_TRIES: u32 = 8;
const PROOF_TRIES: u32 = 12;
/// Held in memory for each part.
const BUFFER: usize = 512 * 1024;
/// A slow part writes what it has this often.
@ -30,22 +29,51 @@ pub struct Link {
pub ranges: bool,
/// The first version seen, kept for display and as the one the bytes on disk are of.
pub version: Validators,
/// Its servers differ in dates and tags but were shown to have the same bytes: only size and bytes count. Shared by clones.
pub farm: Arc<AtomicBool>,
/// Shared by clones.
pub farm: Arc<Farm>,
}
/// Servers behind one link that differ in dates and tags. Each other version counts once its bytes were shown to be the same.
#[derive(Debug, Default)]
pub struct Farm {
/// Known to be one from before.
stored: bool,
proven: Mutex<Vec<Validators>>,
/// Bytes of the known version at an offset, that other versions are compared with.
sample: Mutex<Option<(u64, Vec<u8>)>>,
}
impl Farm {
pub fn is(&self) -> bool {
self.stored || !self.proven.lock().unwrap().is_empty()
}
}
impl Link {
pub fn new(client: Client, source: Source, ranges: bool, version: Validators, farm: bool) -> Link {
Link { client, source, ranges, version, farm: Arc::new(AtomicBool::new(farm)) }
Link { client, source, ranges, version, farm: Arc::new(Farm { stored: farm, ..Farm::default() }) }
}
pub fn farm(&self) -> bool {
self.farm.load(Ordering::Relaxed)
self.farm.is()
}
fn set_farm(&self) {
if !self.farm.swap(true, Ordering::Relaxed) {
log::info!("{}: servers differ in dates only, telling versions by size and bytes", self.source.url);
/// Finished bytes at `at`, of the version the bytes here are of.
pub(super) fn known_sample(&self, at: u64, data: Vec<u8>) {
self.farm.sample.lock().unwrap().get_or_insert((at, data));
}
/// Of the version the bytes here are of, or of one shown to have the same bytes.
fn sure(&self, version: &Validators) -> bool {
self.version.same_file(version) || self.farm.proven.lock().unwrap().iter().any(|p| p == version)
}
/// `version` has the same bytes as the known one.
fn proven(&self, version: Validators) {
let mut proven = self.farm.proven.lock().unwrap();
if !proven.contains(&version) {
log::info!("{}: another server has the same bytes ({:?}, {:?})", self.source.url, version.etag, version.last_modified);
proven.push(version);
}
}
}
@ -74,7 +102,7 @@ pub(super) async fn fetch_within(
let (mut response, mut known, mut unsure) = if link.ranges {
range(link, part, file, &mut stop).await?
} else {
(whole(link, part, body, &mut stop).await?, vec![], false)
(whole(link, part, body, &mut stop).await?, vec![], None)
};
part.begin();
let mut buf = Vec::with_capacity(BUFFER);
@ -98,10 +126,11 @@ pub(super) async fn fetch_within(
return Err(Error::Changed);
}
known.drain(..old.len());
// Another version's reply had the bytes that are here: the servers differ in dates only.
if unsure && known.is_empty() {
link.set_farm();
unsure = false;
// Another version's reply had the bytes that are here: its server differs in dates only.
if known.is_empty()
&& let Some(version) = unsure.take()
{
link.proven(version);
}
// Piece by piece, as fast as the limits have it. One chunk is read ahead, so that the sender has room again before
// all is used up.
@ -171,17 +200,17 @@ async fn flush(part: &LivePart, file: &PartialFile, buf: Vec<u8>) -> Result<Vec<
/// Asks for the rest of the part and checks that this is what comes. Also gives the finished bytes it must begin with, and
/// whether the reply is of another version of the same size, which these bytes have to confirm.
async fn range(link: &Link, part: &LivePart, file: &PartialFile, stop: &mut Stop) -> Result<(Response, Vec<u8>, bool)> {
async fn range(link: &Link, part: &LivePart, file: &PartialFile, stop: &mut Stop) -> Result<(Response, Vec<u8>, Option<Validators>)> {
let p = part.get();
let mut overlap = p.done.min(if link.farm() { SAMPLE } else { OVERLAP });
loop {
let first = p.start + p.done - overlap;
if p.done == 0 {
return Ok((sure_range(link, first, p.end, stop).await?, vec![], false));
return Ok((sure_range(link, first, p.end, stop).await?, vec![], None));
}
let (response, unsure) = send_range(link, first, p.end, stop).await?;
// Enough of the bytes here to tell another version from the same file on another server.
if unsure && overlap < p.done.min(SAMPLE) {
if unsure.is_some() && overlap < p.done.min(SAMPLE) {
overlap = p.done.min(SAMPLE);
continue;
}
@ -192,45 +221,53 @@ async fn range(link: &Link, part: &LivePart, file: &PartialFile, stop: &mut Stop
/// A range from the known version, or from another one shown to have the same bytes.
async fn sure_range(link: &Link, first: u64, end: Option<u64>, stop: &mut Stop) -> Result<Response> {
let (response, unsure) = send_range(link, first, end, stop).await?;
if !unsure {
return Ok(response);
for _ in 0..PROOF_TRIES {
let (response, unsure) = send_range(link, first, end, stop).await?;
if unsure.is_none() {
return Ok(response);
}
drop(response);
// Only replies of the same size are unsure, so the size is known.
let until = end.or(link.version.size).unwrap_or(first);
prove(link, first, (until - first).min(SAMPLE), stop).await?;
}
drop(response);
// Only replies of the same size are unsure, so the size is known.
let until = end.or(link.version.size).unwrap_or(first);
prove(link, first, (until - first).min(SAMPLE), stop).await?;
Ok(send_range(link, first, end, stop).await?.0)
Err(Error::Changed)
}
/// Asks for `len` bytes at `at` until a reply of the known version and one of another can be compared. The same bytes make
/// the link a farm; other bytes, or no reply of the known version, mean the file changed.
/// Asks for `len` bytes at `at` until a sure reply and one of another version can be compared. The same bytes make that
/// version sure; other bytes, or no sure reply at all, mean the file changed.
async fn prove(link: &Link, at: u64, len: u64, stop: &mut Stop) -> Result<()> {
let (mut known, mut other) = (None, None);
let mut other = None;
for _ in 0..PROOF_TRIES {
if link.farm() {
return Ok(());
}
// The known sample's place, once there is one.
let (at, len) = link.farm.sample.lock().unwrap().as_ref().map_or((at, len), |(at, d)| (*at, d.len() as u64));
let (response, unsure) = send_range(link, at, Some(at + len), stop).await?;
let data = all(&link.client, response, len, stop).await?;
if data.len() as u64 != len {
return Err(Error::Cut { got: data.len() as u64, expected: Some(len) });
}
*(if unsure { &mut other } else { &mut known }) = Some(data);
if let (Some(a), Some(b)) = (&known, &other) {
if a != b {
match unsure {
Some(version) => other = Some((version, at, data)),
None => link.known_sample(at, data),
}
let sample = link.farm.sample.lock().unwrap().clone();
if let (Some((at, known)), Some((version, other_at, data))) = (sample, &other)
&& at == *other_at
&& known.len() == data.len()
{
if known != *data {
return Err(Error::Changed);
}
link.set_farm();
link.proven(version.clone());
return Ok(());
}
}
Err(Error::Changed)
}
/// A reply to a range, and whether it is of another version of the same size: maybe the same file from another server of
/// a farm, which only its bytes can tell. Never unsure on a farm.
async fn send_range(link: &Link, first: u64, end: Option<u64>, stop: &mut Stop) -> Result<(Response, bool)> {
/// A reply to a range, and its version when that is another one of the same size: maybe the same file from another server
/// of a farm, which only its bytes can tell.
async fn send_range(link: &Link, first: u64, end: Option<u64>, stop: &mut Stop) -> Result<(Response, Option<Validators>)> {
let last = end.map(|e| (e - 1).to_string()).unwrap_or_default();
// Servers of a farm with other dates answer a date in If-Range with the whole file.
let mut if_range = if link.farm() { None } else { link.version.if_range() };
@ -241,7 +278,7 @@ async fn send_range(link: &Link, first: u64, end: Option<u64>, stop: &mut Stop)
StatusCode::PARTIAL_CONTENT => {
let range = ContentRange::of(headers).ok_or_else(|| Error::BadReply("no usable Content-Range".into()))?;
let version = Validators::of(headers, range.total);
let unsure = !link.version.same_file(&version);
let unsure = !link.sure(&version);
if unsure && !link.version.maybe_same(&version) {
return Err(Error::Changed);
}
@ -250,16 +287,19 @@ async fn send_range(link: &Link, first: u64, end: Option<u64>, stop: &mut Stop)
}
check_length(headers, range)?;
check_encoding(headers, response.url())?;
return Ok((response, unsure && !link.farm()));
return Ok((response, unsure.then_some(version)));
}
StatusCode::OK => {
let version = Validators::of(headers, content_length(headers));
if link.version.same_file(&version) || (link.farm() && link.version.maybe_same(&version)) {
if link.version.same_file(&version) {
return Err(Error::RangeIgnored);
}
if link.version.maybe_same(&version) && if_range.take().is_some() {
continue;
}
if link.farm() && link.version.maybe_same(&version) {
return Err(Error::RangeIgnored);
}
return Err(if comes_as_page(link, headers) { Error::Page } else { Error::Changed });
}
StatusCode::RANGE_NOT_SATISFIABLE if unsatisfied_total(headers).is_some_and(|t| link.version.size != Some(t)) => {
@ -306,8 +346,10 @@ pub async fn same_bytes(link: &Link, known: &[u8], at: u64, stop: &mut Stop) ->
let len = known.len() as u64;
let (response, unsure) = send_range(link, at, Some(at + len), stop).await?;
let same = same_body(&link.client, response, known, stop).await?;
if same && unsure && len > 0 {
link.set_farm();
if same && len > 0
&& let Some(version) = unsure
{
link.proven(version);
}
Ok(same)
}

View file

@ -13,7 +13,7 @@ mod fuzz;
pub use download::{Options, Shared, download};
pub(crate) use download::is_page;
pub(crate) use fetch::{bytes_at, same_body, small};
pub use fetch::{Link, OVERLAP, compare, fetch, same_bytes};
pub use fetch::{Farm, Link, OVERLAP, SAMPLE, compare, fetch, same_bytes};
pub use monitor::{Monitor, PartEvent, PartId, PartState, PartView, ServerState, ServerView, Snapshot};
pub use name::{prefer as prefer_name, safe as safe_name};
pub(crate) use piece::piece;

172
crates/core/tests/farm.rs Normal file
View file

@ -0,0 +1,172 @@
//! Links served by a farm: servers with the same bytes but their own dates and tags (S048), and liars among them.
use medlar_core::disk::partial_path;
use medlar_core::host::{Caps, Hosts};
use medlar_core::http::*;
use medlar_core::model::{Task, TaskId};
use medlar_core::segment::Rules;
use medlar_core::store::Store;
use medlar_testserver::{Faults, TestServer, expected};
use sha2::{Digest, Sha256};
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::watch;
const MB: u64 = 1 << 20;
const PATH: &str = "/data/31/8m/output.bin";
struct Bench {
server: TestServer,
dir: tempfile::TempDir,
store: Arc<Store>,
client: Client,
options: Options,
}
impl Bench {
async fn new() -> Bench {
let dir = tempfile::tempdir().unwrap();
let store = Arc::new(Store::open(&dir.path().join("medlar.db")).unwrap());
let client = client(&ClientOptions { idle_timeout: Duration::from_millis(1500), ..ClientOptions::default() }).unwrap();
let options = Options {
rules: Rules { min: 64 * 1024, align: 4096, min_time: Duration::ZERO },
tick: Duration::from_millis(20),
stall: Duration::from_millis(500),
backoff: Duration::from_millis(20),
checkpoint: Duration::from_millis(15),
..Options::default()
};
Bench { server: TestServer::start().await, dir, store, client, options }
}
fn add(&self) -> TaskId {
self.store.add_task(Task { url: self.server.url(PATH), folder: self.dir.path().join("files"), ..Task::default() }).unwrap()
}
async fn run_until(&self, id: TaskId, stop: Stop) -> Result<PathBuf> {
let source = Source::new(&self.store.task(id).unwrap().url).unwrap();
let hosts = Hosts::new(Caps { burst: 100, per_second: 100.0, ..Caps::default() });
let shared = Shared { client: self.client.clone(), store: self.store.clone(), hosts };
let monitor = Monitor::new(4);
let run = download(&shared, id, source, &self.options, &monitor, stop);
tokio::time::timeout(Duration::from_secs(30), run).await.expect("hangs")
}
async fn run(&self, id: TaskId) -> Result<PathBuf> {
let (_keep, stop) = watch::channel(false);
self.run_until(id, stop).await
}
/// Stops it once every part has something.
async fn half(&self, id: TaskId) {
let (halt, stop) = watch::channel(false);
let watching = async {
while self.store.parts(id).unwrap().len() < 2 || self.store.parts(id).unwrap().iter().any(|p| p.done == 0) {
tokio::time::sleep(Duration::from_millis(5)).await;
}
halt.send_replace(true);
};
let running = self.run_until(id, stop);
tokio::pin!(running);
let result = tokio::select! {
result = &mut running => result,
() = watching => running.await,
};
assert!(matches!(result, Err(Error::Stopped)), "{result:?}");
}
fn partial(&self, id: TaskId) -> PathBuf {
let task = self.store.task(id).unwrap();
partial_path(&task.folder, &task.name)
}
fn farm(&self, nodes: u32, liar: bool, throttle: Option<u64>) {
self.server.set_faults(PATH, Faults { farm: Some(nodes), liar, throttle_conn: throttle, ..Faults::default() });
}
}
fn check(path: &Path) {
let data = std::fs::read(path).unwrap();
assert_eq!(data.len() as u64, 8 * MB);
assert_eq!(Sha256::digest(&data), Sha256::digest(expected(31, 0, 8 * MB as usize)));
}
#[tokio::test(flavor = "multi_thread")]
async fn a_farm_downloads_in_parts() {
let b = Bench::new().await;
b.farm(3, false, Some(MB));
let id = b.add();
let done = b.run(id).await.unwrap();
check(&done);
let log = b.server.requests_for(PATH);
let range = |r: &&medlar_testserver::Request| r.header("range")?.strip_prefix("bytes=")?.split('-').next()?.parse::<u64>().ok();
let starts: BTreeSet<_> = log.iter().filter(|r| r.status == 206).filter_map(|r| range(&r)).collect();
assert!(starts.len() >= 4, "parts in parallel: {starts:?}");
assert!(b.store.task(id).unwrap().farm, "the farm is kept");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_farm_goes_on_after_a_stop() {
// With the farm known from before, and without (found again by the bytes).
for stored in [true, false] {
let b = Bench::new().await;
b.farm(3, false, Some(MB));
let id = b.add();
b.half(id).await;
let mut task = b.store.task(id).unwrap();
assert!(task.farm, "found while it ran");
let first = (task.etag.clone(), task.last_modified.clone());
task.farm = stored;
b.store.save_task(task).unwrap();
b.farm(3, false, None);
b.server.clear_log();
let done = b.run(id).await.unwrap();
check(&done);
let task = b.store.task(id).unwrap();
// Without the flag the parts may well find replies of the first version, and nothing has to be proven again.
assert!(task.farm || !stored, "the farm is kept");
assert_eq!((task.etag, task.last_modified), first, "the first validators stay");
if stored {
let asked: Vec<_> = b.server.requests_for(PATH).into_iter().filter(|r| r.header("if-range").is_some()).collect();
assert!(asked.is_empty(), "If-Range on a farm: {asked:?}");
}
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_liar_of_the_same_size_is_another_file() {
let b = Bench::new().await;
b.farm(2, true, None);
let id = b.add();
// Changed, or by chance all from one of them: never mixed.
match b.run(id).await {
Err(Error::Changed) => assert!(!b.store.task(id).unwrap().farm),
Ok(done) => {
let data = std::fs::read(done).unwrap();
let liar = 31 ^ 7u64.wrapping_mul(0x1234_5678_9ABC_DEF1);
let whole = |seed| Sha256::digest(expected(seed, 0, 8 * MB as usize));
assert!([whole(31), whole(liar)].contains(&Sha256::digest(&data)), "two files were mixed");
}
other => panic!("{other:?}"),
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_liar_on_the_way_keeps_what_is_there() {
let b = Bench::new().await;
b.farm(2, false, Some(MB));
let id = b.add();
b.half(id).await;
let before = std::fs::read(b.partial(id)).unwrap();
b.farm(2, true, None);
let result = b.run(id).await;
assert!(matches!(result, Err(Error::Changed)), "{result:?}");
let after = std::fs::read(b.partial(id)).unwrap();
for p in b.store.parts(id).unwrap() {
let range = p.start as usize..(p.start + p.done) as usize;
assert!(before[range.clone()] == after[range.clone()], "finished bytes were touched");
assert!(after[range.clone()] == expected(31, p.start, p.done as usize)[..], "other bytes were kept as done");
}
}

View file

@ -73,7 +73,7 @@ impl Source {
pub fn versioned(&self, version: u32) -> Source {
match self {
Source::Gen { seed, len } if version > 0 => Source::Gen {
seed: seed ^ (u64::from(version) * 0x1234_5678_9ABC_DEF1),
seed: seed ^ u64::from(version).wrapping_mul(0x1234_5678_9ABC_DEF1),
len: *len,
},
other => other.clone(),

View file

@ -539,7 +539,7 @@ where
let node = f.farm.filter(|n| *n > 1).map(|n| req_no % n);
let lies = f.liar && node.is_some_and(|k| k % 2 == 1);
let src = reply.source.versioned(version + u32::from(lies) * 1000);
let src = reply.source.versioned(version + u32::from(lies) * 7);
let total = src.len();
let head_only = req.method == "HEAD";
let mut status = reply.status;