formualizer-eval 0.8.3

High-performance Arrow-backed Excel formula engine with dependency graph and incremental recalculation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
use std::collections::{BTreeMap, BTreeSet};
use std::time::{Duration, Instant};

use formualizer_common::RangeAddress;

use super::{EvaluationBudgets, VertexId};
use crate::formula_plane::region_index::Region;
use crate::formula_plane::runtime::FormulaSpanRef;
use crate::reference::CellRef;

pub type RequestId = u64;

#[cfg(test)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum TargetPreparationFault {
    #[default]
    None,
    AfterDiscovery,
    FinalRevisionValidation,
    FinalGraphValidation,
    Admission,
    Reservation,
    BeforeFirstMutation,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum EvaluationTarget {
    Cell {
        sheet: String,
        row: u32,
        col: u32,
    },
    Range(RangeAddress),
    Name {
        name: String,
        scope_sheet: Option<String>,
    },
    Table {
        name: String,
        selection: TableSelection,
    },
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) enum TargetProducer {
    Legacy(VertexId),
    Span {
        span_ref: FormulaSpanRef,
        demanded: Region,
    },
    Symbol(VertexId),
    ValueOnly(CellRef),
}

#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub enum TableSelection {
    #[default]
    Whole,
    Headers,
    Data,
    Totals,
    Column(String),
    Columns {
        start: String,
        end: String,
    },
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum OpaquePreparePolicy {
    #[default]
    Widen,
    Error,
}

#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PrepareScope {
    #[default]
    Exact,
    Sheets(Vec<String>),
    Workbook,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum OpaqueReason {
    DynamicReference,
    RuntimeTextReference,
    UnknownFunction,
    UnknownCustomFunction,
    UnresolvedCrossSheetBinding,
    UnresolvedName,
    UnresolvedTable,
    FormulaName,
    DeferredSourcePackage,
    UnsupportedSourceSemantics,
    UncertainDefaultSheetBinding,
}

/// Controls that apply to a whole target evaluation: preparation *and*
/// evaluation. Cancellation and the deadline are hoisted onto the engine for the
/// duration of the call, so every checkpoint in both phases observes them.
#[derive(Clone, Debug)]
pub struct TargetEvalOptions<'a> {
    pub request_id: Option<RequestId>,
    pub cancel: Option<crate::engine::CancelToken>,
    pub deadline: Option<Instant>,
    pub budgets: Option<&'a EvaluationBudgets>,
    pub opaque_policy: OpaquePreparePolicy,
}

impl Default for TargetEvalOptions<'_> {
    fn default() -> Self {
        Self {
            request_id: None,
            cancel: None,
            deadline: None,
            budgets: None,
            opaque_policy: OpaquePreparePolicy::Widen,
        }
    }
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct PreparationRevision {
    pub graph: u64,
    /// Raw FormulaPlane epoch. Kept separate from each authority-index counter so
    /// unrelated component revisions cannot collide through arithmetic folding.
    pub authority: u64,
    pub authority_indexes: u64,
    pub authority_indexed_plane: u64,
    pub staged: u64,
    pub symbols: u64,
    pub semantic: u64,
    pub provider: Option<u64>,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum PreparationOutcome {
    #[default]
    Prepared,
    CompatibilityPrepared,
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct PreparedTargetGraphReport {
    pub request_id: RequestId,
    pub requested_targets: usize,
    pub normalized_regions: usize,
    pub normalized_target_list: Vec<EvaluationTarget>,
    pub selected_staged_cells: usize,
    /// Total family proposals owned by the whole deferred packages selected by
    /// this request. Selection and consumption are package-atomic.
    pub selected_source_families: usize,
    pub retained_staged_cells: usize,
    pub selected_cells: Vec<RangeAddress>,
    pub retained_cells: Vec<RangeAddress>,
    pub widened_scope: PrepareScope,
    pub widening_reasons: Vec<OpaqueReason>,
    pub revisions: PreparationRevision,
    pub commit_window: Duration,
    pub estimated_scratch_bytes: u64,
    pub observed_scratch_bytes: u64,
    pub estimated_commit_work: u64,
    pub actual_commit_work: u64,
    pub outcome: PreparationOutcome,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct StagedFormulaLease {
    pub(crate) row: u32,
    pub(crate) col: u32,
    pub(crate) generation: u64,
    pub(crate) insertion_order: u64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct StagedFormulaPresence {
    generation: u64,
    insertion_order: u64,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct StagedPackageLease {
    pub(crate) generation: u64,
    pub(crate) family_count: usize,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct StagedPackageRect {
    start_row: u32,
    start_col: u32,
    end_row: u32,
    end_col: u32,
}

impl StagedPackageRect {
    fn intersects(self, start_row: u32, start_col: u32, end_row: u32, end_col: u32) -> bool {
        self.start_row <= end_row
            && start_row <= self.end_row
            && self.start_col <= end_col
            && start_col <= self.end_col
    }
}

#[derive(Clone, Debug)]
struct StagedPackagePresence {
    generation: u64,
    family_count: usize,
    geometry: Vec<StagedPackageRect>,
    fallback_points: BTreeSet<(u32, u32)>,
    geometry_complete: bool,
}

#[derive(Clone, Debug, Default)]
pub(crate) struct StagedFormulaIndex {
    revision: u64,
    next_generation: u64,
    next_insertion_order: u64,
    sheets: BTreeMap<String, BTreeMap<(u32, u32), StagedFormulaPresence>>,
    packages: BTreeMap<String, StagedPackagePresence>,
}

impl StagedFormulaIndex {
    fn bump(&mut self) {
        self.revision = self
            .revision
            .checked_add(1)
            .expect("staged formula index revision exhausted");
    }

    pub(crate) fn revision(&self) -> u64 {
        self.revision
    }

    pub(crate) fn stage(&mut self, sheet: &str, row: u32, col: u32) {
        let generation = self.next_generation;
        self.next_generation = self
            .next_generation
            .checked_add(1)
            .expect("staged formula generation exhausted");
        let entries = self.sheets.entry(sheet.to_string()).or_default();
        let insertion_order = entries.get(&(row, col)).map_or_else(
            || {
                let order = self.next_insertion_order;
                self.next_insertion_order = self
                    .next_insertion_order
                    .checked_add(1)
                    .expect("staged formula insertion order exhausted");
                order
            },
            |entry| entry.insertion_order,
        );
        entries.insert(
            (row, col),
            StagedFormulaPresence {
                generation,
                insertion_order,
            },
        );
        self.bump();
    }

    pub(crate) fn remove(&mut self, sheet: &str, row: u32, col: u32) -> bool {
        let removed = self
            .sheets
            .get_mut(sheet)
            .is_some_and(|entries| entries.remove(&(row, col)).is_some());
        if self.sheets.get(sheet).is_some_and(BTreeMap::is_empty) {
            self.sheets.remove(sheet);
        }
        if removed {
            self.bump();
        }
        removed
    }

    pub(crate) fn clear_sheet(&mut self, sheet: &str) {
        let changed = self.sheets.remove(sheet).is_some() | self.packages.remove(sheet).is_some();
        if changed {
            self.bump();
        }
    }

    pub(crate) fn clear_all(&mut self) {
        if !self.sheets.is_empty() || !self.packages.is_empty() {
            self.sheets.clear();
            self.packages.clear();
            self.bump();
        }
    }

    pub(crate) fn set_package(
        &mut self,
        sheet: &str,
        package: Option<&super::DeferredFormulaPackage>,
    ) {
        let changed = if let Some(package) = package {
            let generation = self.next_generation;
            self.next_generation = self
                .next_generation
                .checked_add(1)
                .expect("staged package generation exhausted");
            let mut geometry = Vec::new();
            for family in &package.families {
                match &family.members {
                    super::SourceFamilyMembers::CompleteDomain(domain) => {
                        let rect = domain.rect();
                        geometry.push(StagedPackageRect {
                            start_row: rect.start.row.saturating_add(1),
                            start_col: rect.start.col.saturating_add(1),
                            end_row: rect.end.row.saturating_add(1),
                            end_col: rect.end.col.saturating_add(1),
                        });
                    }
                    super::SourceFamilyMembers::ExplicitMembers(members) => {
                        geometry.extend(members.as_slice().iter().map(|coord| StagedPackageRect {
                            start_row: coord.row.saturating_add(1),
                            start_col: coord.col.saturating_add(1),
                            end_row: coord.row.saturating_add(1),
                            end_col: coord.col.saturating_add(1),
                        }));
                    }
                }
            }
            geometry.extend(
                package
                    .partitioned_families
                    .iter()
                    .map(|family| StagedPackageRect {
                        start_row: family.declared.start.row.saturating_add(1),
                        start_col: family.declared.start.col.saturating_add(1),
                        end_row: family.declared.end.row.saturating_add(1),
                        end_col: family.declared.end.col.saturating_add(1),
                    }),
            );
            let fallback_points = package
                .source_coordinates
                .iter()
                .map(|coord| (coord.row.saturating_add(1), coord.col.saturating_add(1)))
                .collect();
            let geometry_complete = package.source_geometry_complete
                || package.report.source_formula_records_spooled == 0;
            self.packages.insert(
                sheet.to_string(),
                StagedPackagePresence {
                    generation,
                    family_count: package.families.len() + package.partitioned_families.len(),
                    geometry,
                    fallback_points,
                    geometry_complete,
                },
            );
            true
        } else {
            self.packages.remove(sheet).is_some()
        };
        if changed {
            self.bump();
        }
    }

    pub(crate) fn touch_package(&mut self, sheet: &str) {
        if let Some(package) = self.packages.get_mut(sheet) {
            package.generation = self.next_generation;
            self.next_generation = self
                .next_generation
                .checked_add(1)
                .expect("staged package generation exhausted");
            self.bump();
        }
    }

    pub(crate) fn has_packages(&self) -> bool {
        !self.packages.is_empty()
    }

    pub(crate) fn package_sheets(&self) -> impl Iterator<Item = &str> {
        self.packages.keys().map(String::as_str)
    }

    pub(crate) fn package_for_region(
        &self,
        sheet: &str,
        start_row: u32,
        start_col: u32,
        end_row: u32,
        end_col: u32,
    ) -> Option<Result<StagedPackageLease, ()>> {
        let package = self.packages.get(sheet)?;
        let intersects = package
            .geometry
            .iter()
            .copied()
            .any(|rect| rect.intersects(start_row, start_col, end_row, end_col))
            || package
                .fallback_points
                .range((start_row, 0)..=(end_row, u32::MAX))
                .any(|&(row, col)| col >= start_col && col <= end_col);
        if intersects {
            Some(Ok(StagedPackageLease {
                generation: package.generation,
                family_count: package.family_count,
            }))
        } else if package.geometry_complete {
            None
        } else {
            Some(Err(()))
        }
    }

    pub(crate) fn package_lease_for_sheet(&self, sheet: &str) -> Option<StagedPackageLease> {
        self.packages.get(sheet).map(|package| StagedPackageLease {
            generation: package.generation,
            family_count: package.family_count,
        })
    }

    pub(crate) fn package_lease_matches(&self, sheet: &str, lease: StagedPackageLease) -> bool {
        self.packages.get(sheet).is_some_and(|package| {
            package.generation == lease.generation && package.family_count == lease.family_count
        })
    }

    pub(crate) fn leases_in_region(
        &self,
        sheet: &str,
        start_row: u32,
        start_col: u32,
        end_row: u32,
        end_col: u32,
    ) -> Vec<StagedFormulaLease> {
        let mut leases = self
            .sheets
            .get(sheet)
            .into_iter()
            .flat_map(|entries| entries.range((start_row, 0)..=(end_row, u32::MAX)))
            .filter_map(|(&(row, col), entry)| {
                (col >= start_col && col <= end_col).then_some(StagedFormulaLease {
                    row,
                    col,
                    generation: entry.generation,
                    insertion_order: entry.insertion_order,
                })
            })
            .collect::<Vec<_>>();
        leases.sort_by_key(|lease| lease.insertion_order);
        leases
    }

    pub(crate) fn leases_for_sheet(&self, sheet: &str) -> Vec<StagedFormulaLease> {
        self.leases_in_region(sheet, 1, 1, u32::MAX, u32::MAX)
    }

    pub(crate) fn all_leases(&self) -> Vec<(String, StagedFormulaLease)> {
        let mut leases = self
            .sheets
            .iter()
            .flat_map(|(sheet, entries)| {
                entries.iter().map(move |(&(row, col), entry)| {
                    (
                        sheet.clone(),
                        StagedFormulaLease {
                            row,
                            col,
                            generation: entry.generation,
                            insertion_order: entry.insertion_order,
                        },
                    )
                })
            })
            .collect::<Vec<_>>();
        leases.sort_by_key(|(_, lease)| lease.insertion_order);
        leases
    }

    pub(crate) fn lease_matches(&self, sheet: &str, lease: StagedFormulaLease) -> bool {
        self.sheets
            .get(sheet)
            .and_then(|entries| entries.get(&(lease.row, lease.col)))
            .is_some_and(|entry| {
                entry.generation == lease.generation
                    && entry.insertion_order == lease.insertion_order
            })
    }

    pub(crate) fn ordinary_count(&self) -> usize {
        self.sheets.values().map(BTreeMap::len).sum()
    }

    #[cfg(test)]
    pub(crate) fn package_count(&self) -> usize {
        self.packages.len()
    }
}

/// Former name of [`TargetEvalOptions`]. The struct governs the whole call, not
/// only preparation, so it was renamed before the name was frozen by a release.
#[deprecated(since = "0.8.0", note = "renamed to TargetEvalOptions")]
pub type PrepareTargetsOptions<'a> = TargetEvalOptions<'a>;