salsa/salsa-2022-tests/tests/accumulate-from-tracked-fn.rs
Niko Matsakis 9df075b63c reset accumulators on new revisions, etc
Accumulators don't currently work across revisions
due to a few bugs. This commit adds 2 tests to show
the problems and reworks the implementation strategy.

We keep track of when the values in an accumulator were pushed
and reset the vector to empty when the push occurs in a new
revision.

We also ignore stale values from old revisions
(but update the revision when it is marked as validated).

Finally, we treat an accumulator as an untracked read,
which is quite conservative but correct. To get better
reuse, we would need to (a) somehow determine when different
values were pushed, e.g. by hashing or tracked the old values;
and (b) have some `DatabaseKeyIndex` we can use to identify
"the values pushed by this query".

Both of these would add overhead to accumulators and I didn'τ
feel like doing it, particularly since the main use case for
them is communicating errors and things which are not typically
used from within queries.
2022-08-17 06:47:11 -04:00

94 lines
2 KiB
Rust

//! Accumulate values from within a tracked function.
//! Then mutate the values so that the tracked function re-executes.
//! Check that we accumulate the appropriate, new values.
use salsa_2022_tests::{HasLogger, Logger};
use expect_test::expect;
use test_log::test;
#[salsa::jar(db = Db)]
struct Jar(List, Integers, compute);
trait Db: salsa::DbWithJar<Jar> + HasLogger {}
#[salsa::input]
struct List {
value: u32,
next: Option<List>,
}
#[salsa::accumulator]
struct Integers(u32);
#[salsa::tracked]
fn compute(db: &dyn Db, input: List) {
eprintln!(
"{:?}(value={:?}, next={:?})",
input,
input.value(db),
input.next(db)
);
let result = if let Some(next) = input.next(db) {
let next_integers = compute::accumulated::<Integers>(db, next);
eprintln!("{:?}", next_integers);
let v = input.value(db) + next_integers.iter().sum::<u32>();
eprintln!("input={:?} v={:?}", input.value(db), v);
v
} else {
input.value(db)
};
Integers::push(db, result);
eprintln!("pushed result {:?}", result);
}
#[salsa::db(Jar)]
#[derive(Default)]
struct Database {
storage: salsa::Storage<Self>,
logger: Logger,
}
impl salsa::Database for Database {
fn salsa_event(&self, _event: salsa::Event) {}
fn salsa_runtime(&self) -> &salsa::Runtime {
self.storage.runtime()
}
}
impl Db for Database {}
impl HasLogger for Database {
fn logger(&self) -> &Logger {
&self.logger
}
}
#[test]
fn test1() {
let mut db = Database::default();
let l0 = List::new(&mut db, 1, None);
let l1 = List::new(&mut db, 10, Some(l0));
compute(&db, l1);
expect![[r#"
[
11,
1,
]
"#]]
.assert_debug_eq(&compute::accumulated::<Integers>(&db, l1));
l0.set_value(&mut db, 2);
compute(&db, l1);
expect![[r#"
[
12,
2,
]
"#]]
.assert_debug_eq(&compute::accumulated::<Integers>(&db, l1));
}