Skip to content

Switch to struct-based databases - #1462

Open
ChayimFriedman2 wants to merge 3 commits into
salsa-rs:masterfrom
ChayimFriedman2:perf-exp
Open

ChayimFriedman2 wants to merge 3 commits into
salsa-rs:masterfrom
ChayimFriedman2:perf-exp

Conversation

@ChayimFriedman2

@ChayimFriedman2 ChayimFriedman2 commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

See individual commits.

@netlify

netlify Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

👷 Deploy request for salsa-rs pending review.

Visit the deploys page to approve it

Name Link
🔨 Latest commit 9ff2b2f

@ChayimFriedman2
ChayimFriedman2 marked this pull request as draft December 3, 2026 07:57
@codspeed

codspeed Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will improve performance by 8.11%

⚡ 38 improved benchmarks
✅ 64 untouched benchmarks
⏩ 2 skipped benchmarks1

Performance Changes

Mode Benchmark BASE HEAD Efficiency
⚡ Walltime parallel_fast_path[NoEviction] 39.4 µs 32 µs +23.11%
⚡ Walltime project_check_then_incremental[NoEviction] 812.1 µs 678 µs +19.77%
⚡ Walltime parallel_fast_path[Sieve] 44 µs 39.6 µs +11.25%
⚡ Walltime one_hit_wonders[NoEviction] 126.4 µs 114.1 µs +10.79%
⚡ Walltime mixed_access[(NoEviction, 64)] 1.3 ms 1.2 ms +10.58%
⚡ Walltime mixed_access[(NoEviction, 256)] 1.3 ms 1.2 ms +10.49%
⚡ Walltime project_check_then_incremental[Sieve] 930.2 µs 842.8 µs +10.37%
⚡ CPU Simulation disabled_eviction[Lru] 327.5 µs 297.3 µs +10.15%
⚡ Walltime phase_change[(NoEviction, 64)] 1.4 ms 1.3 ms +9.97%
⚡ Walltime phase_change[(NoEviction, 256)] 1.4 ms 1.3 ms +9.45%
⚡ CPU Simulation fast_path_and_sweep[NoEviction] 328.1 µs 299.8 µs +9.44%
⚡ CPU Simulation disabled_eviction[NoEviction] 325.6 µs 297.6 µs +9.42%
⚡ CPU Simulation fast_path[NoEviction] 325.6 µs 297.6 µs +9.42%
⚡ CPU Simulation disabled_eviction[Sieve] 325.9 µs 297.9 µs +9.4%
⚡ Walltime one_hit_wonders[Sieve] 150.5 µs 137.8 µs +9.25%
⚡ CPU Simulation fast_path_and_sweep[Sieve] 351.1 µs 322.7 µs +8.78%
⚡ CPU Simulation fast_path[Sieve] 348.4 µs 320.4 µs +8.73%
⚡ CPU Simulation cached_same_revision_supertype 99.1 µs 91.2 µs +8.67%
⚡ CPU Simulation cached_same_revision 100 µs 92.5 µs +8.1%
⚡ Walltime scan_resistance[NoEviction] 133.9 µs 124.4 µs +7.63%
... ... ... ... ... ...

ℹ️ Only the first 20 benchmarks are displayed. Go to the app to view all benchmarks.

Tip

Curious why performance improved? Comment @codspeedbot explain why performance improved on this PR, or directly use the CodSpeed MCP with your agent.


Comparing ChayimFriedman2:perf-exp (9ff2b2f) with master (c2b9fe8)

Open in CodSpeed

Footnotes

  1. 2 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@ChayimFriedman2

ChayimFriedman2 commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor Author

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 InheritsDb trait. At the top of the hierarchy there is always salsa::Storage, and InheritsDb ensures that we can access it just by casting the pointer. InheritsDb itself could be simpler for Salsa needs (no need for a full chain), but the current trait simplifies user code (you can see it a little bit in the tests here, and more in the proc macro I have for r-a).

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.
@ChayimFriedman2 ChayimFriedman2 changed the title Perf experiment, I need to organize this Switch to struct-based databases Dec 3, 2026
@ChayimFriedman2
ChayimFriedman2 marked this pull request as ready for review December 3, 2026 13:26
@ChayimFriedman2

Copy link
Copy Markdown
Contributor Author

This should be ready now.

@MichaReiser

Copy link
Copy Markdown
Contributor

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.

@ChayimFriedman2

ChayimFriedman2 commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor Author

The commit messages are very elaborate and explain everything needed.

@ChayimFriedman2

Copy link
Copy Markdown
Contributor Author

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.

@MichaReiser

MichaReiser commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

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.

@ChayimFriedman2

Copy link
Copy Markdown
Contributor Author

First, I'll note that this is not that big change, conceptually. In rust-analyzer, search & replace dyn Db for Db mostly cut it (yes it's large but automatic and no need to review), then I followed with small changes.

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 #[salsa::db] in Ruff, it seems that many if not most of the various database methods are just getters, and do not really abstract over behavior - which is the purpose of traits. This is consistent with what I see in rust-analyzer. But because traits cannot have data, we're forced into making getters that return structs defined upstream, breaking encapsulation and also duplicating not little code.

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.

@ChayimFriedman2

Copy link
Copy Markdown
Contributor Author

Looking at your PR (only a little), it seems the agent "fixed" the compilation by basically brute-forcing; using one QueryDb and manually type-erasing and essentially making a trait. I don't know if this puts performance off the table (but it probably does), but it certainly makes the code more ugly instead of less. The idea of this PR is that databases stay separated, and databases carry their own data instead of letting others store it and using getters.

@MichaReiser

MichaReiser commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

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 Storage to the enclosing database

The safety comment in maybe_changed_after says the database belongs to the ingredient. Two handles can share the ingredient and its memos while only one of them is large enough to hold the database type the query expects. The shortest reproducer I found uses an accumulator, so it works within a single revision. Revalidation cast · Accumulator cast

use salsa::{Accumulator, Storage};

#[salsa::db]
#[derive(Default)]
struct Child {
    storage: Storage,
    extra: u64,
}

thread_local! {
    static CHILD: Child = Child::default();
}

#[salsa::accumulator]
#[derive(Debug)]
struct Note(u64);

#[salsa::tracked(returns(copy))]
fn child(db: &Child) {
    Note(db.extra).accumulate(db);
}

#[salsa::tracked(returns(copy))]
fn parent(_db: &Storage) {
    CHILD.with(child);
}

#[test]
fn collect_from_cloned_storage() {
    let storage = CHILD.with(|db| {
        parent(db);
        db.storage.clone()
    });

    assert_eq!(parent::accumulated::<Note>(&storage)[0].0, 0);
}

During parent(db), the two queries borrow the same database through different types. The thread-local gives parent a safe way to call child with the full &Child, and Salsa records the parent → child dependency. Later, parent::accumulated(&storage) follows that edge using the standalone clone. downcast_unchecked constructs a &Child at the address of the clone, where there’s no space for extra. Miri reports that the reference extends beyond the allocation. The original Child is still alive.

I also reproduced this through ordinary revalidation after a write. What would let Salsa establish that the handle used to follow the edge can provide the concrete database the dependency needs? The offset-zero guarantee lets us go from &Child to &Storage. Going back requires knowing which object we borrowed.

2. #[salsa::db] can generate an invalid InheritsDb impl

The macro selects the first field before conditional compilation. For example, this compiles and gives Deref and InheritsDb::parent different addresses for the same storage. Macro expansion

#[salsa::db]
#[derive(Default)]
struct Db {
    #[cfg(any())]
    storage: salsa::Storage,
    prefix: usize,
    storage: salsa::Storage,
}

Rust removes the first declaration. The generated &self.storage resolves to the surviving field after prefix, while parent() casts the address of prefix to &Storage. Calling current_revision() through that reference makes Miri report an invalid Arc pointer.

There’s also a case where the offset is correct and the inferred field type is wrong.

use salsa::Storage;

#[salsa::db]
#[derive(Default)]
struct Db<Storage = Box<salsa::Storage>> {
    storage: Storage,
}

Inside the struct, Storage names the type parameter. The generated impl omits the parameter, so Storage there resolves to the import. &self.storage type-checks because &Box<Storage> coerces to &Storage, but parent() treats the box pointer itself as an inline Storage. Miri reports an out-of-bounds reference. If we keep the unsafe impl, we need to establish both the offset and the exact type of the compiled field. Rejecting unsupported generics would address the second example.

3. Can we keep attach_allow_change?

I tracked down the attachment panic in the ty port. A request attaches its database and starts a Rayon operation with a clone per job. Rayon can run a job on the same thread as the request. attach_allow_change temporarily installs the job’s handle and restores the request’s handle when the job returns or unwinds. Replacing it with attach panics as soon as the job starts because the clone has a different address. I reproduced this on 9ff2b2f with a one-thread pool and one item, outside any active tracked query. Could we keep the scoped switch with &Storage and retain the cancelled_switch_restores_the_outer_query_handle test? ty call site · Failing ty job

4. Requiring storage first changes when a writer can resume

ty deliberately declares storage last in ProjectDatabase. When a worker drops its database, it releases its system: Arc<_> before dropping the storage handle that wakes the writer. ProjectDatabase::system_mut relies on that order when it calls Arc::get_mut immediately after trigger_cancellation() returns. With storage first, the writer can wake while the worker still holds its system. I paused a worker during field destruction and checked the strong count when cancellation returned. It was 1 with the original field order and 2 with the required order. The ty port compensates with a custom Drop that explicitly releases the application state first. This is one reason I’d like to evaluate concrete query parameters independently of the layout requirement. Original field order · Custom Drop in the port

Smaller migration issues

  • db.attach(|db| query(db)) now passes &Storage to the closure through autoderef. Once query takes &Db, this fails to compile. Could the method attach the storage and pass the original &Self to the closure?
  • With detailed-trace and a DEBUG subscriber, DatabaseImpl::default().trigger_cancellation() logs DidSetCancellationFlag. The migrated Storage::default() passes None for the event callback and loses that output.
  • The database tutorial still tells readers to declare Storage<Self> and implement salsa::Database. It also includes the db_impl anchor deleted from the calculator example. The parser and cycle examples need the new query signatures too. Database tutorial

@MichaReiser

Copy link
Copy Markdown
Contributor

Looking at your PR (only a little), it seems the agent "fixed" the compilation by basically brute-forcing; using one QueryDb and manually type-erasing and essentially making a trait. I don't know if this puts performance off the table (but it probably does), but it certainly makes the code more ugly instead of less. The idea of this PR is that databases stay separated, and databases carry their own data instead of letting others store it and using getters.

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

@ChayimFriedman2

Copy link
Copy Markdown
Contributor Author

Looked at it, actually quite nice job.

  1. I already realized Clone can be unsound, but thought it will only matter to my macro and not this minimalist macro. Well, turn out I was wrong 😄 The problem is that Clone can cut a database (that's essentially C++'s baseclass slicing...). It's possible to fix I believe by only allowing to clone "leaf" databases, but I haven't figured out the details yet.
  2. That's macro shenanigans that I tried to protect from, and nobody will meet anyway, but worth fixing.
  3. That's not a problem. I thought nobody used attach_allow_change() except r-a and we no longer use it, but it can easily be reintroduced.
  4. That should be possible to fix in ty via ManuallyDrop and some unsafe. Ideally Rust would let you customize the drop order irrelevant to the offsets in memory, but not today. That's not really possible to fix in Salsa (except by making the macro more complicated and automatically handling custom drop order), because if it's last we don't know at what offset it is.

@MichaReiser

Copy link
Copy Markdown
Contributor

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"]);
}

@ChayimFriedman2

Copy link
Copy Markdown
Contributor Author

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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants