Repository navigation
Switch to struct-based databases - #1462
ChayimFriedman2 wants to merge 3 commits into
Conversation
👷 Deploy request for salsa-rs pending review.Visit the deploys page to approve it
|
Merging this PR will improve performance by 8.11%
Performance Changes
Tip Curious why performance improved? Comment Comparing Footnotes
|
|
Impressive. It'll take me more time to organize that, but I'll comment on the general idea now for others. So for a long time I disliked that databases are traits. IMO with the way new Salsa works, this doesn't really give us anything, and it does have disadvantages: perf-wise, it forces virtual calls and a db to be in two registers instead of one (or spilled), and behavior-wise, it precludes sharing data (and not just behavior) in a database, a situation I would like to have in rust-analyzer and even appeared here in the tests. So I refactored (a very breaking change but migration is pretty easy, for r-a I also have a proc macro that allows you to keep your traits and we might want (or may not) to upstream). Now, a database is a struct. It forms a "inheritance chain" via the The changes for Salsa itself are not that large, but pretty much all tests needed to change. This was mostly search & replace (though it did involve not little manual work) and I will separate that to ease review. |
The `#[db]` macro can no longer be applied to a trait or impl. When applied to a struct, another database has to be the first field, and we say our database "inherits" from it. This is represented via the `InheritsDb` trait. The root of all database inheritance chains is `salsa::Storage`.
A crucial part is that via unsafe and macros we manage to guarantee that a super-database is always located at offset 0. That makes converting between inheriting databases essentially free, and critically, since every database has `Storage` as an ancestor, that means we can get the associated `Storage` (and from it, `Zalsa` and `ZalsaLocal`) with zero virtual calls.
This has two main advantages: performance and clarity. Performance-wise, this avoids virtual call and makes a database handle one machine word instead of two. Furthermore many methods used to keep their `&Zalsa` and/or `&ZalsaLocal` to save a virtual call, pressuring registers; now, every method that needs at least two of the set {Concrete database, Zalsa, ZalsaLocal} just takes a database handle, which is either `&Storage` if it only needs access to Salsa details or `RawDatabase`, which is a type-erased database that keeps the provenance and lets you (unsafely) downcast, if it needs to call user code with the concrete database.
Compile-time should also be improved since monomorphization was reduced.
Clarity-wise, this allows databases to carry data and not just behavior, which is very useful sometimes.
`#[db]` also implements `Deref` to the super-database to make conversion seamless.
The database traits were significantly refactored; `ZalsaDatabase` and `Database` are gone, instead code accesses the `Storage`, and a new (private) `DatabaseExt` trait was introduced which provides shorthand methods for accessing zalsas from any database (not just `Storage`). `HasStorage` was replaced with the more general `InheritsDb`. Technically we don't need more than one level of indirection - that is, we can allow only subclassing `Storage` directly - but it's useful, and I have a macro in rust-analyzer that uses this to make things even more convenient.
This commit only changes core Salsa code; however this is breaking pretty much every example and test, the next commit will fix that.
Except compile-fail trybuilds. I have to admit that I haven't checked them one-by-one. I used search & replace, replacing `dyn <Db>` with the concrete type needed, then fixing imports etc.. The only notable changes are: - The tests checking attaching of a different database at the same address were removed, since now the address defines the database. - The database definitions themselves deserve a closer look. Most just use `salsa::Storage`, but there are examples of "inheritance" and even two-level inheritance. This is actually a fairly good demonstration how the new semantics are better. I particularly like the `HasLogger` trait that just became a super-database containing the log itself.
One case regressed - a `#[salsa::tracked]` on a struct field now triggers the tracked macro for some reason, and I failed to see why, so I gave up.
b0efa5d to
9ff2b2f
Compare
|
This should be ready now. |
|
This looks interesting. I have an agent port ty to get a sense for the improvements (looks like 4-5% at most). Would you mind writing a PR summary that explains this change. |
|
The commit messages are very elaborate and explain everything needed. |
|
I'll note that while the Salsa improvements are impressive, the benchmarks are of course doing little work besides Salsa. The main effect I believe is better register allocation and also avoiding virtual calls. But an even more important motivation for me is that it enables storing data in a database, you can look at the second commit for a (modest) example. |
|
A summary that presents the motivation in a clearer way would certainly help me review this sooner. This is also a very big change for users. So we should consider alternatives as well. We also see failing server tests in ty with dbs that can't be changed between threads. I have to look into what's causing this https://github.com/astral-sh/ruff/actions/runs/47116996083/job/144291039148?pr=31314. |
|
First, I'll note that this is not that big change, conceptually. In rust-analyzer, search & replace I agree that the motivation is worth expanding on. To clarify, while I expected a perf benefit it was not the main motivation. The main motivation was that databases really want to carry data. I guess it will be more convincing if I'll use ty for examples, so let's do it 😄 (but I don't really know the codebases, just looked now). If I search for For the things that do need virtual calls, I have a macro that fakes a trait with this schema - I can share it if you want, but didn't want to upstream it yet (or at all). A not-less important motivation is that the cost of virtual calls prevent putting data in the database that we would put there otherwise. I don't know how applicable this is to ty, but in r-a we have some data that is very hot (accessed in the trait solver), and because we cannot put it in the database, we pass it in addition which has performance costs and makes the code ugly. |
|
Looking at your PR (only a little), it seems the agent "fixed" the compilation by basically brute-forcing; using one |
|
Thanks, that's very helpful. I plan to go through the findings later myself (might not be this week). If you have time before, here a few Codex findings. I'm not saying that we need to fix all of them (as I said, I didn't review all of them eyt). We may also just need additional assertions in place 1. Following a dependency can cast a standalone
|
It's very possible that codex did a terrible job here. We should probably have a migration guide, so that other projects don't make the same mistake |
|
Looked at it, actually quite nice job.
|
|
I think it now migrated ty properly. One case that it found that is no longer supported is: use salsa::Setter;
use std::collections::HashSet;
mod semantic {
#[salsa::input]
pub struct File {
#[returns(ref)]
pub text: String,
}
#[salsa::db]
pub trait Db: salsa::Database {
fn is_open(&self, file: File) -> bool;
}
#[salsa::tracked(returns(ref))]
pub fn completion_words(db: &dyn Db, file: File) -> Vec<String> {
if !db.is_open(file) {
return Vec::new();
}
file.text(db).split_whitespace().map(str::to_owned).collect()
}
}
// Different crate
use semantic::{File, completion_words};
#[salsa::input]
struct Project {
#[returns(ref)]
open_files: HashSet<File>,
}
#[salsa::db]
trait ProjectDb: semantic::Db {
fn project(&self) -> Project;
}
#[salsa::tracked(returns(copy))]
fn is_file_open(db: &dyn ProjectDb, file: File) -> bool {
db.project().open_files(db).contains(&file)
}
#[salsa::db]
#[derive(Clone, Default)]
struct Editor {
storage: salsa::Storage<Self>,
project: Option<Project>,
}
#[salsa::db]
impl salsa::Database for Editor {}
#[salsa::db]
impl ProjectDb for Editor {
fn project(&self) -> Project {
self.project.unwrap()
}
}
#[salsa::db]
impl semantic::Db for Editor {
fn is_open(&self, file: File) -> bool {
is_file_open(self, file)
}
}
#[test]
fn completions_follow_the_projects_open_files() {
let mut db = Editor::default();
let foo = File::new(&db, "alpha".to_owned());
let bar = File::new(&db, "beta".to_owned());
let project = Project::new(&db, HashSet::from([foo]));
db.project = Some(project);
assert_eq!(completion_words(&db, foo).as_slice(), ["alpha"]);
assert!(completion_words(&db, bar).is_empty());
project.set_open_files(&mut db).to(HashSet::from([bar]));
assert!(completion_words(&db, foo).is_empty());
assert_eq!(completion_words(&db, bar).as_slice(), ["beta"]);
} |
|
Indeed, not all methods are pure data proxies, some do abstract over behavior. Like I said I have a proc macro that abstracts over that, basically by hand-implementing traits with vtables. It looks like: #[db(pub data: AdditionalData)] // The DB will have a `pub data: AdditionalData` field, this is optional.
pub trait Db {
fn foo(&self, ...) -> Foo;
}
// Then in a downstream crate:
#[db]
pub trait SubDb: Db {}
fn foo(db: &SubDb, ...) -> Foo { ... }
fn impl_db<Db: salsa::InheritsDb<Db>>(vtable: &mut DbVtableBuilder<Db>) {
vtable.foo(foo);
}
// And in the leaf DB crate:
#[db]
pub trait LeafDb: SubDb {}
impl LeafDb {
pub fn new() -> Self {
let mut vtable = DbVtableBuilder::<Self>::default();
middle_crate::impl_db(&mut vtable);
Self { storage: SubDb::from_parts(Db::from_parts(salsa::Storage::default(), vtable, AdditionalData::default())) } // This is unsound currently and will change.
}
}I can share the code if you want. |
See individual commits.