Commit Graph

897 Commits

Author SHA1 Message Date
Shubham Mishra f01175078e Marks MutTxId as !Send (#4039)
# Description of Changes

Same as https://github.com/clockworklabs/SpacetimeDB/pull/3972.
Merged the original PR into wrong branch instead of mater :)

---------

Signed-off-by: Shubham Mishra <shivam828787@gmail.com>
Co-authored-by: Phoebe Goldman <phoebe@clockworklabs.io>
2026-01-16 12:18:54 +00:00
Kim Altintop ef61c7c123 In-memory DatabaseLogger (#3961)
This is the second step to make in-memory-only databases not touch the
disk at all.

While at it, also make it so file-backed module logs are streamed in
constant memory where possible.

Depends-on: #3912 

# Expected complexity level and risk

2

# Testing

Added some unit-level tests.

---------

Signed-off-by: Kim Altintop <kim@eagain.io>
Co-authored-by: Phoebe Goldman <phoebe@clockworklabs.io>
2026-01-16 07:10:04 +00:00
Mazdak Farrokhzad 3a3128d6e9 eval_updates_sequential: no queries? => quit early (#4049)
# Description of Changes

In `eval_updates_sequential`, if here are no queries, don't eval updates
at all.
Found via flamegraph. Makes `eval_updates_sequential` take 3.3% of
`commit_and_broadcast_event` instead of 8%.

# API and ABI breaking changes

None

# Expected complexity level and risk

1
2026-01-16 01:25:37 +00:00
Mazdak Farrokhzad 7cff2a6b72 Add a feature flag no-job-core-pinning (#4046)
# Description of Changes

Anther knob for benchmarking only without job core pinning but keeping
other core pinning (tokio background, rayon, etc.).

# API and ABI breaking changes

None

# Expected complexity level and risk

1

# Testing

No semantic changes.
2026-01-15 12:10:43 +00:00
Mazdak Farrokhzad 8544e6cf02 Add Hash indices (#3976)
# Description of Changes

Fixes https://github.com/clockworklabs/SpacetimeDB/issues/1122.

Adds hash indices and exposes them through `#[index(hash)]` for Rust
modules,
with support for typescript and C# to come in follow ups.
On the client/sdk side, for now, any index is backed via a BTree/native
index as it is the most general.

A hash index may only be queried through point scan and never ranged
scans.
Attempting a ranged scan results in an error, with the mechanism
implemented in the previous PR
(https://github.com/clockworklabs/SpacetimeDB/pull/3974).



# API and ABI breaking changes

None

# Expected complexity level and risk

2?

# Testing

A test for ensuring that hash indices cannot be used for range scans is
added.
Tests exercising hash indices will come in the next PR.
2026-01-14 09:44:20 +00:00
Mazdak Farrokhzad 14b346c79c Add error handling for ranged seeks on non-range compat indices (#3974)
# Description of Changes

When doing a ranged seek on a non-ranged index (none such exist yet, but
will be added in a follow up), return an (ABI) error.

Also:

- Use point scans in query execution (`IxScan(Delta)Eq`).
- Refactor table index code with macro `same_for_all_types`.

# API and ABI breaking changes

None

# Expected complexity level and risk

2?

# Testing

Testing the error handling will be possible once hash indices are added
(follow up PR).
2026-01-13 21:53:03 +00:00
Kim Altintop bcf6d77fca Time out database shutdown (#4019)
It is possible that, under pathological conditions, a database has a
huge transaction backlog, or that there is some bug that prevents
progress on draining this backlog upon shutdown.

In order to avoid piling up `exit_module_host` tasks (which we would not
notice), impose a timeout to be specified after which `exit_module_host`
will drop resources without waiting for the shutdown to complete
gracefully.
2026-01-13 15:07:16 +00:00
Mazdak Farrokhzad b6e0af78bd --feature no-core-pinning disables core pinning (#3983)
# Description of Changes

Adds a feature `no-core-pinning` that disables core pinning.

# API and ABI breaking changes

None

# Expected complexity level and risk

1

# Testing

Covered by existing tests.
2026-01-13 12:38:02 +00:00
Shubham Mishra 2bff8d617e deadlock fix: Make procedure tx abis synchronous (#3968)
# Description of Changes
Fixes the deadlock in procedures due to holding tx lock across `async`
abis.
More info can be found here -
https://discordapp.com/channels/931210784011321394/1011381307965722774/1458432377574658060.

This patch converts following procedure abis from `async` to sync, which
may seem problematic but it's not as we already hold tx locks in
reducers while blocking the worker thread.
 
```rust
"spacetime_10.3"::procedure_start_mut_tx,
"spacetime_10.3"::procedure_commit_mut_tx,
"spacetime_10.3"::procedure_abort_mut_tx,

```

# API and ABI breaking changes:
I am surprised that this does not turned out to be ABI breaking change.
Maybe because from wasm side, async abis were always treated as
synchoronous.


# Expected complexity level and risk
2, diff is straightforward but it can have hidden implications.

# Testing
I want someone else to also do the similar testing as mine. Just in
case, I missed something and that appeared it to work.

I did the backward compatible testing as following:

1. I published following module on master branch:
```rust
use spacetimedb::{ProcedureContext, Table};

#[spacetimedb::table(name = my_table)]
struct MyTable {
    a: u32,
    b: u8,
}

#[spacetimedb::procedure]
fn insert_a_value(ctx: &mut ProcedureContext, a: u32, b: u8) {
    ctx.with_tx(|ctx| {
        ctx.db.my_table().insert(MyTable { a, b });
    });
}
```

2. Called a procedure to insert some values: `spacetime call quick
insert_a_value 1 2`
3. Switched to my branch, re-compiled and restarted the server.
4. Called a procedure again with different values, verfied both old and
new values are present.

---------

Signed-off-by: Shubham Mishra <shivam828787@gmail.com>
Co-authored-by: Phoebe Goldman <phoebe@clockworklabs.io>
2026-01-13 07:38:57 +00:00
Ludv1gL 94adfdc328 fix(scheduler): Restore ReducerContext recording for scheduled reducers (#3947)
## Summary

This fixes a regression introduced in commit afe169ac4 ("Fix the issues
with scheduling procedures #3816", Dec 5, 2025) where scheduled reducers
stopped recording their `ReducerContext` to the commitlog.

**Impact:**
- No `inputs` section was written to the commitlog for scheduled
reducers
- The reducer's name, caller, timestamp, and arguments were not
persisted

## Root Cause

The old code in `module_host.rs::call_scheduled_reducer_inner` patched
`tx.ctx` with the `ReducerContext`:

```rust
tx.ctx = ExecutionContext::with_workload(
    tx.ctx.database_identity(),
    Workload::Reducer(ReducerContext { ... }),
);
```

This was removed when the logic moved to `scheduler.rs`. The new code in
`call_reducer_with_tx` only applies the `ReducerContext` when `tx` is
`None` — since the scheduler passes `Some(tx)`, the context was never
applied.

## Fix

Restore the `tx.ctx` patching in `scheduler.rs` before calling
`call_reducer_with_tx`.

## Test Plan

- [ ] Existing tests pass

Co-authored-by: Phoebe Goldman <phoebe@clockworklabs.io>
2026-01-09 17:14:18 +00:00
Kim Altintop 05d4874918 Create db.lock file only for persistent databases (#3912)
This is the first step to make in-memory only databases not touch the
disk at all. Pending is an in-memory only sink for module logs.

Responsibility for the lock file is transferred to `Durability`, which
means that only persistent databases opened for writing acquire the
lock.

As a consequence, the `Durability` trait gains a `close` method that
prevents further writes and drains the internal buffers, even when
multiple `Arc`-pointers to the `Durability` exist.


# Expected complexity level and risk

2

# Testing

Covered by existing tests.
2026-01-08 08:22:37 +00:00
Noa e5e9bbf626 [TS] Implement and use point scan ABI (#3918)
# Description of Changes

TS equivalent of #3863. I also did optimized single-column indices such
that there's a special case that avoids branching.

# Expected complexity level and risk

1 - straightforward and there's Rust precedent to draw from.

# Testing

- [x] Automated testing is sufficient
2026-01-06 20:39:45 +00:00
Shubham Mishra 6694211417 code polish for #3938 (#3952)
# Description of Changes

Exntention of https://github.com/clockworklabs/SpacetimeDB/pull/3938 to
polish some of the code, which was not done in original PR due to hurry.
- Adds some missing commentary.
- code cleaning mostly limited to changed functions signature.

# API and ABI breaking changes

NA

# Expected complexity level and risk
0

# Testing
Exisiting tests should be enough.

---------

Signed-off-by: Shubham Mishra <shivam828787@gmail.com>
Co-authored-by: joshua-spacetime <josh@clockworklabs.io>
2026-01-06 13:14:01 +00:00
Mario Montoya 038622227d Make /v1/database/:name/call/:func call procedures too, remove procedure route (#3883)
# Description of Changes

Closes #3659 

# API and ABI breaking changes

Remove route and alter the semantics of the `call` route on both server
and `cli`

# Expected complexity level and risk

1

# Testing

- [x] Publish module with `procedures` and observe calling the `cli` the
result is print.

---------

Co-authored-by: Phoebe Goldman <phoebe@goldman-tribe.org>
2025-12-31 23:31:02 +00:00
Shubham Mishra 10fd8b2cd0 fix view deadlock (#3938)
# Description of Changes
Fixes a deadlock in the subscription code and HTTP SQL handler that was
caused by calling view methods on the module while holding the
transaction lock.

I tried a couple of approaches to make the closures `Send` for all code
paths that need to hold the transaction while working with views, but
that didn’t work out well. The V8 module communicates with the host
through channels, which would require dynamic dispatch.

In the current approach, all existing methods that were calling views
from the host are now invoked from inside the module itself. In future,
It will be better to move these methods to common place rather than
being scattrered.
2025-12-30 20:02:15 +00:00
Mazdak Farrokhzad 8e3af49f64 Reuse buffers in ServerMessage<BsatnFormat> (#2911)
# Description of Changes

Fixes https://github.com/clockworklabs/SpacetimeDB/issues/2824.

Defines a global pool `BsatnRowListBuilderPool` which reclaims the
buffers of a `ServerMessage<BsatnFormat>` and which is then used when
building new `ServerMessage<BsatnFormat>`s.

Notes:
1. The new pool `BsatnRowListBuilderPool` reports the same kind of
metrics to prometheus as `PagePool` does.
2. `BsatnRowListBuilder` now works in terms of `BytesMut`.
3. The trait method `fn to_bsatn_extend` is redefined to be capable of
dealing with `BytesMut` as well as `Vec<u8>`.
4. A trait `ConsumeEachBuffer` is defined from
`ServerMessage<BsatnFormat>` and down to extract buffers.
`<ServerMessage<_> as ConsumeEachBuffer>::consume_each_buffer(...)` is
then called in `messages::serialize(...)` just after bsatn-encoding the
entire message and before any compression is done. This is the place
where the pool reclaims buffers.

# Benchmarks

Benchmark numbers vs. master using `cargo bench --bench subscription --
--baseline subs` on i7-7700K, 64GB RAM:

```
footprint-scan          time:   [21.607 ms 21.873 ms 22.187 ms]
                        change: [-62.090% -61.438% -60.787%] (p = 0.00 < 0.05)
                        Performance has improved.

full-scan               time:   [22.185 ms 22.245 ms 22.324 ms]
                        change: [-36.884% -36.497% -36.166%] (p = 0.00 < 0.05)
                        Performance has improved.
```

The improvements in `footprint-scan` are mostly thanks to
https://github.com/clockworklabs/SpacetimeDB/pull/2918, but 7 ms of the
improvements here are thanks to the pool. The improvements to
`full-scan` should be only thanks to the pool.

# API and ABI breaking changes

None

# Expected complexity level and risk

2?

# Testing

- Tests for `Pool<T>` also apply to `BsatnRowListBuilderPool`.
2025-12-18 23:02:36 +00:00
joshua-spacetime cb5e7117a7 Make subscribe durable (#3894)
# Description of Changes

With the addition of module-defined views, subscriptions are no longer
read-only as they may invoke view materialization.

The way this works is that a subscription starts off as a mutable
transaction, materializes views if necessary, and then downgrades to a
read-only transaction to evaluate the subscription.

Before this patch, we were calling `commit_downgrade` directly on the
`MutTxId` in order to downgrade the transaction. This would update the
in-memory `CommittedState`, but it wouldn't make the transaction
durable.

This would result in us incrementing the transaction offset of the
in-memory `CommittedState` without writing anything to the commitlog.
This in turn would invalidate snapshots as they would be pointing
further ahead into the commitlog than they should, and so when replaying
from a snapshot we would potentially skip over commits that were not
included in the snapshot.

This patch changes those call sites to use
`RelationalDB::commit_tx_downgrade` which both updates the in-memory
state **and** makes the transaction durable.

**NOTE:** The fact that views are materialized is purely an
implementation detail at this point in time. And technically view tables
are ephemeral meaning they are not persisted to the commitlog. So the
real bug here was that we were updating the tx offset of the in-memory
committed state at all. This is technically fixed by
https://github.com/clockworklabs/SpacetimeDB/pull/3884 and so after
https://github.com/clockworklabs/SpacetimeDB/pull/3884 lands this change
becomes a no-op. However, we still shouldn't be calling `commit` and
`commit_downgrade` directly on a `MutTxId` since in most cases it is
wrong to bypass the durability layer. And without this change, the bug
would still be present were view tables not ephemeral, which they may
not be at some point in the future.

# API and ABI breaking changes

None

# Expected complexity level and risk

1. The change itself is trivial, the bug is not.

# Testing

Adding an automated test for this is not so straightforward. First it's
view related which means we don't have many options apart from a smoke
test, but I don't believe the smoke tests have a mechanism for replaying
the commitlog.

If transaction offsets are supposed to be linear, without any gaps, then
it would be useful to assert that on each append, in which case we could
write a smoke test that would fail as soon as the offsets diverged.
2025-12-18 02:42:11 +00:00
joshua-spacetime a7c605caa9 Resolve algebraic type refs recursively for view type check (#3876)
# Description of Changes

Resolves algebraic type refs recursively in order to check the product
type of a query builder view.

This should fix the issue reported
[here](https://discord.com/channels/1037340874172014652/1448796556366057513).
However I've so far been unsuccessful in trying repro it.

Also adds further commentary to `Typespace::resolve` to make it clear
that it is not recursive.

# API and ABI breaking changes

None

# Expected complexity level and risk

0

# Testing

TODO. So far I haven't been able to repro with a smoketest
2025-12-18 01:24:32 +00:00
Phoebe Goldman 4829616ec5 Ignore system meta-descriptor rows during replay (#3891)
# Description of Changes

Based on #3887 . Review starting from commit 233b48cc4.

We've encountered a commitlog which includes inserts into `st_table`,
`st_column`, &c of the rows which describe `st_view`, `st_view_param`,
&c. This caused replay to fail, as those rows were already inserted
during bootstrapping,
so we got set-semantic duplicate errors. With this commit, we ignore
set-semantic duplicate errors when replaying a commitlog specifically
for rows in system tables which describe system tables.

We also have to do an additional fixup for sequences. This is described
in-depth in comments added at the relevant locations.

# API and ABI breaking changes

N/a

# Expected complexity level and risk

1 - I was careful not to swallow any errors which aren't obviously safe.

# Testing

- [x] Manually replayed commitlog which includes the above mentioned
inserts, got error prior to this commit, no error with this commit.
2025-12-17 21:39:34 +00:00
Kim Altintop e2b4113ffb Async shutdown for database / durability (#3880)
Controlled shutdown of a database should drain the outstanding
transactions
queue(s) and flush them to the durability layer.

With the introduction of another queueing layer in #3868, it became
harder to
observe when or if this process is completed.

This patch thus introduces an explicit (async) shutdown method for
`RelationalDB` and below, which will wait until all submitted
transactions are
either reported durable, or an error occurs in the durability layer.

`RelationalDB` is made `!Clone`, such that shutdown can be initiated in
the
`Drop` impl. Note that this requires access to a tokio runtime, which we
thread
through via the `Persistence` services in order to allow control over
which of
the various runtimes is being used for durability-related tasks.

Also moves `RelationalDB::open` to a blocking thread when a
persistence-enabled
database is constructed by the `HostController` -- this process performs
heavy
I/O and can take a substantial amount of time, during which we don't
want to
block a worker thread.

# API and ABI breaking changes

None

# Expected complexity level and risk

3

# Testing

- [ ] some testing added
- [ ] existing tests still pass
- [ ] `impl Drop for RelationalDB` difficult to test, extra eyeballs
needed

---------

Co-authored-by: Mazdak Farrokhzad <twingoow@gmail.com>
2025-12-17 18:28:42 +00:00
Phoebe Goldman 13614d7515 Add a fault-tolerant commitlog replay mode for use in debugging (#3887)
# Description of Changes

When debugging broken commitlogs, we want to inspect the whole
commitlog, including the part after the first error.
This is in contrast with the way we want to replay in prod, where we'd
rather get a hard error than an incorrect state.

This commit adds a new flag to commitlog replay, `ErrorBehavior`. The
`core` crate passes `ErrorBehavior::FailFast`
when replaying commitlogs to reconstruct databases. Internal tooling
(not in this repository) uses `ErrorBehavior::Warn` to print the
entirety of a broken commitlog.

# API and ABI breaking changes

Changes internal APIs only.

# Expected complexity level and risk

1 - no change to behavior of SpacetimeDB.

# Testing

None.
2025-12-17 14:15:24 +00:00
Kim Altintop a388c48458 Ensure all-ephemeral transactions don't consume a tx offset (#3884)
Views are materialized in mutable transactions, but should not increment
the transaction offset maintained in the committed state.

This fixes storing completely empty transactions in the commitlog, and
maintains that the committed state tx offset is in-sync with the
commitlog's tx offset.

# Expected complexity level and risk

2

# Testing

Added a test.

---------

Signed-off-by: Kim Altintop <kim@eagain.io>
Co-authored-by: Mazdak Farrokhzad <twingoow@gmail.com>
2025-12-16 23:14:21 +00:00
Phoebe Goldman cc2ac5424c Strip sensitive info from HTTP errors (#3878)
# Description of Changes 

`reqwest` includes the full URL in its errors, including query params.
This is unfortunate, as query params can contain sensitive info like API
tokens. It's difficult for modules to clean these themselves, as they
see errors as strings, losing the structure of `reqwest::Error`.
In this commit, we strip query parts out of URLs in errors before
returning them to modules. I've also audited all of the error return
paths in the `http_request` method and left comments justifying why the
unchanged ones are safe.

# API and ABI breaking changes

Only if you consider the format of error messages part of our API, which
I don't. Procedure APIs aren't stable yet anyways.

# Expected complexity level and risk

1

# Testing

None yet - accepting input from reviewers about desired tests if we feel
that's necessary.

- [ ] <!-- maybe a test you want to do -->
- [ ] <!-- maybe a test you want a reviewer to do, so they can check it
off when they're satisfied. -->

---------

Signed-off-by: Phoebe Goldman <phoebe@goldman-tribe.org>
Co-authored-by: Julien Lavocat <JulienLavocat@users.noreply.github.com>
2025-12-16 22:32:17 +00:00
Mazdak Farrokhzad 492e591845 Add WASM point scan ABIs & use them in Rust bindings (#3863)
# Description of Changes

Provides new WASM ABIs:

- `datastore_index_scan_point_bsatn`
- `datastore_delete_by_index_scan_point_bsatn`

These are then used where applicable to speed up `.find(_)` and friends.

Point scans are also used more internally where applicable.

What remains after this is use in C# module bindings and to expose this
in TS as well.

The PR makes TPS go from roughly 36k to 38k TPS on my machine and also
makes a difference in flamegraphs where the time spent in some index
scans are substantially decreased.

# API and ABI breaking changes

None

# Expected complexity level and risk

3? This touches the datastore an how we expose it to modules.

# Testing

Some existing tests now exercise the new ABIs by changing what
`.find(_)` and friends do.

---------

Signed-off-by: Mazdak Farrokhzad <twingoow@gmail.com>
2025-12-12 22:07:54 +00:00
Mazdak Farrokhzad 907d67ec1f wasmtime: pool async stack allocations on unix (#3830)
# Description of Changes

Uses `with_host_stack` to provide a `StackCreator` that pools
`FiberStack`s.
This does not use the pooling instance allocator and is limited to just
stacks.

# API and ABI breaking changes

None

# Expected complexity level and risk

3? Some unsafe and wasmtime internals relied upon.

# Testing

Covered by existing tests.
2025-12-11 07:46:47 +00:00
Shubham Mishra 17b6ee1847 fix automigration bug with auto_inc (#3862)
# Description of Changes
fixes #3861.

While running prechecks for automigration, the `range` passed to
`iter_by_col_range_mut` was of type `AlgebraicValue::I128`, even though
it should have matched the column’s type.

Fix is straightforward by introducing `AlgebraicValue::from_i128`
helper.

# API and ABI breaking changes
NA

# Expected complexity level and risk
1

# Testing

- Modified smoketest to repro reported bug.

---------

Signed-off-by: Shubham Mishra <shivam828787@gmail.com>
Co-authored-by: Mazdak Farrokhzad <twingoow@gmail.com>
2025-12-10 13:18:38 +00:00
Kim Altintop 062649c92e client-api: Send WebSocket messages fragmented (#2931)
RFC 6455, Section 5.4 describes message fragmentation, and we can do
that with tungstenite.

It does seem to help getting control messages (ping, pong, close)
through without head-of-line blocking.

# Expected complexity level and risk

2 - Need to test with clients

# Testing

TBD - some more abstraction is needed due to the difficulty of
synthetically producing a large outgoing message.
2025-12-09 09:21:11 +00:00
Noa af5b04e949 Implement sourcemap handling (#3828)
# Description of Changes

Uses the `sourcemap` crate to map text locations in the bundle to text
locations in the original source code.

# Expected complexity level and risk

1 - essentially only related to diagnostics

# Testing

- [x] Manually tested
- [ ] Add an automated test for backtrace output
2025-12-08 22:29:54 +00:00
Noa afe169ac4a Fix the issues with scheduling procedures (#3816)
# Description of Changes

This reapplies the patch from #3704, and fixes the issues that were
causing it to deadlock.

The reason it was deadlocking was that it allowed for the following
sequence of events:
* `SchedulerActor::handle_queued()` begins mutable tx
* `ModuleHost::disconnect_client()` submits call to `call_reducer(tx:
None)`
* scheduler submits call to `call_reducer(tx: Some)`
* `WasmModuleInstance::disconnect_client` now has to try to take tx
lock, but the scheduler's call_reducer already holds it and is behind it
in the queue

So, I moved most of the logic from `handle_queued` back to being
executed in the module worker thread, but kept the code in
`scheduler.rs` so that it can all be reasoned about locally.

Fixes #3645. Should I uncomment the implementation of
`ExportFunctionForScheduledTable for F: Procedure` now?

# Expected complexity level and risk

2 - there's a chance that this patch hasn't fully fixed the deadlock
issue from #3704, but I'm quite confident.

# Testing

- [x] Manually verified that deadlock no longer occurs - previously,
`while true; do python -m smoketests schedule_reducer -k
test_scheduled_table_subscription; done` would freeze up in only 2 or 3
iterations, but now it can run for 10 minutes without issues.
2025-12-05 22:27:30 +00:00
Piotr Sarnacki e0dc9fb261 Remove energy multiplier from wasmtime fuel calculations (#3832)
# Description of Changes

In the past we've been converting CPU instructions into energy. We are
not doing it on the SpacetimeDB side anymore, thus we should report the
WasmTime fuel directly
2025-12-05 19:09:28 +00:00
Shubham Mishra 013b202861 Views: snapshot to skip ephermeral tables (#3720)
# Description of Changes.
fixes #3715 

The patch makes snapshots to skip ephemeral tables.

# API and ABI breaking changes
NA

# Expected complexity level and risk
1

# Testing

<!-- Describe any testing you've done, and any testing you'd like your
reviewers to do,
so that you're confident that all the changes work as expected! -->

- [ ] <!-- maybe a test you want to do -->
- [ ] <!-- maybe a test you want a reviewer to do, so they can check it
off when they're satisfied. -->

---------

Co-authored-by: joshua-spacetime <josh@clockworklabs.io>
2025-12-05 09:20:41 +00:00
Kim Altintop a959996ba7 Debug "stuck module" issue (#3813)
Adds some logging and times out lock acquisition attempts in the host
controller.

Should help debugging clockworklabs/SpacetimeDBPrivate#2337
2025-12-04 20:23:32 +00:00
Noa c2b8c7fc7f [TS] Implement TextEncoder/TextDecoder with native code (#3800)
# Description of Changes

This implements (a subset of) the TextEncoder/TextDecoder web APIs using
native functions to do the actual `Uint8Array <-> String` conversion.
This should be a good bit faster than the `fast-text-encoding` package.

# Expected complexity level and risk

2 - this introduces new kinds of JS code and host calls to the v8 host,
but they're pretty well encapsulated.

# Testing

- [x] All TS modules make use of these already for encoding/decoding
strings in BSATN - the `fast-text-encoding` polyfill we pull in only
takes effect if the classes don't already exist, so the smoketests
passing means it works.
2025-12-04 20:11:52 +00:00
Mazdak Farrokhzad 55e0c99850 Store SubscriptionMetrics for Update, Subscribe, Unsubscribe in ModuleSubscriptions (#3821)
# Description of Changes

This showed up in flamegraphs, in particular for `Update`, so let's
cache the `SubscriptionMetrics`s.

# API and ABI breaking changes

None

# Expected complexity level and risk

1

# Testing

Covered by existing tests.
2025-12-04 18:36:56 +00:00
Noa 653a2a1bad Update wasmtime to v39 (#3818)
# Description of Changes

As discussed; could possibly improve performance/in general it's good to
keep up with patches, it's been over a year since we last bumped this.

# Expected complexity level and risk

2 - large, important dependency but wasmtime is very solid,
well-engineered software.

# Testing

- [x] smoketests run on wasmtime
2025-12-04 10:53:51 +00:00
Jeffrey Dallatezza 9989416cd3 Update view ABI to support returning queries (#3685)
# Description of Changes

This adds some changes for how we return data from view functions.
Originally, we interpreted the output of a view function as a bsatn
encoding of an array of rows. Since we also want to be able to return
queries from view functions, we need to be able to return different
types too. At this point, this is effectively not a functional change,
since we don't use the new format, and we don't actually try to parse
the new format.

This introduces a new format for view returns, which is a
`ViewResultHeader`, potentially followed by additional data. For
example, if a view were returning rows directly, it would write a
`ViewResultHeader::RowData`, followed by an array of rows. Note that we
could have given that object a byte array with the rows instead of using
a header an a separate object, but that would force us create an extra
copy when encoding and when decoding.

To make this backward compatible with existing views, we have a
different way to return the new format. For v8 views, if they return a
byte array, we assume it is the old format. If they return an object, we
expect the `data` field of that object to be the actual return data.

For wasm views, we interpret a return code of 2 to mean that it uses the
new format.

On the host side, we handle this naively: we will perform the query, and
we will act as though the view has a read dependency on the tables in
the query. In follow up PRs we can make this more efficient.

# API and ABI breaking changes

This is not a breaking change, but it does make the ABI more complicated
(specifically to avoid breaking it).

# Expected complexity level and risk

1.5. This should not affect the existing return style.

# Testing

I've done manual testing of this with a version of the typescript
bindings that returns queries.
2025-12-03 19:56:41 +00:00
Piotr Sarnacki 1fb8c28e9e Actually report reducer fuel used (#3799)
# Description of Changes

In the `call_reducer_with_tx` function we only reported the WASM fuel
used by view evaulation, but not the stats from the actual reducer call.
This PR fixes it and we now properly record it.

# Expected complexity level and risk

1

# Testing

I've tested the change locally. Before the change the reported metrics
were always zero after running any reducer. Now the usage is reported
properly.
2025-12-01 19:26:13 +00:00
John Detter d26f3a10a9 Revert "Procedures: fix scheduling (#3704)" (#3774)
This reverts commit b2e37e8008.

# Description of Changes

<!-- Please describe your change, mention any related tickets, and so on
here. -->

Reverts #3704 which I'm pretty sure contains some sort of bug which is
causing the smoketests to hang.

# API and ABI breaking changes

None

<!-- If this is an API or ABI breaking change, please apply the
corresponding GitHub label. -->

# Expected complexity level and risk

1

<!--
How complicated do you think these changes are? Grade on a scale from 1
to 5,
where 1 is a trivial change, and 5 is a deep-reaching and complex
change.

This complexity rating applies not only to the complexity apparent in
the diff,
but also to its interactions with existing and future code.

If you answered more than a 2, explain what is complex about the PR,
and what other components it interacts with in potentially concerning
ways. -->

# Testing

<!-- Describe any testing you've done, and any testing you'd like your
reviewers to do,
so that you're confident that all the changes work as expected! -->

- [x] CI passing again
2025-11-26 17:06:11 +00:00
Mazdak Farrokhzad b2e37e8008 Procedures: fix scheduling (#3704)
# Description of Changes

Reworks how `SchedulerActor::handle_queued` works so that it first
determines the parameters of the call to a reducer or the parameters of
the call to the procedure. This also enables the removal of the special
case `call_scheduled_reducer`.

Fixes #3645.

# API and ABI breaking changes

None

# Expected complexity level and risk

2

# Testing

A test `schedule_procedure` is added.

---------

Co-authored-by: Noa <coolreader18@gmail.com>
Co-authored-by: Phoebe Goldman <phoebe@goldman-tribe.org>
Co-authored-by: rekhoff <r.ekhoff@clockworklabs.io>
2025-11-26 03:56:53 +00:00
Phoebe Goldman 507b087dd8 Add metrics for recording HTTP requests performed by procedures. (#3745)
# Description of Changes

This commit adds several new metrics to `DB_METRICS` for tracking
procedures' HTTP requests:

- `procedure_http_request_size_bytes`.
- `procedure_http_response_size_bytes`.
- `procedure_num_http_requests`.
- `procedure_num_successful_http_requests`.
- `procedure_num_failed_http_requests`.
- `procedure_num_timeout_http_requests`.
- `procedure_num_in_progress_http_requests`.

See help strings in `crates/datastore/src/db_metrics/mod.rs` for details
on what each of these tracks.

Closes #3712 .

# API and ABI breaking changes

N/a - I don't think we count metrics as a stable API.

# Expected complexity level and risk

2, I guess? If we intend to use these for billing, some of the choices
I've made about tracking may impact our business.

# Testing

None; I don't know how to test Prometheus metrics.

Co-authored-by: Noa <coolreader18@gmail.com>
2025-11-25 17:40:13 +00:00
Mazdak Farrokhzad ed2a18cff7 Bump hashbrown, foldhash; Fix some compile errors in master (#3722)
# Description of Changes

There were mentions of `hashbrown` in the repo that did not go through
`spacetimedb_data_structures::map`.
This caused compile errors on master when running certain tests locally.
These have been replaced with the proper imports.

The PR also bump hashbrown to 0.16.1 and foldhash to 0.2.0.

# API and ABI breaking changes

None

# Expected complexity level and risk

2

# Testing

Covered by existing tests.
2025-11-25 12:17:24 +00:00
joshua-spacetime 75d35d324b Fix realtime update for views (#3747)
# Description of Changes

View tables have private metadata columns that need to be dropped before
sending results to clients. Before this patch we dropped these columns
for sql queries and initial subscriptions, but we didn't drop them after
incremental update which is what this patch does.

# API and ABI breaking changes

None

# Expected complexity level and risk

1

# Testing

- [x] Smoketest
2025-11-25 06:26:44 +00:00
Noa fd524cf275 [TS] Anonymous transactions (#3743)
# Description of Changes

Mirrors the Rust API.

# Expected complexity level and risk

2

# Testing

- [x] Automated procedure testing now enabled for typescript (from
`sdks/rust/tests`)
2025-11-25 02:20:57 +00:00
Noa cb3ac50bdf [TS] Http procedure API (#3731)
# Description of Changes

Provides a fetch-alike API on `ctx.http`. I guess it could just be
`ctx.fetch()` instead of `ctx.http.fetch()`, but I'm not sure if that's
a good idea.

# Expected complexity level and risk

2

# Testing

<!-- Describe any testing you've done, and any testing you'd like your
reviewers to do,
so that you're confident that all the changes work as expected! -->

- [x] Need to verify that this actually works
- [ ] <!-- maybe a test you want a reviewer to do, so they can check it
off when they're satisfied. -->
2025-11-25 01:26:27 +00:00
Noa 72f34a349f [TS] Implement basic procedure calling (#3649)
# Description of Changes

Implements `__call_procedure__` in the TS bindings and host.

# Expected complexity level and risk

2

# Testing

<!-- Describe any testing you've done, and any testing you'd like your
reviewers to do,
so that you're confident that all the changes work as expected! -->

- [ ] <!-- maybe a test you want to do -->
- [ ] <!-- maybe a test you want a reviewer to do, so they can check it
off when they're satisfied. -->
2025-11-24 19:18:33 +00:00
Phoebe Goldman 64606ace26 Print internal error when a procedure call fails in sdk test client (#3725)
# Description of Changes

And also add a `log::warn` call next to a `tracing::warn` call, since
our tests don't seem to report tracing output.

In response to suspicious test flake
https://github.com/clockworklabs/SpacetimeDB/actions/runs/19577977435/job/56068366154?pr=3409
.

# API and ABI breaking changes

N/a

# Expected complexity level and risk

1

# Testing

N/a
2025-11-24 17:33:00 +00:00
Piotr Sarnacki 0491b5e8a2 Add spacetime_worker_reducer_returned_errors_total metric (#3613)
# Description of Changes

Currently, we have a metric for reducer panics called
`spacetime_worker_wasm_instance_errors_total`. This commit adds a metric
for tracking errors returned from the module, like for example an Err
result in Rust, or throwing a SenderError in TypeScript

This will be needed for the web database overview dashboard, but it
should be useful for tracking sender errors in general.

# Expected complexity level and risk

1

# Testing

- [x] I've tested the change locally verifying the counter increments
when an instance returns an error

---------

Co-authored-by: Tyler Cloutier <cloutiertyler@users.noreply.github.com>
2025-11-24 14:13:19 +00:00
Piotr Sarnacki 827bb9b54f Add metrics for subscription queries (#3661)
# Description of Changes

We have some metrics measuring various lower level things like index
scans, but at the moment we have no easy way to figure out which columns
might need an index. This commit introduces three new metrics that
provide that information by labeling count, latency, and number of rows
canned along with the scan type (index scan, table scan, mixed scan) and
info about unindexed columns.
# API and ABI breaking changes

None

# Expected complexity level and risk

2

I'm honestly not sure. I don't think it's overly complex, but it adds
some overhead in the subscriptions initial query path.

# Testing

- [x] I've tested the changes locally
2025-11-24 12:59:14 +00:00
Shubham Mishra 582c846c11 Views: index readsets (#3706)
# Description of Changes
Precise index readsets

fixes #https://github.com/clockworklabs/SpacetimeDBPrivate/issues/2118

# API and ABI breaking changes
NA

# Expected complexity level and risk
2.5

Potential to regress performance.

# Testing
Updated smoketests.
2025-11-22 07:37:32 +00:00
Noa de142d4af9 HTTP followup: remove http dep from spacetimedb_lib (#3719)
# Description of Changes

Follow up to #3684. Moves `Error` and `Timeout` out of lib, so that we
don't have to implement `SpacetimeType` for them, and then removes the
http dependency altogether, so that `lib` can be leaner. I also got rid
of the separate `HttpValue` type, since it only really exists to mirror
the `http` crate and typescript won't make use of it.

# Expected complexity level and risk

1

# Testing

n/a - just code movement.
2025-11-21 06:01:21 +00:00