Compare commits

..
3 changed files with 89 additions and 262 deletions
+75 -3
View File
@@ -6,6 +6,10 @@ const MAX_XML_PART: u64 = 64 * 1024 * 1024;
/// Most zip entries looked at while validating a written package.
const MAX_ENTRIES: usize = 200_000;
/// Decompressed bytes that comparing one package's relationship kinds may read in total: the
/// relationship parts themselves and the targets whose content is checked.
const RELATIONSHIP_BUDGET: u64 = 512 * 1024 * 1024;
/// Relationship kinds (lower case) whose absence after a save isn't a loss: the calculation chain is
/// a cache Excel rebuilds, and GridCraft never writes it.
pub(super) const REBUILT_KINDS: [&str; 1] = ["calcchain"];
@@ -117,6 +121,30 @@ fn read_zip_part(zip: &mut Zip<'_>, name: &str) -> Result<Vec<u8>, String> {
Ok(buf)
}
enum PartError {
/// Reading the part would spend more than the remaining budget.
OverBudget,
Unreadable,
}
/// Reads a part like [`read_zip_part`], charging the decompressed bytes to `budget`.
fn read_zip_part_within(zip: &mut Zip<'_>, name: &str, budget: &mut u64) -> Result<Vec<u8>, PartError> {
let f = zip.by_name(name).map_err(|_| PartError::Unreadable)?;
// One byte past what is left shows that the part doesn't fit.
let limit = MAX_XML_PART.min(budget.saturating_add(1));
let mut buf = Vec::new();
// Bytes read before a decompression error still count against the budget.
let res = f.take(limit).read_to_end(&mut buf);
let read = buf.len() as u64;
if read > *budget {
*budget = 0;
return Err(PartError::OverBudget);
}
*budget -= read;
res.map_err(|_| PartError::Unreadable)?;
Ok(buf)
}
/// Whether the producer flagged its cached results as stale with `<calcPr fullCalcOnLoad="1">`:
/// libraries that don't calculate write it, and store 0 or nothing as every formula's value.
pub(super) fn full_calc_on_load(bytes: &[u8]) -> bool {
@@ -232,19 +260,30 @@ pub fn validate_package(bytes: &[u8]) -> Result<Vec<String>, String> {
/// nothing are left out, as a save may rightly drop them: a link to a place in the workbook
/// (`#Sheet1!A1`, written as a cell's `location`) and a target part with nothing in it.
pub(super) fn relationship_kinds(bytes: &[u8]) -> Result<BTreeMap<String, String>, String> {
relationship_kinds_within(bytes, RELATIONSHIP_BUDGET)
}
/// [`relationship_kinds`] reading at most `budget` decompressed bytes. `Err` once the relationship
/// parts alone need more: their kinds can't be listed completely.
fn relationship_kinds_within(bytes: &[u8], mut budget: u64) -> Result<BTreeMap<String, String>, String> {
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| format!("not a zip package: {e}"))?;
let names = zip_names(&mut zip);
let by_key: HashMap<String, &String> = names.iter().map(|n| (part_key(n), n)).collect();
// Several relationships name the same part; each fresh check decompressed it again, so
// repeated references to one highly compressible part multiplied the work. The verdict is
// remembered per (part, named content) and the decompression the package can cause is
// budgeted as a whole (finding: repeated decompression).
// budgeted as a whole, the relationship parts included: many large, unreferenced rels parts
// would otherwise each spend a full per-part allowance.
let mut verdicts: HashMap<(String, &'static str), bool> = HashMap::new();
let mut budget: u64 = 512 * 1024 * 1024;
let mut kinds = BTreeMap::new();
for n in names.iter().filter(|n| part_key(n).ends_with(".rels")) {
let Some(src_dir) = rels_source_dir(&part_key(n)) else { continue };
let Ok(els) = read_zip_part(&mut zip, n).and_then(|xml| xml_elements(&xml)) else { continue };
let xml = match read_zip_part_within(&mut zip, n, &mut budget) {
Ok(xml) => xml,
Err(PartError::OverBudget) => return Err(format!("{n}: relationship check stopped at its decompression limit")),
Err(PartError::Unreadable) => continue,
};
let Ok(els) = xml_elements(&xml) else { continue };
for (_, attrs) in els.iter().filter(|(el, _)| el == "Relationship") {
let Some(kind) = attr(attrs, "Type").and_then(|t| t.rsplit('/').next()) else { continue };
let target = attr(attrs, "Target").unwrap_or("");
@@ -329,3 +368,36 @@ fn holds_something_uncached(zip: &mut Zip<'_>, name: &str, marker: &'static str,
buf.clear();
}
}
#[cfg(test)]
mod tests {
use std::io::Write as _;
use super::*;
/// A package with `count` relationship parts of `size` bytes each, none of them describing an
/// existing part.
fn many_rels(count: usize, size: usize) -> Vec<u8> {
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);
let head = r#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom" Target="https://example.com" TargetMode="External"/>"#;
let tail = "</Relationships>";
let filler = " ".repeat(size.saturating_sub(head.len() + tail.len()));
for i in 0..count {
z.start_file(format!("xl/_rels/part{i}.xml.rels"), opts).unwrap();
z.write_all(head.as_bytes()).unwrap();
z.write_all(filler.as_bytes()).unwrap();
z.write_all(tail.as_bytes()).unwrap();
}
z.finish().unwrap().into_inner()
}
#[test]
fn relationship_parts_count_against_the_decompression_budget() {
// Each part fits the per-part allowance, but together they need more than the budget.
let bytes = many_rels(8, 64 * 1024);
assert!(relationship_kinds_within(&bytes, 256 * 1024).is_err());
let kinds = relationship_kinds_within(&bytes, 1024 * 1024).unwrap();
assert_eq!(kinds.get("custom").map(String::as_str), Some("custom"));
}
}
+14 -178
View File
@@ -24,7 +24,7 @@ mod pass_host;
#[cfg(test)]
use graph::Intervals;
pub use graph::{FxHasher, Graph, Key};
use graph::{HashMap, HashSet, Node, Taken};
use graph::{HashMap, HashSet, Node};
use pass_host::{PassHost, spills_as_before};
/// Calculation state kept beside a workbook.
@@ -292,16 +292,17 @@ impl Calc {
}
}
}
// Spill areas of changed anchors also change. They stay rectangles: one seed per spilled
// cell listed the formulas reading the area once per cell.
let mut areas: Vec<(usize, RangeRef)> = cleared;
// Spill areas of changed anchors also change.
for &k in changed {
if let Some(r) = wb.sheet(k.0).and_then(|s| s.spill_ranges.get(&k.1)) {
areas.push((k.0, *r));
seeds.extend(r.iter().map(|c| (k.0, c)));
}
}
for (si, r) in &cleared {
seeds.extend(r.iter().map(|c| (*si, c)));
}
let t0 = prof_now();
let dirty = self.dirty_closure(wb, &seeds, &areas);
let dirty = self.dirty_closure(wb, &seeds);
let t1 = prof_now();
let n = dirty.len();
self.run(wb, dirty, false);
@@ -310,39 +311,16 @@ impl Calc {
}
}
/// The formulas to recalculate after `seeds` and every cell of `areas` changed: the seeds
/// that are formulas, and everything that reads them, directly or through other formulas.
fn dirty_closure(&self, wb: &Workbook, seeds: &[Key], areas: &[(usize, RangeRef)]) -> Vec<Key> {
fn dirty_closure(&self, _wb: &Workbook, seeds: &[Key]) -> Vec<Key> {
let mut seen: HashSet<Key> = HashSet::default();
let mut queue: VecDeque<Key> = VecDeque::new();
// Each range-index entry is listed once in the whole walk: many changed cells under one
// broad reference (or many formulas inside one) would otherwise list every formula reading
// it once per cell, which squared the work.
let mut taken = Taken::default();
let mut deps = Vec::new();
for k in seeds {
if self.graph.nodes.contains_key(k) && seen.insert(*k) {
queue.push_back(*k);
}
deps.clear();
self.graph.dependents_untaken(k.0, k.1, &mut taken, &mut deps);
for d in deps.drain(..) {
if seen.insert(d) {
queue.push_back(d);
}
}
}
for &(si, r) in areas {
if let Some(sh) = wb.sheet(si) {
for (c, _) in sh.cells.iter_range(r) {
if self.graph.nodes.contains_key(&(si, c)) && seen.insert((si, c)) {
queue.push_back((si, c));
}
}
}
deps.clear();
self.graph.dependents_of_range(si, r, &mut deps);
for d in deps.drain(..) {
let mut deps = Vec::new();
self.graph.dependents(k.0, k.1, &mut deps);
for d in deps {
if seen.insert(d) {
queue.push_back(d);
}
@@ -353,9 +331,10 @@ impl Calc {
queue.push_back(*k);
}
}
let mut deps = Vec::new();
while let Some(k) = queue.pop_front() {
deps.clear();
self.graph.dependents_untaken(k.0, k.1, &mut taken, &mut deps);
self.graph.dependents(k.0, k.1, &mut deps);
for d in deps.drain(..) {
if seen.insert(d) {
queue.push_back(d);
@@ -432,7 +411,7 @@ impl Calc {
if spill_changes.is_empty() {
break;
}
dirty = self.dirty_closure(wb, &spill_changes, &[]);
dirty = self.dirty_closure(wb, &spill_changes);
}
// Loops among formulas the run did not evaluate stay listed while they are still formulas.
// Iterative calculation reports none.
@@ -712,149 +691,6 @@ pub(crate) mod tests {
assert!(visited < 64, "visited {visited} nodes for no match");
}
#[test]
fn untaken_queries_list_each_interval_once_in_all() {
// 1,000 ranges over every row of 5,000: point queries at every row used to list all 1,000
// each time (5 million matches); sharing `taken`, each range is listed once in all.
let n = 5_000u32;
let mut iv: Intervals<u32> = Intervals::default();
for t in 0..1_000 {
iv.insert(0, n, t);
}
for r in 0..n {
iv.insert(r, r, 10_000 + r);
}
iv.settle();
let mut taken = Vec::new();
let mut listed = Vec::new();
for row in 0..=n + 3 {
iv.query_untaken(row, row, &mut taken, &mut |t| {
listed.push(*t);
true
});
}
listed.sort_unstable();
let want: Vec<u32> = (0..1_000).chain(10_000..10_000 + n).collect();
assert_eq!(listed, want);
// An entry the caller declines is offered again.
let mut taken = Vec::new();
let mut offered = 0;
for _ in 0..3 {
iv.query_untaken(7, 7, &mut taken, &mut |t| {
if *t == 10_007 {
offered += 1;
}
*t != 10_007
});
}
assert_eq!(offered, 3);
}
#[test]
fn dirty_closure_matches_a_walk_of_every_cell() {
// Random formulas over single cells, narrow ranges and wide (over 64 columns) ranges, some
// removed or left unsettled: the closure equals the one found by listing every dependent
// of every changed cell, area cells included, as before `taken` and areas existed.
use super::{HashSet, Node};
use crate::eval::Area;
use std::collections::VecDeque;
let mut s = 0x2545_F491_4F6C_DD1D;
for case in 0..40 {
let mut wb = Workbook::new();
let mut calc = Calc::new();
let pick = |s: &mut u64, n: u64| (rng(s) % n) as u32;
let mut keys: Vec<Key> = Vec::new();
for _ in 0..300 {
let k = (0, CellRef::new(pick(&mut s, 120), pick(&mut s, 150)));
let mut areas = Vec::new();
for _ in 0..1 + pick(&mut s, 3) {
let start = CellRef::new(pick(&mut s, 120), pick(&mut s, 150));
let end = match pick(&mut s, 3) {
0 => start,
1 => CellRef::new(start.row + pick(&mut s, 40), start.col + pick(&mut s, 5)),
_ => CellRef::new(start.row + pick(&mut s, 20), start.col + 65 + pick(&mut s, 30)),
};
areas.push(Area { sheet: 0, range: RangeRef::new(start, end) });
}
if let Some(sh) = wb.sheet_mut(0) {
sh.cells.set(k.1, Cell::formula(Formula::new("=1")));
}
calc.graph.insert(k, Node { areas, dynamic: false });
keys.push(k);
if rng(&mut s).is_multiple_of(7) {
calc.graph.settle();
}
}
for _ in 0..30 {
let k = keys[(rng(&mut s) % keys.len() as u64) as usize];
calc.graph.remove(k);
if let Some(sh) = wb.sheet_mut(0) {
sh.cells.remove(k.1);
}
}
if case % 2 == 0 {
calc.graph.settle();
}
let seeds: Vec<Key> = (0..1 + pick(&mut s, 25)).map(|_| (0, CellRef::new(pick(&mut s, 140), pick(&mut s, 220)))).collect();
let areas: Vec<(usize, RangeRef)> = (0..pick(&mut s, 3))
.map(|_| {
let start = CellRef::new(pick(&mut s, 120), pick(&mut s, 150));
(0, RangeRef::new(start, CellRef::new(start.row + pick(&mut s, 30), start.col + pick(&mut s, 80))))
})
.collect();
let got: HashSet<Key> = calc.dirty_closure(&wb, &seeds, &areas).into_iter().collect();
// The walk before: every area cell is a seed, and every cell lists all its dependents.
let mut all = seeds.clone();
for (si, r) in &areas {
all.extend(r.iter().map(|c| (*si, c)));
}
let mut want: HashSet<Key> = HashSet::default();
let mut queue: VecDeque<Key> = VecDeque::new();
let mut deps = Vec::new();
for k in &all {
if calc.graph.nodes.contains_key(k) && want.insert(*k) {
queue.push_back(*k);
}
deps.clear();
calc.graph.dependents(k.0, k.1, &mut deps);
queue.extend(deps.iter().copied().filter(|d| want.insert(*d)));
}
while let Some(k) = queue.pop_front() {
deps.clear();
calc.graph.dependents(k.0, k.1, &mut deps);
queue.extend(deps.iter().copied().filter(|d| want.insert(*d)));
}
assert_eq!(got, want, "case {case}");
}
}
#[test]
fn clearing_a_spill_recalculates_formulas_reading_it_once_each() {
// 300 formulas read the area an anchor spills into; clearing the anchor changes all of it
// and every one of them is recalculated (they were listed once per spilled cell).
let mut wb = Workbook::new();
let mut calc = Calc::new();
let set = |wb: &mut Workbook, calc: &mut Calc, at: CellRef, input: &str| {
if let Some(sh) = wb.sheet_mut(0) {
if input.is_empty() {
sh.cells.remove(at);
} else {
sh.cells.set(at, Cell::formula(Formula::new(input)));
}
}
calc.cells_changed(wb, &[(0, at)]);
};
set(&mut wb, &mut calc, CellRef::new(0, 0), "=SEQUENCE(2000)");
for r in 0..300 {
set(&mut wb, &mut calc, CellRef::new(r, 2), "=COUNT(A1:A2000)");
}
assert_eq!(wb.sheet(0).map(|s| s.value(CellRef::new(299, 2))), Some(Value::Number(2000.0)));
set(&mut wb, &mut calc, CellRef::new(0, 0), "");
for r in 0..300 {
assert_eq!(wb.sheet(0).map(|s| s.value(CellRef::new(r, 2))), Some(Value::Number(0.0)), "row {r}");
}
}
/// `rows` rows of six numbers (E:J) and `=SUM(E{r}:J{r})` in K.
fn sum_rows(rows: u32) -> Workbook {
let mut wb = Workbook::new();
-81
View File
@@ -151,54 +151,6 @@ impl<T: Copy + Ord> Intervals<T> {
self.walk(1, 0, self.max_end.len() / 2, p, a, f)
}
/// [`Intervals::query`] that skips entries an earlier call with the same `taken` already
/// took (and whole subtrees of them), so that a series of queries lists each interval once in
/// all. `f` answers whether it took the entry; one it declines is offered again later.
/// `taken` belongs to this index as it is now; start it empty. Pending insertions (a few at
/// most after [`Intervals::settle`]) are offered every time.
pub(super) fn query_untaken(&self, a: u32, b: u32, taken: &mut Vec<bool>, f: &mut dyn FnMut(&T) -> bool) {
for it in &self.pending {
if it.0 <= b && it.1 >= a {
f(&it.2);
}
}
let p = self.items.partition_point(|it| it.0 <= b);
if p == 0 {
return;
}
if taken.len() != self.max_end.len() {
*taken = vec![false; self.max_end.len()];
}
self.walk_untaken(1, 0, self.max_end.len() / 2, p, a, taken, f);
}
/// Returns whether everything under `node` has now been reported (or is dead).
#[allow(clippy::too_many_arguments)]
fn walk_untaken(&self, node: usize, lo: usize, hi: usize, p: usize, a: u32, taken: &mut [bool], f: &mut dyn FnMut(&T) -> bool) -> bool {
if taken.get(node).copied().unwrap_or(true) {
return true;
}
if lo >= p || self.max_end.get(node).is_none_or(|m| *m < a) {
return false;
}
let done = if hi - lo <= 1 {
match (self.items.get(lo), self.dead.get(lo)) {
(Some(it), Some(false)) if it.1 >= a => f(&it.2),
(Some(_), Some(true)) => true,
_ => false,
}
} else {
let mid = lo + (hi - lo) / 2;
let left = self.walk_untaken(2 * node, lo, mid, p, a, taken, f);
let right = self.walk_untaken(2 * node + 1, mid, hi, p, a, taken, f);
left && right
};
if done && let Some(slot) = taken.get_mut(node) {
*slot = true;
}
done
}
fn walk(&self, node: usize, lo: usize, hi: usize, p: usize, a: u32, f: &mut dyn FnMut(&T)) -> usize {
if lo >= p || self.max_end.get(node).is_none_or(|m| *m < a) {
return 1;
@@ -216,13 +168,6 @@ impl<T: Copy + Ord> Intervals<T> {
}
}
/// Range-index entries one dependency walk has already listed (see [`Graph::dependents_untaken`]).
#[derive(Default)]
pub(super) struct Taken {
cols: HashMap<(usize, u32), Vec<bool>>,
wide: HashMap<usize, Vec<bool>>,
}
#[derive(Clone, Debug, Default)]
pub struct Graph {
pub(super) nodes: HashMap<Key, Node>,
@@ -357,32 +302,6 @@ impl Graph {
}
}
/// [`Graph::dependents`] leaving out the formulas whose range reads an earlier call with the
/// same `taken` already listed. A walk over many changed cells that a few broad ranges cover
/// then lists those formulas once, instead of once per cell (which squared the work). The
/// graph must not change while `taken` is in use.
pub(super) fn dependents_untaken(&self, sheet: usize, c: CellRef, taken: &mut Taken, out: &mut Vec<Key>) {
if let Some(v) = self.cell_deps.get(&(sheet, c)) {
out.extend(v.iter().copied());
}
if let Some(v) = self.col_deps.get(&(sheet, c.col)) {
v.query_untaken(c.row, c.row, taken.cols.entry((sheet, c.col)).or_default(), &mut |k| {
out.push(*k);
true
});
}
if let Some(v) = self.wide_deps.get(&sheet) {
// A wide entry is taken once it covers the cell's column too.
v.query_untaken(c.row, c.row, taken.wide.entry(sheet).or_default(), &mut |(c0, c1, k)| {
let hit = *c0 <= c.col && c.col <= *c1;
if hit {
out.push(*k);
}
hit
});
}
}
/// Formulas that read any cell of `range` (a formula can be listed more than once).
pub fn dependents_of_range(&self, sheet: usize, range: RangeRef, out: &mut Vec<Key>) {
if range.count() <= 4096 {