use std::{
collections::{HashMap, hash_map::Entry},
fmt,
fs::File,
hash::{DefaultHasher, Hash, Hasher},
io::{BufRead, BufReader, BufWriter, Write},
path::{Path, PathBuf},
};
use eyre::{Context, Result};
use serde::{
Deserialize,
de::{Deserializer, IgnoredAny, SeqAccess, Visitor},
};
use solana_signature::Signature;
use super::model::CompareTransaction;
use crate::output::{
NdjsonScan, SimulationMetadata, SimulationSummary, SolChange, TokenChange,
missing_metadata_envelope, not_an_ndjson_stream, scan_ndjson_events,
};
pub(super) const TARGET_PARTITION_BYTES: u64 = 256 * 1024 * 1024;
const MAX_PARTITIONS: usize = 128;
const SPILL_WRITE_BUFFER_BYTES: usize = 64 * 1024;
pub(super) struct LoadedSide {
pub(super) partitions: Vec<PathBuf>,
pub(super) total_transactions: usize,
}
struct RecordSink {
paths: Vec<PathBuf>,
writers: Vec<BufWriter<File>>,
}
impl RecordSink {
fn new(partitions: usize, spill: &Path, label: &str) -> Result<Self> {
let (paths, writers) = (0..partitions)
.map(|i| {
let path = spill.join(format!("{label}-{i}.ndjson"));
let file = File::create(&path)
.with_context(|| format!("failed to create spill file {}", path.display()))?;
Ok((
path,
BufWriter::with_capacity(SPILL_WRITE_BUFFER_BYTES, file),
))
})
.collect::<Result<Vec<_>>>()?
.into_iter()
.unzip();
Ok(Self { paths, writers })
}
fn push(&mut self, tx: &CompareTransaction) -> Result<()> {
let mut hasher = DefaultHasher::new();
tx.signature.hash(&mut hasher);
let index = (hasher.finish() % self.writers.len() as u64) as usize;
let writer = &mut self.writers[index];
serde_json::to_writer(&mut *writer, tx)?;
writer.write_all(b"\n")?;
Ok(())
}
fn finish(self) -> Result<Vec<PathBuf>> {
for mut writer in self.writers {
writer.flush()?;
}
Ok(self.paths)
}
}
pub(super) fn partition_count(baseline: &Path, experiment: &Path) -> Result<usize> {
let len = |p: &Path| -> Result<u64> {
Ok(std::fs::metadata(p)
.with_context(|| format!("failed to stat {}", p.display()))?
.len())
};
let max_len = len(baseline)?.max(len(experiment)?);
Ok(usize::try_from(max_len.div_ceil(TARGET_PARTITION_BYTES))
.unwrap_or(MAX_PARTITIONS)
.clamp(1, MAX_PARTITIONS))
}
#[derive(Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
enum SlimEvent {
Metadata(#[allow(dead_code)] SimulationMetadata),
SessionStarted(IgnoredAny),
Tx(SlimTransaction),
Diff(IgnoredAny),
Summary(SimulationSummary),
SessionCompleted(IgnoredAny),
}
#[serde_with::serde_as]
#[derive(Deserialize)]
struct SlimTransaction {
slot: u64,
#[serde_as(as = "serde_with::DisplayFromStr")]
signature: Signature,
success: bool,
error: Option<String>,
#[serde(default)]
compute_units: Option<u64>,
logs: LogCount,
sol_changes: Vec<SolChange>,
token_changes: Vec<TokenChange>,
}
impl From<SlimTransaction> for CompareTransaction {
fn from(tx: SlimTransaction) -> Self {
Self {
slot: tx.slot,
signature: tx.signature,
success: tx.success,
error: tx.error,
compute_units: tx.compute_units,
log_count: tx.logs.0,
sol_changes: tx.sol_changes,
token_changes: tx.token_changes,
}
}
}
struct LogCount(usize);
impl<'de> Deserialize<'de> for LogCount {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct CountVisitor;
impl<'de> Visitor<'de> for CountVisitor {
type Value = LogCount;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("an array of log lines")
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<LogCount, A::Error> {
let mut count = 0;
while seq.next_element::<IgnoredAny>()?.is_some() {
count += 1;
}
Ok(LogCount(count))
}
}
deserializer.deserialize_seq(CountVisitor)
}
}
pub(super) fn load_side(
path: &Path,
partitions: usize,
spill: &Path,
label: &str,
) -> Result<LoadedSide> {
let mut sink = RecordSink::new(partitions, spill, label)?;
let file = File::open(path).with_context(|| format!("failed to read {}", path.display()))?;
let mut seen_metadata = false;
let mut tx_lines = 0_usize;
let mut summary_total: Option<usize> = None;
let scan = scan_ndjson_events(BufReader::new(file), path, &mut |event| {
match event {
SlimEvent::Metadata(_) => seen_metadata = true,
SlimEvent::Tx(tx) => {
tx_lines += 1;
sink.push(&CompareTransaction::from(tx))?;
}
SlimEvent::Summary(summary) => summary_total = Some(summary.total_transactions),
SlimEvent::SessionStarted(_) | SlimEvent::Diff(_) | SlimEvent::SessionCompleted(_) => {}
}
Ok(())
})?;
if let NdjsonScan::NotAnEnvelopeStream = scan {
return Err(not_an_ndjson_stream(path));
}
if !seen_metadata {
return Err(missing_metadata_envelope(path));
}
let Some(total_transactions) = summary_total else {
return Err(eyre::eyre!(
"{} has no `summary` line: the run did not finish (it was stopped or is still \
running). Re-run it to completion before comparing",
path.display()
));
};
if tx_lines != total_transactions {
return Err(eyre::eyre!(
"{} has {tx_lines} transaction line(s), but its `summary` line counts \
{total_transactions}: the file is incomplete. Re-run it before comparing",
path.display()
));
}
Ok(LoadedSide {
partitions: sink.finish()?,
total_transactions,
})
}
pub(super) fn read_partition(path: &Path) -> Result<HashMap<Signature, CompareTransaction>> {
let file = File::open(path).with_context(|| format!("failed to read {}", path.display()))?;
let mut reader = BufReader::new(file);
let mut line = String::new();
let mut records: HashMap<Signature, CompareTransaction> = HashMap::new();
loop {
line.clear();
if reader.read_line(&mut line)? == 0 {
return Ok(records);
}
let tx: CompareTransaction = serde_json::from_str(&line)?;
match records.entry(tx.signature) {
Entry::Vacant(vacant) => {
vacant.insert(tx);
}
Entry::Occupied(mut occupied) => {
if tx.slot >= occupied.get().slot {
occupied.insert(tx);
}
}
}
}
}