#![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
use std::cell::Cell;
use std::collections::BTreeMap;
use std::time::Duration;
use brygge_mutate::harness::{self, Outcome, Seed};
use brygge_mutate::ops::{Encoding, InterestingPosition};
use super::{Edit, check};
use crate::artifact::mutation::{decompose, reassemble_v3};
use crate::artifact::{from_bytes, to_bytes};
use crate::builder::{AtomDraft, IrBuilder};
use crate::model::{
Content, Identity, ImportProvenance, MetadataClaims, PathOp, SourceIdentity, SourceKind, Text,
};
use crate::status::EpistemicStatus;
const QUICK_ITERATIONS: u64 = 500;
const DEEP_FACTOR: u64 = 400;
const TIME_BUDGET: Duration = Duration::from_secs(2);
fn padding(label: &str) -> String {
format!(
"{label}-padding-{}",
"lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod ".repeat(40)
)
}
fn provenance() -> ImportProvenance {
let mut params = BTreeMap::new();
params.insert("padding".to_string(), padding("provenance"));
ImportProvenance {
source: SourceIdentity {
kind: SourceKind::Git,
repo_id: b"repo".to_vec(),
atom_id: b"root".to_vec(),
signatures: Vec::new(),
extras: Vec::new(),
},
brygge_version: "0.1.0".into(),
decoder: "brygge-decode-git".into(),
decoder_version: "0.1.0".into(),
params,
}
}
fn source(n: u8) -> SourceIdentity {
SourceIdentity {
kind: SourceKind::Git,
repo_id: b"repo".to_vec(),
atom_id: vec![n],
signatures: Vec::new(),
extras: Vec::new(),
}
}
fn long_text(label: &str) -> Text {
Text::utf8(&format!(
"{label}: lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor \
incididunt ut labore et dolore magna aliqua, {label} again for good measure."
))
}
fn long_identity(label: &str) -> Identity {
Identity {
name: Text::utf8(&format!("{label} Long Padding Name For Mutation Coverage")),
email: Some(Text::utf8(&format!(
"{label}.long.padding.email.for.mutation.coverage@example.com"
))),
}
}
fn fixed_input() -> crate::artifact::Decoded {
let mut b = IrBuilder::new(provenance());
let blob = b.add_blob(b"hello".to_vec()).unwrap();
let root = b
.add_atom(AtomDraft {
parents: vec![],
ops: vec![PathOp::Add {
path: "a".into(),
content: Content::blob(blob, 0o100_644),
status: EpistemicStatus::Stated,
}],
copies: vec![],
metadata: MetadataClaims {
message: Some(long_text("root")),
author: Some(long_identity("root-author")),
committer: Some(long_identity("root-committer")),
..MetadataClaims::default()
},
source: source(1),
status: EpistemicStatus::Stated,
})
.unwrap();
let child_blob = b.add_blob(b"hello, again".to_vec()).unwrap();
b.add_atom(AtomDraft {
parents: vec![root],
ops: vec![PathOp::Modify {
path: "a".into(),
content: Content::blob(child_blob, 0o100_644),
status: EpistemicStatus::Stated,
}],
copies: vec![],
metadata: MetadataClaims {
message: Some(long_text("child")),
author: Some(long_identity("child-author")),
committer: Some(long_identity("child-committer")),
..MetadataClaims::default()
},
source: source(2),
status: EpistemicStatus::Stated,
})
.unwrap();
let ir = b.finish().unwrap();
from_bytes(&to_bytes(&ir)).unwrap()
}
fn honest_output_bytes(input: &crate::artifact::Decoded) -> Vec<u8> {
let mut step_params = BTreeMap::new();
step_params.insert("padding".to_string(), padding("step"));
let mut edit = Edit::begin(input, "mutation-seed", "0", step_params);
edit.atom_mut(0)
.unwrap()
.set_message(Some(long_text("root, renamed")));
let ir = edit.finish().unwrap();
to_bytes(&ir)
}
fn locate_field(buf: &[u8], target_id: u64, has_leading_count: bool) -> Option<(usize, usize)> {
let mut r = crate::canon::CanonReader::new(buf);
let total = buf.len();
let count = if has_leading_count {
r.uvarint().ok()?
} else {
u64::MAX
};
let mut seen = 0u64;
while (has_leading_count && seen < count) || (!has_leading_count && !r.is_empty()) {
let tag = r.uvarint().ok()?;
let id = tag >> 1;
let len = r.uvarint_len().ok()?;
let value_start = total - r.remaining();
let _ = r.raw(len).ok()?;
seen += 1;
if id == target_id {
return Some((value_start, len));
}
}
None
}
fn transform_consumed_position(tail: &[u8]) -> Option<InterestingPosition> {
let (consumed_start, consumed_len) = locate_field(tail, 4, false)?;
debug_assert_eq!(
consumed_len, 32,
"TransformRecord.consumed is always 32 bytes"
);
Some(InterestingPosition {
offset: consumed_start,
encoding: Encoding::Binary {
width: 8,
big_endian: true,
},
ceiling: None,
})
}
fn after_name_and_version(tail: &[u8]) -> Option<usize> {
let (list_start, _) = locate_field(tail, 6, false)?;
let list_value = tail.get(list_start..)?;
let mut r = crate::canon::CanonReader::new(list_value);
let _count = r.uvarint().ok()?;
let item_start = list_value.len() - r.remaining();
let item_bytes = list_value.get(item_start..)?;
let (version_start, version_len) = locate_field(item_bytes, 2, true)?;
Some(list_start + item_start + version_start + version_len)
}
#[test]
fn check_on_a_mutated_output_against_a_fixed_input_never_panics() {
let input = fixed_input();
let seed_bytes = honest_output_bytes(&input);
let decomposed = decompose(&seed_bytes);
let meta = &decomposed.meta_bytes;
let (atoms_start, atoms_len) =
locate_field(meta, 1, true).expect("the fixture always has atoms");
let after_atoms = atoms_start + atoms_len;
let tail_after_atoms = meta.get(after_atoms..).unwrap();
let extra = after_name_and_version(tail_after_atoms).unwrap_or(0);
let tail_start = after_atoms + extra;
let fixed_prefix = meta.get(..tail_start).unwrap().to_vec();
let tail = meta.get(tail_start..).unwrap().to_vec();
let position = transform_consumed_position(&tail);
let positions: Vec<InterestingPosition> = position.into_iter().collect();
let specs = [Seed::new(&tail, &positions)];
let total: Cell<u64> = Cell::new(0);
let reached_check: Cell<u64> = Cell::new(0);
harness::run(
env!("CARGO_MANIFEST_DIR"),
"check_on_a_mutated_output_against_a_fixed_input_never_panics",
&specs,
QUICK_ITERATIONS,
DEEP_FACTOR,
TIME_BUDGET,
|_seed_index, mutated_tail| {
total.set(total.get() + 1);
let mut full_meta = fixed_prefix.clone();
full_meta.extend_from_slice(mutated_tail);
let full = reassemble_v3(
&decomposed.version_bytes,
&full_meta,
&decomposed.table_bytes,
&decomposed.blob_bytes,
);
match from_bytes(&full) {
Err(_) => Outcome::Ok,
Ok(output) => {
reached_check.set(reached_check.get() + 1);
let _ = check(&input, &output, "mutation-seed");
Outcome::Ok
}
}
},
);
let total = total.get();
let reached = reached_check.get();
assert!(total > 0, "the harness ran zero iterations");
assert!(
reached * 20 >= total * 7,
"only {reached}/{total} ({:.1}%) mutated outputs reached `check` — expected at least 35%",
100.0 * reached as f64 / total as f64
);
}