From b311a8a2b631b0664569ce074372c857218291a2 Mon Sep 17 00:00:00 2001 From: clockwork-labs-bot Date: Sun, 13 Sep 2026 08:10:05 -0400 Subject: [PATCH 01/21] docs: fix TypeScript table count return type --- .../00600-clients/00700-typescript-reference.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md b/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md index 68d84fe951d..34100ce7e84 100644 --- a/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md +++ b/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md @@ -924,7 +924,7 @@ Each table or view defined by a module has an accessor method, whose name is the ```typescript class TableHandle { - public count(): number; + public count(): bigint; } ``` From 80116c7d208a392bd32c9a1d9175cf24b975e349 Mon Sep 17 00:00:00 2001 From: clockwork-labs-bot Date: Mon, 14 Sep 2026 08:11:49 -0400 Subject: [PATCH 02/21] docs: clarify environment value preservation --- .../00100-databases/00300-spacetime-publish.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/00200-core-concepts/00100-databases/00300-spacetime-publish.md b/docs/docs/00200-core-concepts/00100-databases/00300-spacetime-publish.md index dd805b69ecf..15d52f35936 100644 --- a/docs/docs/00200-core-concepts/00100-databases/00300-spacetime-publish.md +++ b/docs/docs/00200-core-concepts/00100-databases/00300-spacetime-publish.md @@ -106,7 +106,7 @@ For all available publishing options and flags, see the [`spacetime publish` CLI ### Environment Variables -Modules can declare environment variables for configuration and secrets. Each publish supplies the complete set of values from the target's `env` configuration and declared shell variables. Required values must be supplied on every publish; omitted optional values are removed. The module and its environment update atomically. +Modules can declare environment variables for configuration and secrets. Each publish supplies values from the target's `env` configuration and declared shell variables, then preserves unspecified stored values by default. Required values must exist in the resulting environment; optional values are removed only when you unset them explicitly or use `--replace-env`. The module and its environment update atomically. See [Environment Variables](./00700-environment-variables.md) for declarations, reading values in module code, publishing examples, and private tables for secrets that need to change without republishing. From dc5eb44d9cf2bb3db94722acda4becb8bbdd921e Mon Sep 17 00:00:00 2001 From: clockwork-labs-bot Date: Tue, 15 Sep 2026 08:10:06 -0400 Subject: [PATCH 03/21] docs: fix C# auth reducer snippet --- .../00200-core-concepts/00500-authentication/00500-usage.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/docs/00200-core-concepts/00500-authentication/00500-usage.md b/docs/docs/00200-core-concepts/00500-authentication/00500-usage.md index a022cc1dc65..65c051ba599 100644 --- a/docs/docs/00200-core-concepts/00500-authentication/00500-usage.md +++ b/docs/docs/00200-core-concepts/00500-authentication/00500-usage.md @@ -132,7 +132,9 @@ public static readonly List OIDC_CLIENT_IDS = new() { "client_XXXXXXXXXXXXXXXXXXXXXX", }; -public void Connect(ReducerContext ctx) + +[Reducer(ReducerKind.ClientConnected)] +public static void Connect(ReducerContext ctx) { var claims = ctx.SenderAuth.Jwt ?? throw new Exception("Client connected without JWT"); if (claims.Issuer != "https://auth.spacetimedb.com/oidc") From 7dbd695020c93045057a93247951951b802f49ed Mon Sep 17 00:00:00 2001 From: clockwork-labs-bot Date: Wed, 16 Sep 2026 08:09:57 -0400 Subject: [PATCH 04/21] docs: clarify procedure HTTP decompression --- .../00200-core-concepts/00200-functions/00400-procedures.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/docs/00200-core-concepts/00200-functions/00400-procedures.md b/docs/docs/00200-core-concepts/00200-functions/00400-procedures.md index 30be60eceae..58be1005c97 100644 --- a/docs/docs/00200-core-concepts/00200-functions/00400-procedures.md +++ b/docs/docs/00200-core-concepts/00200-functions/00400-procedures.md @@ -875,6 +875,11 @@ Procedures can't send requests at the same time as holding open a [transaction]( +Procedure HTTP requests automatically accept gzip and Brotli responses and expose the decoded +response body to module code. If you set an `Accept-Encoding` header yourself, the response body is +still decoded by the host, so do not manually decompress it in the module. Headers that describe the +compressed wire body, such as `Content-Encoding` and `Content-Length`, may be absent after decoding. + :::note If no timeout is specified, HTTP requests default to 30 seconds. User-specified timeouts are clamped to a maximum of 180 seconds by the host. ::: From 07fe0ac5868e80c6ea631ef385817dccaf34da8d Mon Sep 17 00:00:00 2001 From: clockwork-labs-bot Date: Thu, 17 Sep 2026 08:10:21 -0400 Subject: [PATCH 05/21] docs: fix TypeScript procedure argument type --- .../00200-core-concepts/00200-functions/00400-procedures.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/00200-core-concepts/00200-functions/00400-procedures.md b/docs/docs/00200-core-concepts/00200-functions/00400-procedures.md index 58be1005c97..0236f5da9d7 100644 --- a/docs/docs/00200-core-concepts/00200-functions/00400-procedures.md +++ b/docs/docs/00200-core-concepts/00200-functions/00400-procedures.md @@ -140,7 +140,7 @@ const myTable = table( const spacetimedb = schema({ myTable }); export default spacetimedb; -export const insertAValue = spacetimedb.procedure({ a: t.u32(), b: t.u32() }, t.unit(), (ctx, { a, b }) => { +export const insertAValue = spacetimedb.procedure({ a: t.u32(), b: t.string() }, t.unit(), (ctx, { a, b }) => { ctx.withTx(ctx => { ctx.db.myTable.insert({ a, b }); }); From 399fb6f311a94a0bd63fa5340bdde59aed439dc7 Mon Sep 17 00:00:00 2001 From: clockwork-labs-bot Date: Tue, 13 Oct 2026 17:13:38 -0400 Subject: [PATCH 06/21] docs: align reconnect agent skills --- skills/csharp-client/SKILL.md | 4 ++-- skills/typescript-client/SKILL.md | 9 +++++++-- skills/unity/SKILL.md | 4 ++-- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/skills/csharp-client/SKILL.md b/skills/csharp-client/SKILL.md index 47ad75496f9..8af6787560d 100644 --- a/skills/csharp-client/SKILL.md +++ b/skills/csharp-client/SKILL.md @@ -54,9 +54,9 @@ Automatic reconnect is opt-in: add `.WithAutomaticReconnect()` to the builder. I Keep calling `FrameTick()` while `IsActive` is false. `IsReconnecting` is true while recovering before the next handshake. Use `.OnDisconnect((conn, error, next) => ...)` and `.OnConnectError((error, next) => ...)` to inspect `NextReconnect?`: a non-null value provides `Attempt` and `Delay`; null means no retry is scheduled. Existing callback overloads still work. -`OnConnect` runs on every successful reconnect, so create the subscription in the example above only on the first connection, or move it after `Build()`. Register row callbacks once as well. The same connection, identity, table handles, and subscriptions survive; each attempt gets a fresh `ConnectionId`. Cached rows stay readable but stale during outages. The SDK replays subscriptions in one batch and emits only net row changes. Subscription `OnApplied` runs again after replay; use it to mark data ready, not for repeated one-time setup. +`OnConnect` runs once per `DbConnection`, on the first successful connection. Successful automatic reconnects invoke `OnAutomaticReconnect` before subscription replay instead. Register subscriptions and row callbacks once, either in `OnConnect` or after `Build()`, and use `OnAutomaticReconnect` for recovery-specific work such as saving a refreshed token. The same connection, identity, table handles, and subscriptions survive; each attempt gets a fresh `ConnectionId`. Cached rows stay readable but stale during outages. The SDK replays subscriptions in one batch and emits only net row changes. Subscription `OnApplied` runs again after replay; use it to mark data ready, not for repeated one-time setup. -For expiring credentials, combine `.WithToken(initialToken)` with `.WithTokenProvider(() => RefreshTokenAsync())`, where your provider returns `Task` for the same identity. The provider is not called for the initial connection. Before retries, it is called when remaining validity is at most 30 seconds or 5% of the token lifetime, whichever is greater, when expiry cannot be read, or after a reused token is rejected. Provider failures retry; rejection of a freshly provided token is terminal. No periodic refresh runs while connected. Disconnecting ignores a pending provider result but does not cancel the provider's own work. +For expiring credentials, combine `.WithToken(initialToken)` with `.WithTokenProvider(() => RefreshTokenAsync())`, where your provider returns `Task` for the same identity. The provider is not called for the initial connection. Before retries, it is called when remaining validity is at most 30 seconds or 5% of the token lifetime, whichever is greater, when expiry cannot be read, or after a reused token is rejected. Provider failures retry; rejection of a freshly provided token is terminal. No periodic refresh runs while connected. After recovery, persist the token passed to `OnAutomaticReconnect` if the application stores tokens. Disconnecting ignores a pending provider result but does not cancel the provider's own work. Calls made while disconnected fail immediately. Pending reducer calls receive `Status.UnknownResult`; pending procedures and one-off queries fail with `UnknownResultException`. These calls may already have executed and are never replayed. Regenerate bindings so unhandled unknown reducer outcomes reach `OnUnhandledReducerError`. diff --git a/skills/typescript-client/SKILL.md b/skills/typescript-client/SKILL.md index 4249daf15a1..ae59a1683f9 100644 --- a/skills/typescript-client/SKILL.md +++ b/skills/typescript-client/SKILL.md @@ -34,7 +34,8 @@ function Root() { .withDatabaseName(MODULE_NAME) .withToken(localStorage.getItem(TOKEN_KEY) ?? undefined) .withAutomaticReconnect() - .onConnect((_conn, _identity, token) => localStorage.setItem(TOKEN_KEY, token)), + .onConnect((_conn, _identity, token) => localStorage.setItem(TOKEN_KEY, token)) + .onAutomaticReconnect((_conn, _identity, token) => localStorage.setItem(TOKEN_KEY, token)), [] ); return ( @@ -110,6 +111,10 @@ const conn = DbConnection.builder() localStorage.setItem(TOKEN_KEY, token); console.log('Connected as:', identity.toHexString()); }) + .onAutomaticReconnect((_conn, identity, token) => { + localStorage.setItem(TOKEN_KEY, token); + console.log('Reconnected as:', identity.toHexString()); + }) .onDisconnect((_ctx, error, nextAttempt, delayMs) => { if (nextAttempt !== undefined) { console.warn(`Reconnect attempt ${nextAttempt} in ${delayMs} ms`, error); @@ -140,7 +145,7 @@ conn.db.user.onUpdate((ctx, oldUser, newUser) => console.log('Updated:', newUser The React provider's connection manager enables automatic reconnect; the explicit `.withAutomaticReconnect()` above also shows the setting to use for direct connections. Without it, a direct connection does not recover automatically. For direct connections, initial failures are not retried. After an established connection drops, retries use exponential backoff and jitter from `minDelayMs` (default 1 s) up to `maxDelayMs` (default 30 s), until `disconnect()` or a terminal failure. Tune these with `.withAutomaticReconnect({ minDelayMs, maxDelayMs })`; values below the 500 ms and 1 s floors are raised with a warning, so that retrying clients cannot overwhelm the database. While mounted, the React provider also preserves its separate connection-manager retries: it builds a replacement connection after an initial or terminal failure that the core connection will not retry. It respects an explicit `disconnect()`. -The same connection, identity, table handles, subscriptions, and row callbacks survive recovery. Each attempt gets a fresh connection ID. `onConnect` runs again before subscription replay, so register subscriptions and row callbacks once, outside that callback. The SDK replays subscriptions in one batch, retains readable but stale cached rows during outages, and emits net row changes after reconciliation. Subscription `onApplied` runs again after replay; keep one-time setup separate. +The same connection, identity, table handles, subscriptions, and row callbacks survive recovery. Each attempt gets a fresh connection ID. `onConnect` fires once per `DbConnection`; successful automatic reconnects invoke `onAutomaticReconnect` before subscription replay instead. Register subscriptions and row callbacks once, either in `onConnect` or after `build()`, and use `onAutomaticReconnect` for recovery-specific work such as saving a refreshed token. The SDK replays subscriptions in one batch, retains readable but stale cached rows during outages, and emits net row changes after reconciliation. Subscription `onApplied` runs again after replay; keep one-time setup separate. In React, let `useTable` manage its own subscriptions. Do not add a second subscription effect for the same queries or recreate subscriptions whenever `isActive` changes. Use the hook's `isReady` result for data readiness: a successful reconnect handshake does not mean replay has completed. Invoke reducers from event handlers, not during rendering. For a manually created subscription, retain its handle and call `unsubscribe()` when it is no longer needed, including during an outage. diff --git a/skills/unity/SKILL.md b/skills/unity/SKILL.md index 4e1a2b86534..baa52d2e97c 100644 --- a/skills/unity/SKILL.md +++ b/skills/unity/SKILL.md @@ -122,7 +122,7 @@ public class SpacetimeManager : MonoBehaviour ## Automatic Reconnect -Add `.WithAutomaticReconnect()` to the builder to recover an established connection after an outage. In the singleton above, create subscriptions only on the first `OnConnected`, or move them after `Build()`: `OnConnected` runs again after each successful reconnect. Keep calling `FrameTick()` during outages, or use `SpacetimeDBNetworkManager`, which also ticks reconnecting connections. Do not gate ticking on `IsActive`. +Add `.WithAutomaticReconnect()` to the builder to recover an established connection after an outage. In the singleton above, create subscriptions in `OnConnected` or move them after `Build()`: `OnConnected` runs only on the first successful connection. Successful automatic reconnects invoke `OnAutomaticReconnect` before subscription replay; use it for recovery-specific work such as saving a refreshed token. Keep calling `FrameTick()` during outages, or use `SpacetimeDBNetworkManager`, which also ticks reconnecting connections. Do not gate ticking on `IsActive`. The SDK retains the identity, table handles, callbacks, and subscriptions, and replays subscriptions in one batch. Cached rows stay readable during an outage; row callbacks report net changes after recovery. `OnApplied` runs again, so separate one-time object setup from marking data ready. Each reconnect attempt has a fresh `ConnectionId`. @@ -232,6 +232,6 @@ The SpacetimeDB SDK uses code generation. If you encounter issues with IL2CPP bu ### Token Persistence Token save/load via `PlayerPrefs` is demonstrated in the SpacetimeManager singleton above. Persisting the server-issued token and passing it back on reconnect keeps the same identity; without a saved token the server issues a new identity in the `OnConnect` callback. This token does not expire and a lost one can't be recovered, so self-issued identities are for development. For production, authenticate with an OIDC provider such as SpacetimeAuth, which handles token lifecycle. -With automatic reconnect enabled, the SDK retains the authentication token and passes it to `OnConnect`, including on WebGL. Without automatic reconnect, a WebGL connection using a saved token may return a short-lived WebSocket token instead; in that case, keep the original saved token rather than overwriting it in the callback above. +With automatic reconnect enabled, the SDK retains the authentication token and passes it to `OnConnect` on the initial connection, including on WebGL. Successful recovery passes the retained or refreshed token to `OnAutomaticReconnect`. Without automatic reconnect, a WebGL connection using a saved token may return a short-lived WebSocket token instead; in that case, keep the original saved token rather than overwriting it in the callback above. For expiring credentials, configure `.WithToken(initialToken)`, `.WithAutomaticReconnect()`, and `.WithTokenProvider(() => RefreshTokenAsync())`. The provider returns `Task` for the same identity. It is used before reconnect attempts when expiry is unreadable, remaining validity is at most 30 seconds or 5% of the original lifetime, or a reused token is rejected. It is not called for the initial connection or periodically while connected. Provider failures retry; rejection of a freshly provided token stops recovery. `Disconnect()` ignores a pending provider result without canceling the provider's own asynchronous work. From 04e088cebe51405d35efff0bd392d76e65c8512e Mon Sep 17 00:00:00 2001 From: clockwork-labs-bot Date: Tue, 13 Oct 2026 22:49:48 -0400 Subject: [PATCH 07/21] docs: sync reconnect fixes to Codex plugin skills --- .../plugins/spacetimedb/skills/csharp-client/SKILL.md | 4 ++-- .../spacetimedb/skills/typescript-client/SKILL.md | 9 +++++++-- codex-plugin/plugins/spacetimedb/skills/unity/SKILL.md | 4 ++-- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/codex-plugin/plugins/spacetimedb/skills/csharp-client/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/csharp-client/SKILL.md index 47ad75496f9..8af6787560d 100644 --- a/codex-plugin/plugins/spacetimedb/skills/csharp-client/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/csharp-client/SKILL.md @@ -54,9 +54,9 @@ Automatic reconnect is opt-in: add `.WithAutomaticReconnect()` to the builder. I Keep calling `FrameTick()` while `IsActive` is false. `IsReconnecting` is true while recovering before the next handshake. Use `.OnDisconnect((conn, error, next) => ...)` and `.OnConnectError((error, next) => ...)` to inspect `NextReconnect?`: a non-null value provides `Attempt` and `Delay`; null means no retry is scheduled. Existing callback overloads still work. -`OnConnect` runs on every successful reconnect, so create the subscription in the example above only on the first connection, or move it after `Build()`. Register row callbacks once as well. The same connection, identity, table handles, and subscriptions survive; each attempt gets a fresh `ConnectionId`. Cached rows stay readable but stale during outages. The SDK replays subscriptions in one batch and emits only net row changes. Subscription `OnApplied` runs again after replay; use it to mark data ready, not for repeated one-time setup. +`OnConnect` runs once per `DbConnection`, on the first successful connection. Successful automatic reconnects invoke `OnAutomaticReconnect` before subscription replay instead. Register subscriptions and row callbacks once, either in `OnConnect` or after `Build()`, and use `OnAutomaticReconnect` for recovery-specific work such as saving a refreshed token. The same connection, identity, table handles, and subscriptions survive; each attempt gets a fresh `ConnectionId`. Cached rows stay readable but stale during outages. The SDK replays subscriptions in one batch and emits only net row changes. Subscription `OnApplied` runs again after replay; use it to mark data ready, not for repeated one-time setup. -For expiring credentials, combine `.WithToken(initialToken)` with `.WithTokenProvider(() => RefreshTokenAsync())`, where your provider returns `Task` for the same identity. The provider is not called for the initial connection. Before retries, it is called when remaining validity is at most 30 seconds or 5% of the token lifetime, whichever is greater, when expiry cannot be read, or after a reused token is rejected. Provider failures retry; rejection of a freshly provided token is terminal. No periodic refresh runs while connected. Disconnecting ignores a pending provider result but does not cancel the provider's own work. +For expiring credentials, combine `.WithToken(initialToken)` with `.WithTokenProvider(() => RefreshTokenAsync())`, where your provider returns `Task` for the same identity. The provider is not called for the initial connection. Before retries, it is called when remaining validity is at most 30 seconds or 5% of the token lifetime, whichever is greater, when expiry cannot be read, or after a reused token is rejected. Provider failures retry; rejection of a freshly provided token is terminal. No periodic refresh runs while connected. After recovery, persist the token passed to `OnAutomaticReconnect` if the application stores tokens. Disconnecting ignores a pending provider result but does not cancel the provider's own work. Calls made while disconnected fail immediately. Pending reducer calls receive `Status.UnknownResult`; pending procedures and one-off queries fail with `UnknownResultException`. These calls may already have executed and are never replayed. Regenerate bindings so unhandled unknown reducer outcomes reach `OnUnhandledReducerError`. diff --git a/codex-plugin/plugins/spacetimedb/skills/typescript-client/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/typescript-client/SKILL.md index 4249daf15a1..ae59a1683f9 100644 --- a/codex-plugin/plugins/spacetimedb/skills/typescript-client/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/typescript-client/SKILL.md @@ -34,7 +34,8 @@ function Root() { .withDatabaseName(MODULE_NAME) .withToken(localStorage.getItem(TOKEN_KEY) ?? undefined) .withAutomaticReconnect() - .onConnect((_conn, _identity, token) => localStorage.setItem(TOKEN_KEY, token)), + .onConnect((_conn, _identity, token) => localStorage.setItem(TOKEN_KEY, token)) + .onAutomaticReconnect((_conn, _identity, token) => localStorage.setItem(TOKEN_KEY, token)), [] ); return ( @@ -110,6 +111,10 @@ const conn = DbConnection.builder() localStorage.setItem(TOKEN_KEY, token); console.log('Connected as:', identity.toHexString()); }) + .onAutomaticReconnect((_conn, identity, token) => { + localStorage.setItem(TOKEN_KEY, token); + console.log('Reconnected as:', identity.toHexString()); + }) .onDisconnect((_ctx, error, nextAttempt, delayMs) => { if (nextAttempt !== undefined) { console.warn(`Reconnect attempt ${nextAttempt} in ${delayMs} ms`, error); @@ -140,7 +145,7 @@ conn.db.user.onUpdate((ctx, oldUser, newUser) => console.log('Updated:', newUser The React provider's connection manager enables automatic reconnect; the explicit `.withAutomaticReconnect()` above also shows the setting to use for direct connections. Without it, a direct connection does not recover automatically. For direct connections, initial failures are not retried. After an established connection drops, retries use exponential backoff and jitter from `minDelayMs` (default 1 s) up to `maxDelayMs` (default 30 s), until `disconnect()` or a terminal failure. Tune these with `.withAutomaticReconnect({ minDelayMs, maxDelayMs })`; values below the 500 ms and 1 s floors are raised with a warning, so that retrying clients cannot overwhelm the database. While mounted, the React provider also preserves its separate connection-manager retries: it builds a replacement connection after an initial or terminal failure that the core connection will not retry. It respects an explicit `disconnect()`. -The same connection, identity, table handles, subscriptions, and row callbacks survive recovery. Each attempt gets a fresh connection ID. `onConnect` runs again before subscription replay, so register subscriptions and row callbacks once, outside that callback. The SDK replays subscriptions in one batch, retains readable but stale cached rows during outages, and emits net row changes after reconciliation. Subscription `onApplied` runs again after replay; keep one-time setup separate. +The same connection, identity, table handles, subscriptions, and row callbacks survive recovery. Each attempt gets a fresh connection ID. `onConnect` fires once per `DbConnection`; successful automatic reconnects invoke `onAutomaticReconnect` before subscription replay instead. Register subscriptions and row callbacks once, either in `onConnect` or after `build()`, and use `onAutomaticReconnect` for recovery-specific work such as saving a refreshed token. The SDK replays subscriptions in one batch, retains readable but stale cached rows during outages, and emits net row changes after reconciliation. Subscription `onApplied` runs again after replay; keep one-time setup separate. In React, let `useTable` manage its own subscriptions. Do not add a second subscription effect for the same queries or recreate subscriptions whenever `isActive` changes. Use the hook's `isReady` result for data readiness: a successful reconnect handshake does not mean replay has completed. Invoke reducers from event handlers, not during rendering. For a manually created subscription, retain its handle and call `unsubscribe()` when it is no longer needed, including during an outage. diff --git a/codex-plugin/plugins/spacetimedb/skills/unity/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/unity/SKILL.md index 4e1a2b86534..baa52d2e97c 100644 --- a/codex-plugin/plugins/spacetimedb/skills/unity/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/unity/SKILL.md @@ -122,7 +122,7 @@ public class SpacetimeManager : MonoBehaviour ## Automatic Reconnect -Add `.WithAutomaticReconnect()` to the builder to recover an established connection after an outage. In the singleton above, create subscriptions only on the first `OnConnected`, or move them after `Build()`: `OnConnected` runs again after each successful reconnect. Keep calling `FrameTick()` during outages, or use `SpacetimeDBNetworkManager`, which also ticks reconnecting connections. Do not gate ticking on `IsActive`. +Add `.WithAutomaticReconnect()` to the builder to recover an established connection after an outage. In the singleton above, create subscriptions in `OnConnected` or move them after `Build()`: `OnConnected` runs only on the first successful connection. Successful automatic reconnects invoke `OnAutomaticReconnect` before subscription replay; use it for recovery-specific work such as saving a refreshed token. Keep calling `FrameTick()` during outages, or use `SpacetimeDBNetworkManager`, which also ticks reconnecting connections. Do not gate ticking on `IsActive`. The SDK retains the identity, table handles, callbacks, and subscriptions, and replays subscriptions in one batch. Cached rows stay readable during an outage; row callbacks report net changes after recovery. `OnApplied` runs again, so separate one-time object setup from marking data ready. Each reconnect attempt has a fresh `ConnectionId`. @@ -232,6 +232,6 @@ The SpacetimeDB SDK uses code generation. If you encounter issues with IL2CPP bu ### Token Persistence Token save/load via `PlayerPrefs` is demonstrated in the SpacetimeManager singleton above. Persisting the server-issued token and passing it back on reconnect keeps the same identity; without a saved token the server issues a new identity in the `OnConnect` callback. This token does not expire and a lost one can't be recovered, so self-issued identities are for development. For production, authenticate with an OIDC provider such as SpacetimeAuth, which handles token lifecycle. -With automatic reconnect enabled, the SDK retains the authentication token and passes it to `OnConnect`, including on WebGL. Without automatic reconnect, a WebGL connection using a saved token may return a short-lived WebSocket token instead; in that case, keep the original saved token rather than overwriting it in the callback above. +With automatic reconnect enabled, the SDK retains the authentication token and passes it to `OnConnect` on the initial connection, including on WebGL. Successful recovery passes the retained or refreshed token to `OnAutomaticReconnect`. Without automatic reconnect, a WebGL connection using a saved token may return a short-lived WebSocket token instead; in that case, keep the original saved token rather than overwriting it in the callback above. For expiring credentials, configure `.WithToken(initialToken)`, `.WithAutomaticReconnect()`, and `.WithTokenProvider(() => RefreshTokenAsync())`. The provider returns `Task` for the same identity. It is used before reconnect attempts when expiry is unreadable, remaining validity is at most 30 seconds or 5% of the original lifetime, or a reused token is rejected. It is not called for the initial connection or periodically while connected. Provider failures retry; rejection of a freshly provided token stops recovery. `Disconnect()` ignores a pending provider result without canceling the provider's own asynchronous work. From 941190489ea0c71898e51b9231b41d0eb9884f7e Mon Sep 17 00:00:00 2001 From: clockwork-labs-bot Date: Mon, 16 Nov 2026 21:02:51 -0500 Subject: [PATCH 08/21] docs: cover API and tooling changes from audit catch-up --- codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md | 4 ++++ .../plugins/spacetimedb/skills/concepts/SKILL.md | 2 +- .../plugins/spacetimedb/skills/rust-server/SKILL.md | 2 ++ .../spacetimedb/skills/typescript-client/SKILL.md | 2 ++ .../00300-reducers/00400-reducer-context.md | 4 ++++ .../00600-clients/00700-typescript-reference.md | 10 +++++++++- docs/docs/00250-how-to/00900-unit-testing.md | 6 ++++-- .../00100-cli-reference/00300-spacetime-json.md | 1 + .../00300-resources/00200-http-api/00300-database.md | 2 ++ skills/cli/SKILL.md | 4 ++++ skills/concepts/SKILL.md | 2 +- skills/rust-server/SKILL.md | 2 ++ skills/typescript-client/SKILL.md | 2 ++ 13 files changed, 38 insertions(+), 5 deletions(-) diff --git a/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md index 8e604f25be5..430ffe98582 100644 --- a/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md @@ -52,6 +52,10 @@ spacetime generate --lang typescript|csharp|rust --out-dir ./bindings --module-p spacetime generate --lang unrealcpp --uproject-dir ./MyGame --module-path ./server --unreal-module-name MyGame ``` +### TypeScript Import Extensions + +For TypeScript client bindings, `spacetime generate --lang typescript --import-extension none|js|ts` selects the relative import suffix: `none` is the bundler-friendly default, `js` suits `moduleResolution: "nodenext"`, and `ts` suits runtimes executing TypeScript source directly. Set `"import-extension"` per `generate` entry in `spacetime.json` to persist it. This setting changes imports inside generated files, not application imports; NodeNext applications should import an explicit file such as `./module_bindings/index.js`. See https://spacetimedb.com/docs/clients/typescript#import-extensions for direct-TypeScript typecheck settings. + ### Client and Module Bindings `spacetime generate --bindings client` (default) generates bindings for clients connecting to a database. `--bindings module` generates receiver bindings used inside a **sending database module** to call reducers in another **receiving database** through asynchronous IDC. Rust and TypeScript module bindings are supported; C#/C++ module bindings are not implemented yet. `unrealcpp` is client-only; `cpp` is accepted only in module mode. diff --git a/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md index e663f1491fd..db3852e4264 100644 --- a/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md @@ -25,7 +25,7 @@ This describes Spacetime 2.x. The API changed substantially from 1.x, so older a - **App types.** It is used for games, such as BitCraft Online, and for web apps such as chat, collaboration tools, dashboards, and SaaS. The TypeScript SDK has quickstarts for React, Next.js, Vue, Svelte, and more. ([React quickstart](https://spacetimedb.com/docs/quickstarts/react/)) - **Storage.** Tiered storage keeps hot data in memory and colder data on disk. On Maincloud, tables can also be backed by object storage, so a single database can store an effectively unbounded amount of data. ([How does Spacetime scale?](https://spacetimedb.com/blog/how-does-spacetime-scale)) - **Scaling.** Each database runs its transactions one at a time on a single thread. One app can span many databases with asynchronous inter-database communication, and Maincloud replicates each database. ([How does Spacetime scale?](https://spacetimedb.com/blog/how-does-spacetime-scale)) -- **Durability.** Transactions are ACID with serializable isolation. By default, clients see a transaction's results, including the acknowledgment of their own writes, only after it is durable. ([Confirmed reads](https://spacetimedb.com/docs/clients/typescript/#method-withconfirmedreads)) +- **Durability.** Transactions are ACID with serializable isolation. By default, clients see a transaction's results, including the acknowledgment of their own writes, only after it is durable. ([Confirmed reads](https://spacetimedb.com/docs/clients/typescript/#method-withconfirmedreads)) An HTTP durability-confirmation timeout after five seconds returns `504` with an unknown outcome, not proof of rollback; do not retry non-idempotent calls without deduplication. ([HTTP calls](https://spacetimedb.com/docs/http/database#post-v1databasename_or_identitycallreducer)) - **Module languages.** TypeScript, Rust, C#, and C++. TypeScript modules run on V8 and can use npm packages, which are bundled when you publish; Rust, C#, and C++ modules compile to WebAssembly. ([Language support](https://spacetimedb.com/docs/intro/language-support/)) - **Composing modules.** TypeScript and C# modules can mount other modules as submodules, each under its own namespace, to reuse logic such as authentication, rate limiting, or email. Official and community modules are listed at spacetimedb.com/modules. ([Modules](https://spacetimedb.com/docs/modules/)) - **External APIs.** Reducers are deterministic and make no network calls. Procedures make outbound HTTP requests, with a 30-second default timeout and a 180-second maximum. ([Procedures](https://spacetimedb.com/docs/functions/procedures/)) diff --git a/codex-plugin/plugins/spacetimedb/skills/rust-server/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/rust-server/SKILL.md index 42e2f311876..c2e69876968 100644 --- a/codex-plugin/plugins/spacetimedb/skills/rust-server/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/rust-server/SKILL.md @@ -507,4 +507,6 @@ mod tests { `with_reducer_tx` commits on `Ok` and rolls back on `Err` or panic unwinding; propagate reducer errors with `?` when the reducer returns `Result`. Create a new `TestContext` for each test: cloning shares the database. Use `TestAuth::from_jwt_payload(payload, connection_id)?` for client calls and `TestAuth::internal()` for the database itself. The harness exposes `clock`, `rng`, procedure/view contexts, and query execution. It does not simulate subscriptions, RLS, lifecycle calls, or timers. Invoke lifecycle/scheduled reducers explicitly and retain integration tests for host behavior. +In SDK 2.13+, native tests support `ProcedureContext::with_tx` and environment reads. Use `TestContext::set_env` / `unset_env` for module-declared environment keys; undeclared keys and disallowed values are rejected. Clones share the same test environment. The `with_tx` panic workaround applies only to SDK 2.12. + See https://spacetimedb.com/docs/how-to/unit-testing for test setup, HTTP mocking, and current limitations. diff --git a/codex-plugin/plugins/spacetimedb/skills/typescript-client/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/typescript-client/SKILL.md index 9f6737cf85f..a232086ad3a 100644 --- a/codex-plugin/plugins/spacetimedb/skills/typescript-client/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/typescript-client/SKILL.md @@ -15,6 +15,8 @@ metadata: Generated bindings convert snake_case names to camelCase, including row fields: a server column `trip_id` is `tripId` on client rows. +The examples below use bundler-style extensionless imports. For NodeNext or direct-TypeScript execution, choose the matching binding import extension and use explicit file imports in your application; see https://spacetimedb.com/docs/clients/typescript#import-extensions. + ## React: main.tsx ```typescript diff --git a/docs/docs/00200-core-concepts/00200-functions/00300-reducers/00400-reducer-context.md b/docs/docs/00200-core-concepts/00200-functions/00300-reducers/00400-reducer-context.md index 9bcb7f3b17c..2fbb3331601 100644 --- a/docs/docs/00200-core-concepts/00200-functions/00300-reducers/00400-reducer-context.md +++ b/docs/docs/00200-core-concepts/00200-functions/00300-reducers/00400-reducer-context.md @@ -281,8 +281,12 @@ Use the context-provided random API for any reducer logic that needs random valu const fraction = ctx.random(); // [0.0, 1.0) const roll = ctx.random.integerInRange(1, 6); // inclusive const bytes = ctx.random.fill(new Uint8Array(16)); +const cards = ['ace', 'king', 'queen']; +const shuffledCards = ctx.random.shuffle([...cards]); ``` +In SpacetimeDB 2.13+, `ctx.random.shuffle(array)` shuffles the array in place and returns the same array. Copy it first, as above, to preserve the original order. + diff --git a/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md b/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md index 78bdb59bc51..ecc993e4eed 100644 --- a/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md +++ b/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md @@ -85,7 +85,15 @@ spacetime generate --lang typescript \ --module-path PATH-TO-MODULE-DIRECTORY ``` -Import the `module_bindings` in your client's _main_ file: +### Import extensions + +The default generated imports are extensionless, which suits bundler-based clients. For TypeScript projects using `moduleResolution: "nodenext"`, add `--import-extension js` to the generate command. Generated files then import each other with `.js` extensions, which TypeScript resolves to their `.ts` sources and preserves when emitting JavaScript. Use explicit file paths in your own imports too, for example `./module_bindings/index.js` rather than a directory import. + +For runtimes that execute TypeScript source directly, use `--import-extension ts` and import `./module_bindings/index.ts` in your application. If typechecking those imports with TypeScript, enable `allowImportingTsExtensions` with `noEmit` (or another compatible emit configuration). The flag controls imports within the generated bindings, not your application's imports or how it is executed. + +Set `"import-extension": "js"` or `"ts"` on a `generate` entry in [`spacetime.json`](../../00300-resources/00100-cli-reference/00300-spacetime-json.md#generate-configuration) to retain the choice across generation runs. + +For the default bundler configuration, import the `module_bindings` in your client's _main_ file: ```typescript import * as moduleBindings from './module_bindings/index'; diff --git a/docs/docs/00250-how-to/00900-unit-testing.md b/docs/docs/00250-how-to/00900-unit-testing.md index 29d46d7366d..23b303f25b2 100644 --- a/docs/docs/00250-how-to/00900-unit-testing.md +++ b/docs/docs/00250-how-to/00900-unit-testing.md @@ -214,6 +214,8 @@ This won't be needed once [#6317](https://github.com/clockworklabs/SpacetimeDB/i Run these tests natively with `cargo test`, not with a WebAssembly target. The feature enables module registration and the in-memory test datastore without requiring a running host. +SDK 2.13 and later also support environment values in native Rust tests. Use `TestContext::set_env` and `unset_env` for keys declared by the module's `#[spacetimedb::env]` struct. Set values before invoking code that reads `ctx.env`; the harness rejects undeclared keys and values outside a declared constraint. Clones of a `TestContext` share its environment. + ### Define the module For a standalone example, put this in `src/lib.rs`. In an existing module, use your own tables and reducers instead. @@ -1214,8 +1216,8 @@ fn shows_each_client_only_their_own_notes() { ### Known issues -- **`ProcedureContext::with_tx` panics** ([#6296](https://github.com/clockworklabs/SpacetimeDB/pull/6296)). In a test, `with_tx` makes host calls instead of using the test datastore, and panics with `holding &mut HandlerContext, so should not be in a tx already`. Use `try_with_tx` in procedures you want to test until the fix is released. -- **Projects from the `chat-console-rs` template have an invalid dev-dependency** ([#6298](https://github.com/clockworklabs/SpacetimeDB/issues/6298)). `spacetime init` writes the template's `spacetimedb` dev-dependency with a `path` into the SpacetimeDB repository. Replace it with a version that matches the normal dependency, as shown in [Enable the test utilities](#enable-the-test-utilities). +- **SDK 2.12: `ProcedureContext::with_tx` panics in tests.** Upgrade to SDK 2.13 or later for the [fix](https://github.com/clockworklabs/SpacetimeDB/pull/6302). On 2.12, use `try_with_tx` in procedures you want to test; `with_tx` makes host calls instead of using the test datastore. +- **CLI 2.12: `chat-console-rs` projects have an invalid dev-dependency.** CLI 2.13 and later [rewrite template dev-dependencies correctly](https://github.com/clockworklabs/SpacetimeDB/pull/6307). For projects already generated with the old CLI, replace the repository `path` with a version that matches the normal dependency, as shown in [Enable the test utilities](#enable-the-test-utilities). diff --git a/docs/docs/00300-resources/00100-cli-reference/00300-spacetime-json.md b/docs/docs/00300-resources/00100-cli-reference/00300-spacetime-json.md index 3e466c3c5f3..048b7706489 100644 --- a/docs/docs/00300-resources/00100-cli-reference/00300-spacetime-json.md +++ b/docs/docs/00300-resources/00100-cli-reference/00300-spacetime-json.md @@ -57,6 +57,7 @@ The `generate` key is an array of objects. Each object configures bindings gener | `language` | string | Target language: `typescript`, `csharp`, `rust`, `unrealcpp`; `cpp` is reserved for module bindings | | `bindings` | string | `client` (default) for application clients, or `module` for inter-database calls | | `out-dir` | string | Output directory for generated files | +| `import-extension` | string | TypeScript relative import extension: `none` (default) for bundlers, `js` for NodeNext, or `ts` for direct TypeScript execution; see [TypeScript import extensions](../../00200-core-concepts/00600-clients/00700-typescript-reference.md#import-extensions) | | `namespace` | string | C# namespace (`csharp` only) | | `unreal-module-name` | string | Unreal module name (`unrealcpp` only) | | `uproject-dir` | string | Unreal project directory (`unrealcpp` only) | diff --git a/docs/docs/00300-resources/00200-http-api/00300-database.md b/docs/docs/00300-resources/00200-http-api/00300-database.md index d6234a2816c..3054fab79dc 100644 --- a/docs/docs/00300-resources/00200-http-api/00300-database.md +++ b/docs/docs/00300-resources/00200-http-api/00300-database.md @@ -397,6 +397,8 @@ Invoke a reducer or procedure in a database. | ---- | ----- | | `confirmed` | Optional boolean, default `true`. Wait for durability before returning success. For procedure calls, also wait after each successful `withTx`, before procedure code continues. Set to `false` to allow results from state that has committed in memory but may be lost after a crash. +The HTTP durability-confirmation wait has a five-second timeout. If it expires, the response is `504 Gateway Timeout` with an unknown outcome: the operation may already have committed. Do not retry a non-idempotent call without deduplication. This deadline bounds confirmation, not the total execution time of the reducer or procedure. + #### Path parameters | Name | Value | diff --git a/skills/cli/SKILL.md b/skills/cli/SKILL.md index 8e604f25be5..430ffe98582 100644 --- a/skills/cli/SKILL.md +++ b/skills/cli/SKILL.md @@ -52,6 +52,10 @@ spacetime generate --lang typescript|csharp|rust --out-dir ./bindings --module-p spacetime generate --lang unrealcpp --uproject-dir ./MyGame --module-path ./server --unreal-module-name MyGame ``` +### TypeScript Import Extensions + +For TypeScript client bindings, `spacetime generate --lang typescript --import-extension none|js|ts` selects the relative import suffix: `none` is the bundler-friendly default, `js` suits `moduleResolution: "nodenext"`, and `ts` suits runtimes executing TypeScript source directly. Set `"import-extension"` per `generate` entry in `spacetime.json` to persist it. This setting changes imports inside generated files, not application imports; NodeNext applications should import an explicit file such as `./module_bindings/index.js`. See https://spacetimedb.com/docs/clients/typescript#import-extensions for direct-TypeScript typecheck settings. + ### Client and Module Bindings `spacetime generate --bindings client` (default) generates bindings for clients connecting to a database. `--bindings module` generates receiver bindings used inside a **sending database module** to call reducers in another **receiving database** through asynchronous IDC. Rust and TypeScript module bindings are supported; C#/C++ module bindings are not implemented yet. `unrealcpp` is client-only; `cpp` is accepted only in module mode. diff --git a/skills/concepts/SKILL.md b/skills/concepts/SKILL.md index e663f1491fd..db3852e4264 100644 --- a/skills/concepts/SKILL.md +++ b/skills/concepts/SKILL.md @@ -25,7 +25,7 @@ This describes Spacetime 2.x. The API changed substantially from 1.x, so older a - **App types.** It is used for games, such as BitCraft Online, and for web apps such as chat, collaboration tools, dashboards, and SaaS. The TypeScript SDK has quickstarts for React, Next.js, Vue, Svelte, and more. ([React quickstart](https://spacetimedb.com/docs/quickstarts/react/)) - **Storage.** Tiered storage keeps hot data in memory and colder data on disk. On Maincloud, tables can also be backed by object storage, so a single database can store an effectively unbounded amount of data. ([How does Spacetime scale?](https://spacetimedb.com/blog/how-does-spacetime-scale)) - **Scaling.** Each database runs its transactions one at a time on a single thread. One app can span many databases with asynchronous inter-database communication, and Maincloud replicates each database. ([How does Spacetime scale?](https://spacetimedb.com/blog/how-does-spacetime-scale)) -- **Durability.** Transactions are ACID with serializable isolation. By default, clients see a transaction's results, including the acknowledgment of their own writes, only after it is durable. ([Confirmed reads](https://spacetimedb.com/docs/clients/typescript/#method-withconfirmedreads)) +- **Durability.** Transactions are ACID with serializable isolation. By default, clients see a transaction's results, including the acknowledgment of their own writes, only after it is durable. ([Confirmed reads](https://spacetimedb.com/docs/clients/typescript/#method-withconfirmedreads)) An HTTP durability-confirmation timeout after five seconds returns `504` with an unknown outcome, not proof of rollback; do not retry non-idempotent calls without deduplication. ([HTTP calls](https://spacetimedb.com/docs/http/database#post-v1databasename_or_identitycallreducer)) - **Module languages.** TypeScript, Rust, C#, and C++. TypeScript modules run on V8 and can use npm packages, which are bundled when you publish; Rust, C#, and C++ modules compile to WebAssembly. ([Language support](https://spacetimedb.com/docs/intro/language-support/)) - **Composing modules.** TypeScript and C# modules can mount other modules as submodules, each under its own namespace, to reuse logic such as authentication, rate limiting, or email. Official and community modules are listed at spacetimedb.com/modules. ([Modules](https://spacetimedb.com/docs/modules/)) - **External APIs.** Reducers are deterministic and make no network calls. Procedures make outbound HTTP requests, with a 30-second default timeout and a 180-second maximum. ([Procedures](https://spacetimedb.com/docs/functions/procedures/)) diff --git a/skills/rust-server/SKILL.md b/skills/rust-server/SKILL.md index 42e2f311876..c2e69876968 100644 --- a/skills/rust-server/SKILL.md +++ b/skills/rust-server/SKILL.md @@ -507,4 +507,6 @@ mod tests { `with_reducer_tx` commits on `Ok` and rolls back on `Err` or panic unwinding; propagate reducer errors with `?` when the reducer returns `Result`. Create a new `TestContext` for each test: cloning shares the database. Use `TestAuth::from_jwt_payload(payload, connection_id)?` for client calls and `TestAuth::internal()` for the database itself. The harness exposes `clock`, `rng`, procedure/view contexts, and query execution. It does not simulate subscriptions, RLS, lifecycle calls, or timers. Invoke lifecycle/scheduled reducers explicitly and retain integration tests for host behavior. +In SDK 2.13+, native tests support `ProcedureContext::with_tx` and environment reads. Use `TestContext::set_env` / `unset_env` for module-declared environment keys; undeclared keys and disallowed values are rejected. Clones share the same test environment. The `with_tx` panic workaround applies only to SDK 2.12. + See https://spacetimedb.com/docs/how-to/unit-testing for test setup, HTTP mocking, and current limitations. diff --git a/skills/typescript-client/SKILL.md b/skills/typescript-client/SKILL.md index 9f6737cf85f..a232086ad3a 100644 --- a/skills/typescript-client/SKILL.md +++ b/skills/typescript-client/SKILL.md @@ -15,6 +15,8 @@ metadata: Generated bindings convert snake_case names to camelCase, including row fields: a server column `trip_id` is `tripId` on client rows. +The examples below use bundler-style extensionless imports. For NodeNext or direct-TypeScript execution, choose the matching binding import extension and use explicit file imports in your application; see https://spacetimedb.com/docs/clients/typescript#import-extensions. + ## React: main.tsx ```typescript From ebec96717ac4e03beebbb921890054e30f42890d Mon Sep 17 00:00:00 2001 From: clockwork-labs-bot Date: Tue, 17 Nov 2026 09:11:56 -0500 Subject: [PATCH 09/21] docs: clarify receiver dependency local-source lookup --- .../00100-databases/00650-inter-database-communication.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md b/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md index 3f1be1aef08..7c0b8c84a27 100644 --- a/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md +++ b/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md @@ -128,7 +128,7 @@ The sending module needs **receiver bindings**: code generated from the receivin `parent` makes `game-world` a child database of `lobby` when it's first published, so that it inherits the lobby's team permissions. Async IDC doesn't require this; any database can call another on the same server. -`name` is the name of the directory created for the generated code, and `database` refers to either a deployed receiving database or the receiving database's source code. Next generate the bindings: +`name` is the name of the directory created for the generated code. `database` must match another target in the same `spacetime.json`; here, it selects the `game-world` child's local `./game_world` module source. It does not fetch a deployed database's schema, so the receiving module's source must be available locally. Next generate the bindings: ```bash spacetime generate lobby From 9003aa49dadf05fda9d015bacf4aa286a325d0c2 Mon Sep 17 00:00:00 2001 From: clockwork-labs-bot Date: Wed, 18 Nov 2026 09:12:54 -0500 Subject: [PATCH 10/21] docs: clarify CLI login and PostHog integration guidance --- codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md | 4 ++++ .../plugins/spacetimedb/skills/typescript-server/SKILL.md | 6 ++++-- .../00100-databases/00300-spacetime-publish.md | 6 +++++- docs/docs/00250-how-to/00900-unit-testing.md | 2 ++ modules/spacetime-posthog-ts/README.md | 2 +- modules/spacetime-posthog-ts/example/README.md | 4 ++-- skills/cli/SKILL.md | 4 ++++ skills/typescript-server/SKILL.md | 6 ++++-- 8 files changed, 26 insertions(+), 8 deletions(-) diff --git a/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md index 430ffe98582..f5a10924410 100644 --- a/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md @@ -180,6 +180,10 @@ spacetime server clear ### Authentication +Log in with `spacetime login` before publishing, including to local servers. Without a saved login, the browser-login prompt defaults to yes; declining it shows a server-issued identity warning and a second prompt that defaults to no. A server-issued identity works only on its issuing server, owns databases published with it, and cannot be recovered if its token is lost. A later `spacetime login` replaces that saved token. + +`--yes` / `--yes=skip-login` and closed stdin can still create a server-issued identity for compatibility; they do not authenticate you with spacetimedb.com. Do not use them to bypass login setup for unattended publishing. Alert the user before intentionally creating a server-issued identity. + ```bash # Login (opens browser) spacetime login diff --git a/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md index d3348b5a04d..946a4159bdb 100644 --- a/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md @@ -281,6 +281,8 @@ export default spacetimedb; Official reusable libraries include `@spacetimedb/cron`, `@spacetimedb/retry`, `@spacetimedb/rate-limit`, and `@spacetimedb/crypto`. Their registration shapes differ: `@spacetimedb/rate-limit/submodule` is mountable, cron/retry expose factories, and crypto exports helpers. Consult the chosen package's README/exports rather than assuming every package root is a mountable module. +For server-side PostHog analytics, mount `@spacetimedb/posthog/submodule` in the root schema, then call `posthog.install(ctx.as.posthog)` from the root init reducer. After the host reducer's authorization and state change, call `posthog.enqueueEventInTx(ctx.as.posthog, args)` to queue an event in that same transaction; it does not make a network request. Use `tx.as.posthog` inside a procedure's `withTx`, not the procedure context. An administrator must configure the provider before scheduled delivery can send events. See the [package integration guide](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-posthog-ts#integrate-into-an-application) for its exact schema, imports, arguments, and delivery semantics. + ## Environment Variables ```typescript @@ -494,7 +496,7 @@ Handlers are synchronous: return `SyncResponse` directly rather than marking the ## Module Unit Tests -Use `spacetimedb` 2.12+ and Node.js 22+ in the **module** project, not the client. Set `"type": "module"` in `package.json` and install the test runner with `npm install --save-dev vitest@^3.2.4`. Configure the host-import replacement: +Use `spacetimedb` 2.12+ and a supported Node.js release (22.23.4+, 24.22.1+, or 26.12.1+ on those release lines) in the **module** project, not the client. Set `"type": "module"` in `package.json` and install the test runner with `npm install --save-dev vitest@^3.2.4`. Configure the host-import replacement: ```typescript // vitest.config.ts @@ -522,4 +524,4 @@ it('inserts a record', () => { }); ``` -Run `npx vitest run`. Create a fresh harness per test. `withReducerTx` commits on normal return and rolls back/rethrows on exceptions; do not catch a failure inside the transaction if rollback is expected. Callbacks must be synchronous. Use `TestAuth.fromJwtPayload(JSON.stringify({ iss: 'test', sub: 'alice' }), connectionId)` for client authorization tests; internal auth represents the database, not a client or the publisher. The harness exposes `clock`, `rng`, procedure/view contexts, and query execution. It does not simulate subscriptions, RLS, lifecycle calls, or scheduling; invoke lifecycle/scheduled reducers explicitly and retain live integration tests for those host behaviors. +Run `npx vitest run`. Create a fresh harness per test. `withReducerTx` commits on normal return and rolls back/rethrows on exceptions; do not catch a failure inside the transaction if rollback is expected. Callbacks must be synchronous. Use `TestAuth.fromJwtPayload(JSON.stringify({ iss: 'test', sub: 'alice' }), connectionId)` for client authorization tests; internal auth represents the database, not a client or the publisher. The harness exposes `clock`, `rng`, procedure/view contexts, and query execution. It does not simulate subscriptions, RLS, lifecycle calls, or scheduling; invoke lifecycle/scheduled reducers explicitly and retain live integration tests for those host behaviors. It does not currently supply namespaced `ctx.as` / `tx.as` helper contexts for mounted submodules; test those integrations against a running database. diff --git a/docs/docs/00200-core-concepts/00100-databases/00300-spacetime-publish.md b/docs/docs/00200-core-concepts/00100-databases/00300-spacetime-publish.md index d3a640b537f..fcd4b583a66 100644 --- a/docs/docs/00200-core-concepts/00100-databases/00300-spacetime-publish.md +++ b/docs/docs/00200-core-concepts/00100-databases/00300-spacetime-publish.md @@ -43,7 +43,11 @@ Before publishing, authenticate with SpacetimeDB: spacetime login ``` -This opens a browser window for authentication. Once complete, your credentials are saved locally. +This opens a browser window for authentication. Once complete, your credentials are saved locally. This login also works with local servers. + +If no login is saved, the CLI offers browser login by default. Declining it shows a warning and asks you to confirm creating a server-issued identity; pressing Enter at this second prompt cancels. A server-issued identity works only on that server, and databases you publish belong to it. Running `spacetime login` later replaces its saved token, and a lost server-issued token cannot be recovered. + +For compatibility, `--yes` (including `--yes=skip-login`) or closed standard input can still create a server-issued identity when no login is saved. These are not substitutes for authentication: log in before running unattended publishes. ### Publishing a New Database diff --git a/docs/docs/00250-how-to/00900-unit-testing.md b/docs/docs/00250-how-to/00900-unit-testing.md index 23b303f25b2..e306ac1745f 100644 --- a/docs/docs/00250-how-to/00900-unit-testing.md +++ b/docs/docs/00250-how-to/00900-unit-testing.md @@ -60,6 +60,8 @@ export default defineConfig({ The plugin also configures the installed `spacetimedb` package to pass through Vitest's transforms. The package includes the test datastore's WebAssembly runtime; you do not need to compile it yourself. +The TypeScript harness does not currently supply namespaced `ctx.as` / `tx.as` helper contexts for mounted submodules. Test integrations that use those contexts against a running database. + ### Define the module For a standalone example, put this in `src/index.ts`. In an existing module, keep your own schema and reducers instead. diff --git a/modules/spacetime-posthog-ts/README.md b/modules/spacetime-posthog-ts/README.md index 12f6af165e5..74a52317540 100644 --- a/modules/spacetime-posthog-ts/README.md +++ b/modules/spacetime-posthog-ts/README.md @@ -93,7 +93,7 @@ spacetime call --server http://127.0.0.1:3000 spacetime-posthog set_posthog_conf Verify: ```bash -spacetime call --server http://127.0.0.1:3000 spacetime-posthog get_posthog_config_status '{}' +spacetime call --server http://127.0.0.1:3000 spacetime-posthog get_posthog_config_status ``` ## Public views diff --git a/modules/spacetime-posthog-ts/example/README.md b/modules/spacetime-posthog-ts/example/README.md index 61becd41d1c..4a9a834b43c 100644 --- a/modules/spacetime-posthog-ts/example/README.md +++ b/modules/spacetime-posthog-ts/example/README.md @@ -5,8 +5,8 @@ send the café's activity to your analytics project. ## Run it locally -Requires Node.js 20+, pnpm 10, and the SpacetimeDB CLI and server built from -this checkout. +Requires a recent version of Node.js 22, 24, or 26 or later, pnpm 10, and the +SpacetimeDB CLI and server built from this checkout. Start SpacetimeDB in a separate terminal: diff --git a/skills/cli/SKILL.md b/skills/cli/SKILL.md index 430ffe98582..f5a10924410 100644 --- a/skills/cli/SKILL.md +++ b/skills/cli/SKILL.md @@ -180,6 +180,10 @@ spacetime server clear ### Authentication +Log in with `spacetime login` before publishing, including to local servers. Without a saved login, the browser-login prompt defaults to yes; declining it shows a server-issued identity warning and a second prompt that defaults to no. A server-issued identity works only on its issuing server, owns databases published with it, and cannot be recovered if its token is lost. A later `spacetime login` replaces that saved token. + +`--yes` / `--yes=skip-login` and closed stdin can still create a server-issued identity for compatibility; they do not authenticate you with spacetimedb.com. Do not use them to bypass login setup for unattended publishing. Alert the user before intentionally creating a server-issued identity. + ```bash # Login (opens browser) spacetime login diff --git a/skills/typescript-server/SKILL.md b/skills/typescript-server/SKILL.md index d3348b5a04d..946a4159bdb 100644 --- a/skills/typescript-server/SKILL.md +++ b/skills/typescript-server/SKILL.md @@ -281,6 +281,8 @@ export default spacetimedb; Official reusable libraries include `@spacetimedb/cron`, `@spacetimedb/retry`, `@spacetimedb/rate-limit`, and `@spacetimedb/crypto`. Their registration shapes differ: `@spacetimedb/rate-limit/submodule` is mountable, cron/retry expose factories, and crypto exports helpers. Consult the chosen package's README/exports rather than assuming every package root is a mountable module. +For server-side PostHog analytics, mount `@spacetimedb/posthog/submodule` in the root schema, then call `posthog.install(ctx.as.posthog)` from the root init reducer. After the host reducer's authorization and state change, call `posthog.enqueueEventInTx(ctx.as.posthog, args)` to queue an event in that same transaction; it does not make a network request. Use `tx.as.posthog` inside a procedure's `withTx`, not the procedure context. An administrator must configure the provider before scheduled delivery can send events. See the [package integration guide](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-posthog-ts#integrate-into-an-application) for its exact schema, imports, arguments, and delivery semantics. + ## Environment Variables ```typescript @@ -494,7 +496,7 @@ Handlers are synchronous: return `SyncResponse` directly rather than marking the ## Module Unit Tests -Use `spacetimedb` 2.12+ and Node.js 22+ in the **module** project, not the client. Set `"type": "module"` in `package.json` and install the test runner with `npm install --save-dev vitest@^3.2.4`. Configure the host-import replacement: +Use `spacetimedb` 2.12+ and a supported Node.js release (22.23.4+, 24.22.1+, or 26.12.1+ on those release lines) in the **module** project, not the client. Set `"type": "module"` in `package.json` and install the test runner with `npm install --save-dev vitest@^3.2.4`. Configure the host-import replacement: ```typescript // vitest.config.ts @@ -522,4 +524,4 @@ it('inserts a record', () => { }); ``` -Run `npx vitest run`. Create a fresh harness per test. `withReducerTx` commits on normal return and rolls back/rethrows on exceptions; do not catch a failure inside the transaction if rollback is expected. Callbacks must be synchronous. Use `TestAuth.fromJwtPayload(JSON.stringify({ iss: 'test', sub: 'alice' }), connectionId)` for client authorization tests; internal auth represents the database, not a client or the publisher. The harness exposes `clock`, `rng`, procedure/view contexts, and query execution. It does not simulate subscriptions, RLS, lifecycle calls, or scheduling; invoke lifecycle/scheduled reducers explicitly and retain live integration tests for those host behaviors. +Run `npx vitest run`. Create a fresh harness per test. `withReducerTx` commits on normal return and rolls back/rethrows on exceptions; do not catch a failure inside the transaction if rollback is expected. Callbacks must be synchronous. Use `TestAuth.fromJwtPayload(JSON.stringify({ iss: 'test', sub: 'alice' }), connectionId)` for client authorization tests; internal auth represents the database, not a client or the publisher. The harness exposes `clock`, `rng`, procedure/view contexts, and query execution. It does not simulate subscriptions, RLS, lifecycle calls, or scheduling; invoke lifecycle/scheduled reducers explicitly and retain live integration tests for those host behaviors. It does not currently supply namespaced `ctx.as` / `tx.as` helper contexts for mounted submodules; test those integrations against a running database. From 67becd6777a0e2f4ec9e8e25d4ef007488fe571e Mon Sep 17 00:00:00 2001 From: clockwork-labs-bot Date: Wed, 18 Nov 2026 12:37:47 -0500 Subject: [PATCH 11/21] docs: complete catch-up audit for storage, modules and SDKs --- .../plugins/spacetimedb/skills/cli/SKILL.md | 2 + .../spacetimedb/skills/concepts/SKILL.md | 8 ++- .../spacetimedb/skills/csharp-server/SKILL.md | 2 + .../spacetimedb/skills/rust-server/SKILL.md | 4 +- .../skills/typescript-client/SKILL.md | 2 + .../skills/typescript-server/SKILL.md | 6 +- .../spacetimedb/skills/unreal/SKILL.md | 16 ++++- .../00300-spacetime-publish.md | 2 + .../00200-automatic-migrations.md | 4 ++ .../00100-databases/00600-modules.md | 12 ++++ .../00650-inter-database-communication.md | 14 ++++- .../00200-functions/00400-procedures.md | 4 ++ docs/docs/00200-core-concepts/00300-tables.md | 63 +++++++++++++++++++ .../00300-tables/00210-file-storage.md | 8 +++ .../00300-tables/00500-schedule-tables.md | 4 ++ .../00700-typescript-reference.md | 2 + skills/cli/SKILL.md | 2 + skills/concepts/SKILL.md | 8 ++- skills/csharp-server/SKILL.md | 2 + skills/rust-server/SKILL.md | 4 +- skills/typescript-client/SKILL.md | 2 + skills/typescript-server/SKILL.md | 6 +- skills/unreal/SKILL.md | 16 ++++- 23 files changed, 180 insertions(+), 13 deletions(-) diff --git a/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md index f5a10924410..4f0fa27bd1b 100644 --- a/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md @@ -81,6 +81,8 @@ when changing build modes. Managed builds alone do not enable C# module unit tes where supported. The CLI manages `SPACETIMEDB_WASM_AOT` and its legacy alias `EXPERIMENTAL_WASM_AOT`; users do not need to set either for .NET 10. +New databases receive a server-allocated identity; a supplied identity can update an existing database, not create one. Only the registered name owner can recreate a deleted database whose name remains registered. + ### Publishing & Deployment ```bash diff --git a/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md index db3852e4264..07e7ad920d8 100644 --- a/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md @@ -37,7 +37,7 @@ This describes Spacetime 2.x. The API changed substantially from 1.x, so older a - **Auth.** Spacetime works with any OIDC provider, such as Auth0, Clerk, Better Auth, or Firebase Auth. SpacetimeAuth is a first-party provider with magic links, social logins, and user and role management. ([Authentication](https://spacetimedb.com/docs/core-concepts/authentication/)) - **Scheduled work.** Schedule tables run reducers or procedures at a specific time or on a repeating interval. In TypeScript, the Cron module adds calendar schedules with time zones. ([Schedule tables](https://spacetimedb.com/docs/tables/schedule-tables/), [Cron module](https://spacetimedb.com/modules/cron)) - **Ephemeral events.** Event tables broadcast rows to subscribers without storing them, for things like typing indicators. ([Event tables](https://spacetimedb.com/docs/tables/event-tables/)) -- **Files.** Files can be stored as bytes in table columns, or a procedure can store large files in S3 or a similar service and keep a reference in a table. In TypeScript, the Files module handles uploads, listing and download routes. ([File storage](https://spacetimedb.com/docs/tables/file-storage/), [Files module](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-files-ts)) +- **Files.** Files can be stored as bytes in table columns, or a procedure can store large files in S3 or a similar service and keep a reference in a table. In TypeScript, the Files module handles database-backed uploads, listing and download routes; the S3 module keeps bytes in a private bucket and tracks ownership and upload state in the database. ([File storage](https://spacetimedb.com/docs/tables/file-storage/), [Files module](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-files-ts), [S3 module](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-s3-ts)) - **SQL and tools.** Spacetime speaks the PostgreSQL wire protocol, so PostgreSQL drivers, `psql`, and GUI clients can connect. ([PostgreSQL wire protocol](https://spacetimedb.com/docs/how-to/pg-wire/)) - **Dashboard.** On Maincloud, each database's dashboard on spacetimedb.com lets you browse, filter, edit, delete, and export table rows, call reducers, and view logs and metrics. ([Maincloud dashboard](https://spacetimedb.com/docs/how-to/deploy/maincloud/#viewing-your-database-on-the-web-dashboard)) - **Schema changes.** Compatible changes, such as adding tables or columns with defaults, migrate automatically when you republish, and incremental migrations handle the rest. ([Automatic migrations](https://spacetimedb.com/docs/databases/automatic-migrations/)) @@ -134,6 +134,8 @@ Server-side modules can be written in: Rust, C#, TypeScript, C++ Lifecycle: Write → Compile → Publish (`spacetime publish`) → Hot-swap (republish without disconnecting clients) +Scheduled functions are private, but the database owner can still call them directly. To restrict a callback to scheduler execution, compare the sender with the database identity; see the server skills for language-specific syntax. + ## HTTP Handlers A module can expose its own HTTP API. Each handler takes a request and returns a response, and one router per module binds handlers to a method and path. Requests reach them under `/v1/database//route`, so a `/say-hello` route is served at `/v1/database/my-db/route/say-hello`. @@ -144,6 +146,10 @@ A module can expose its own HTTP API. Each handler takes a request and returns a Use HTTP handlers for webhooks and for clients that can't use a SpacetimeDB SDK. See the language-specific server skills for syntax. +## Table Storage Policies + +Tables default to keeping pages and blobs resident in memory. A cache policy can permit eviction to local disk (`required_on_disk`) or any configured tier (`no_requirement`), including remote object storage. It does not configure a backend or force eviction; actual eviction depends on server tiers and memory budgets. Any indexes on tables with non-default policies must be B-trees. See https://spacetimedb.com/docs/tables#storage-policy and the language-specific table options. + ## Reusable Modules and Configuration TypeScript and C# support same-language submodule composition. A namespace has a language accessor and a canonical database name; SQL, CLI calls, and HTTP calls use the canonical name. Changing the canonical namespace drops its tables and their data, so pin it when renaming an accessor. TypeScript supports nested submodules; C# composition requires 2.13+ with .NET 10/C# 14, and nested or repeated C# mounts require 2.14+. See the respective server skills for registration and helper-context rules. diff --git a/codex-plugin/plugins/spacetimedb/skills/csharp-server/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/csharp-server/SKILL.md index e4d10138436..37d7cbbe67e 100644 --- a/codex-plugin/plugins/spacetimedb/skills/csharp-server/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/csharp-server/SKILL.md @@ -47,6 +47,8 @@ spacetime build # CLI selects WASM automatically assemblies. .NET 10 composition uses generated assembly descriptors, not the dependency's standalone WASM exports; no special root/library build flag is needed. +Table attributes also accept `CachePolicy = TableCachePolicy.RequiredInMemory` (default), `TableCachePolicy.RequiredOnDisk`, or `TableCachePolicy.NoRequirement`. See the concepts skill for storage semantics and index restrictions. + ## Module Structure Reducers are static methods in a `static partial class`; tables are `public partial struct`s. This reference keeps everything in one `public static partial class Module`, which needs only `using SpacetimeDB;`: diff --git a/codex-plugin/plugins/spacetimedb/skills/rust-server/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/rust-server/SKILL.md index c2e69876968..ff8114750e8 100644 --- a/codex-plugin/plugins/spacetimedb/skills/rust-server/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/rust-server/SKILL.md @@ -42,7 +42,7 @@ pub struct Entity { } ``` -Options: `accessor = snake_case` (required), `public`, `scheduled(reducer_fn)`, `index(...)` +Options: `accessor = snake_case` (required), `public`, `scheduled(reducer_fn)`, `index(...)`, `cache_policy = required_in_memory | required_on_disk | no_requirement` (default: `required_in_memory`; see the concepts skill for storage semantics). `ctx.db` accessors use the `accessor` name (snake_case). @@ -292,7 +292,7 @@ Construct a connection ID from a numeric representation with `ConnectionId::from A reducer calls a reducer in another database by inserting a row into an outbox table. The call is sent only if the transaction commits, runs exactly once, and runs in order with other calls through the same outbox to the same database. The sending reducer doesn't wait for it. Both databases must be on the same server. -Generate receiver bindings by listing the receiving module under `dependencies` in the sending database's `spacetime.json`, then running `spacetime generate `. Rust bindings are written to `src/remote_bindings/`. +Generate receiver bindings by listing the receiving module under `dependencies` in the sending database's `spacetime.json`, then running `spacetime generate `. Rust bindings are written to `src/remote_bindings/`, with `mod.rs` roots. Regenerate older bindings and remove obsolete `lib.rs` path overrides. With `game_world` imported as a module identifier, `spacetimedb::outbox!(game_world::admit_player);` generates `AdmitPlayerOutbox` with `msg_id`, `target`, and the reducer argument columns. Optional `accessor = custom_outbox` and `name = "custom_outbox"` override table names. Use a manual table (below) for extra columns, reducer arguments named `msg_id` or `target`, or multiple outboxes for the same reducer. ```json { diff --git a/codex-plugin/plugins/spacetimedb/skills/typescript-client/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/typescript-client/SKILL.md index a232086ad3a..d311d31d766 100644 --- a/codex-plugin/plugins/spacetimedb/skills/typescript-client/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/typescript-client/SKILL.md @@ -164,6 +164,8 @@ conn.subscriptionBuilder().subscribe('SELECT * FROM by_id(42)'); Use explicit queries for every table on that connection, not subscribe-all, which skips views with arguments. Only `SELECT * FROM view_name(literal_args)` is supported. All argument values share one cache table; unsubscribe from obsolete arguments to avoid combining their rows. Validate/encode dynamic values as SQL literals rather than concatenating untrusted input. In React, raw SQL subscriptions need explicit lifetime management and cleanup; `useTable` does not supply an argument-bearing view builder. +A server message that cannot be decoded or applied ends the connection without automatic retry: errors go to `onConnectError` before establishment or `onDisconnect` afterwards. Synchronous exceptions thrown by user callbacks are logged without preventing other callbacks from running. TypeScript SDKs containing the row-boundary decoding fix (#6091) can read rows with appended table columns using older generated bindings; removing, reordering, or changing existing column types is not. Regenerate bindings to access added columns. + ## Automatic Reconnect and Token Refresh The React provider's connection manager enables automatic reconnect; the explicit `.withAutomaticReconnect()` above also shows the setting to use for direct connections. Without it, a direct connection does not recover automatically. For direct connections, initial failures are not retried. After an established connection drops, retries use exponential backoff and jitter from `minDelayMs` (default 1 s) up to `maxDelayMs` (default 30 s), until `disconnect()` or a terminal failure. Tune these with `.withAutomaticReconnect({ minDelayMs, maxDelayMs })`; values below the 500 ms and 1 s floors are raised with a warning, so that retrying clients cannot overwhelm the database. While mounted, the React provider also preserves its separate connection-manager retries: it builds a replacement connection after an initial or terminal failure that the core connection will not retry. It respects an explicit `disconnect()`. diff --git a/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md index 946a4159bdb..69c5d670973 100644 --- a/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md @@ -72,7 +72,7 @@ const entity = table( ); ``` -Options: `name` (snake_case, recommended), `public: true`, `event: true`, `indexes: [...]` +Options: `name` (snake_case, recommended), `public: true`, `event: true`, `indexes: [...]`, `cachePolicy: 'required_in_memory' | 'required_on_disk' | 'no_requirement'` (default: `required_in_memory`; see the concepts skill for storage semantics). `ctx.db` accessors are the keys passed to `schema({...})`, verbatim: `schema({ scoreRecord })` -> `ctx.db.scoreRecord`. Keep TypeScript identifiers and accessors camelCase. Use explicit `name: 'snake_case'` strings when you need a canonical database name that differs from the TypeScript identifier. @@ -281,6 +281,10 @@ export default spacetimedb; Official reusable libraries include `@spacetimedb/cron`, `@spacetimedb/retry`, `@spacetimedb/rate-limit`, and `@spacetimedb/crypto`. Their registration shapes differ: `@spacetimedb/rate-limit/submodule` is mountable, cron/retry expose factories, and crypto exports helpers. Consult the chosen package's README/exports rather than assuming every package root is a mountable module. +Additional mountable packages include `@spacetimedb/auth/submodule` (application-managed sign-in and sessions, distinct from hosted SpacetimeAuth), `@spacetimedb/agents/submodule` (conversations/model calls), and `@spacetimedb/files/submodule` (database-backed files). Auth and Agents require root initialization via `install(ctx.as.auth)` / `install(ctx.as.agents)`. Auth HTTP handlers must be delegated from the root router; configure its signing key first. Agents hosts must authenticate callers, derive owners from trusted state, and enforce quotas before paid model calls. Files helpers accept `ctx.as.files` from reducers or `tx.as.files` inside `withTx`. These libraries require SDK/CLI/server 2.12+. Follow the [package integration guides](https://spacetimedb.com/docs/modules#reusable-typescript-packages) for exact exports and initialization rather than assuming all packages share an `install` API. + +For large external files, `@spacetimedb/s3/submodule` supplies the private state tables; `@spacetimedb/s3` supplies `client` and `s3Tick`. Declare AWS credentials on the root environment, construct a client with `client(options)`, call its `initialize(tx)` method during initialization, and schedule its `reconcile(ctx, credentials)` method in a procedure. Derive owners on the server. The [S3 guide](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-s3-ts) specifies bucket constraints and reconciliation behavior; restoring an old database can remove newer S3 objects under its dedicated prefix. + For server-side PostHog analytics, mount `@spacetimedb/posthog/submodule` in the root schema, then call `posthog.install(ctx.as.posthog)` from the root init reducer. After the host reducer's authorization and state change, call `posthog.enqueueEventInTx(ctx.as.posthog, args)` to queue an event in that same transaction; it does not make a network request. Use `tx.as.posthog` inside a procedure's `withTx`, not the procedure context. An administrator must configure the provider before scheduled delivery can send events. See the [package integration guide](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-posthog-ts#integrate-into-an-application) for its exact schema, imports, arguments, and delivery semantics. ## Environment Variables diff --git a/codex-plugin/plugins/spacetimedb/skills/unreal/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/unreal/SKILL.md index b30759ca5e2..144dfaef4b4 100644 --- a/codex-plugin/plugins/spacetimedb/skills/unreal/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/unreal/SKILL.md @@ -153,7 +153,7 @@ void AGameManager::EndPlay(const EEndPlayReason::Type EndPlayReason) void AGameManager::Tick(float DeltaTime) { - if (Conn && Conn->IsActive()) + if (Conn) // Keep ticking during automatic recovery, too. { Conn->FrameTick(); } @@ -222,6 +222,18 @@ Save the `Token` for future reconnection. The `Identity` is the user's persisten --- +## Automatic Reconnect and Token Refresh + +Automatic reconnect is opt-in: add `->WithAutomaticReconnect()` to the builder. Regenerate bindings to get the reconnect methods. Initial connection failures are not retried; after an established connection drops, retries continue with exponential backoff and jitter. Configure `FAutomaticReconnectOptions.MinDelaySeconds` (default 1) and `MaxDelaySeconds` (default 30) with `->WithAutomaticReconnectOptions(Options)`; the effective floors are 0.5 and 1 second. `Disconnect()` cancels recovery. Keep `FrameTick()` running even when `IsActive()` is false; `IsReconnecting()` reports recovery in progress. + +`OnConnect` runs once. `OnAutomaticReconnect` takes the same `FOnConnectDelegate` and runs after recovery, before subscription replay; use it to save the new token. Register subscriptions and row callbacks once, not on every recovery or `OnApplied`: subscriptions replay atomically, their `OnApplied` callbacks run again, and unchanged rows do not fire row callbacks. Cached rows remain readable but stale until reconciliation. + +Existing disconnect/error delegates keep their signatures. `OnDisconnectWithReconnect` and `OnConnectErrorWithReconnect` additionally receive `bWillReconnect`, `NextReconnectAttempt`, and `NextReconnectDelaySeconds`. Do not create a replacement connection while a retry is pending. Calls are never replayed: interrupted calls may have executed and report `UnknownResult`; calls during recovery report `Disconnected`. + +For expiring credentials, use `WithToken` for the initial token and `WithTokenProvider` for recovery. Its `FTokenProviderDelegate` receives `UReconnectTokenRequest*`; complete it asynchronously with `Request->Complete(NewToken, FString())` or an empty token and an error. Tokens must retain the original identity. Provider failures retry; rejection of a fresh token is terminal. The server must support session replacement and batch subscriptions. See https://spacetimedb.com/docs/clients/unreal#method-withautomaticreconnect. + +--- + ## Subscribing to Tables After connecting, subscribe to receive table data: @@ -304,7 +316,7 @@ UFUNCTION() void OnUserUpdate(const FEventContext& Context, const FUserType& OldRow, const FUserType& NewRow); ``` -Register callbacks before connecting or in `HandleSubscriptionApplied`. +Register row callbacks once before subscribing, for example in `HandleConnect`. Do not register them in `HandleSubscriptionApplied`: it runs again after automatic subscription replay. --- diff --git a/docs/docs/00200-core-concepts/00100-databases/00300-spacetime-publish.md b/docs/docs/00200-core-concepts/00100-databases/00300-spacetime-publish.md index fcd4b583a66..875cc5a16e6 100644 --- a/docs/docs/00200-core-concepts/00100-databases/00300-spacetime-publish.md +++ b/docs/docs/00200-core-concepts/00100-databases/00300-spacetime-publish.md @@ -65,6 +65,8 @@ This command: 4. Runs the `init` lifecycle reducer (if defined) 5. Starts accepting client connections +New databases receive a server-allocated identity; you cannot create one at an identity you supply. An existing database can be updated by name or identity. If a deleted database name is still registered, only its name owner can recreate it. + After publishing, SpacetimeDB outputs your database identity. **Save this identity** - you'll need it for administrative tasks. ### Updating an Existing Database diff --git a/docs/docs/00200-core-concepts/00100-databases/00500-migrations/00200-automatic-migrations.md b/docs/docs/00200-core-concepts/00100-databases/00500-migrations/00200-automatic-migrations.md index f18e51877ba..d7654e51403 100644 --- a/docs/docs/00200-core-concepts/00100-databases/00500-migrations/00200-automatic-migrations.md +++ b/docs/docs/00200-core-concepts/00100-databases/00500-migrations/00200-automatic-migrations.md @@ -25,6 +25,10 @@ The following changes are always allowed and will not break existing clients: - **Adding new reducers.** - **Removing `Unique` constraints.** +:::note Older bindings and newer SDKs +TypeScript and C# SDKs containing the [row-boundary decoding fix](https://github.com/clockworklabs/SpacetimeDB/pull/6091) can read rows with appended columns using bindings generated from the older schema: they skip the trailing fields they do not know. Older SDK versions may fail to decode those rows; keeping old bindings is not the same as keeping an old SDK. Regenerate bindings to access the new fields. Removing, reordering, or changing the types of existing columns is not covered by this compatibility. +::: + ## ⚠️ Potentially Breaking Changes These changes are allowed by automatic migration, but may cause runtime errors for clients that haven't been updated: diff --git a/docs/docs/00200-core-concepts/00100-databases/00600-modules.md b/docs/docs/00200-core-concepts/00100-databases/00600-modules.md index df21debca74..51e0380d96d 100644 --- a/docs/docs/00200-core-concepts/00100-databases/00600-modules.md +++ b/docs/docs/00200-core-concepts/00100-databases/00600-modules.md @@ -14,6 +14,18 @@ Modules let you package reusable database logic as a library that any consumer c Submodules are supported in TypeScript and C# (.NET 10 only). Cross-language composition is not supported. ::: +## Reusable TypeScript Packages + +Official packages provide reusable application features. Follow each package's integration guide: not every package root is a mountable submodule. + +- [Auth](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-auth-ts) provides application-managed password and OAuth sign-in, sessions, and connection bindings. Mount `@spacetimedb/auth/submodule`, initialize it from the root, and configure its signing key and root HTTP routes. This is a library inside your application, not the hosted SpacetimeAuth service. +- [Agents](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-agents-ts) stores conversations and runs model calls with application tools. Mount `@spacetimedb/agents/submodule` and initialize it from the root. The host must authenticate callers, derive conversation ownership from trusted state, and enforce quotas before paid model calls. +- [Files](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-files-ts) stores file contents in database tables and supplies upload, listing, and download helpers. Mount `@spacetimedb/files/submodule`; pass its helper context from a reducer or a procedure transaction. +- [S3](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-s3-ts) stores file contents in a private S3 bucket while keeping ownership and upload state in SpacetimeDB. Its guide covers bucket permissions, root environment declarations for credentials, initialization, and a scheduled reconciliation procedure. Derive file ownership on the server, never from a client-supplied owner. +- [PostHog](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-posthog-ts) queues analytics events transactionally for scheduled delivery. Mount `@spacetimedb/posthog/submodule`, initialize it from the root, and configure the provider before sending events. + +These packages require SpacetimeDB SDK, CLI, and server 2.12 or later. Their tables are private; expose only authorized data through your application's views and operations. Perform network I/O in procedures or HTTP handlers, not inside transactions. + ## Writing a Submodule A submodule is a regular SpacetimeDB module. The same module can be published independently or included by another module; no special root/library build role is required. diff --git a/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md b/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md index 7c0b8c84a27..f57ba674e6d 100644 --- a/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md +++ b/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md @@ -390,7 +390,7 @@ spacetime sql lobby "SELECT * FROM admit_player_outbox" ### Generated outbox declarations -You can always declare an outbox by manually specifying the table and types. However, in TypeScript, the receiver bindings can declare an outbox for you. `gw.outbox.admitPlayer()` returns an outbox table with a `msgId` message ID column, a `target` column, and a column for each parameter of the reducer: +You can always declare an outbox by manually specifying the table and types. TypeScript and Rust receiver bindings also provide shorthand declarations. In TypeScript, `gw.outbox.admitPlayer()` returns an outbox table with a `msgId` message ID column, a `target` column, and a column for each parameter of the reducer: ```typescript const spacetimedb = schema({ @@ -404,6 +404,18 @@ ctx.db.admitPlayerOutbox.insert({ msgId: 0n, target: world, name }); Like `table()`, it takes an optional `name`. Without one, the table is named after its key in `schema()`. It can't declare an outbox for a reducer with a parameter named `msgId` or `target`. For that reducer, use `table()` to manually declare an outbox table, and give the message ID and target columns other names. +In Rust, import the receiving module and use `spacetimedb::outbox!`: + +```rust +use remote_bindings::game_world; + +spacetimedb::outbox!(game_world::admit_player); +``` + +For the `admit_player(name: String)` reducer above, this creates `AdmitPlayerOutbox` with `msg_id: u64`, `target: game_world::Identity`, and `name: String`, accessed through `ctx.db.admit_player_outbox()`. Insert `msg_id: 0` to allocate the message ID. Optional `accessor = custom_outbox` and `name = "custom_outbox"` arguments override the accessor and canonical table name. The receiver must be in scope as a module identifier. If its arguments include `msg_id` or `target`, or you need multiple outboxes for the same reducer or extra columns, declare the table manually instead. + +Rust receiver bindings now use `mod.rs` as their root. Regenerate older bindings and remove any obsolete `#[path = "remote_bindings/game_world/lib.rs"]` override; the normal `mod remote_bindings;` declaration works with the generated directory structure. + ## Receiving calls The receiving reducer can be any reducer that clients can call, which excludes [lifecycle reducers](../00200-functions/00300-reducers/00500-lifecycle.md), scheduled reducers, and `on_result` reducers. It runs in its own transaction, like a call from a client, and `ctx.sender` is the sending database's identity. If it fails, its changes roll back, and the error goes back to the sending database. diff --git a/docs/docs/00200-core-concepts/00200-functions/00400-procedures.md b/docs/docs/00200-core-concepts/00200-functions/00400-procedures.md index 093b5a93890..459a62e1286 100644 --- a/docs/docs/00200-core-concepts/00200-functions/00400-procedures.md +++ b/docs/docs/00200-core-concepts/00200-functions/00400-procedures.md @@ -15,6 +15,10 @@ However, procedures don't automatically run in database transactions, and must manually open and commit a transaction in order to read from or modify the database state. For this reason, prefer defining reducers rather than procedures unless you need to use one of the special procedure operators. +:::note Database shutdown +Pausing or suspending a database interrupts in-flight procedure HTTP requests and sleeps, and prevents procedures from starting further transactions during shutdown. Transactions committed earlier in the procedure are not rolled back with the interrupted work. Handle failure at the caller; do not assume a procedure finishes after the database stops. +::: + ## Defining Procedures diff --git a/docs/docs/00200-core-concepts/00300-tables.md b/docs/docs/00200-core-concepts/00300-tables.md index f7a506d4023..361abe09763 100644 --- a/docs/docs/00200-core-concepts/00300-tables.md +++ b/docs/docs/00200-core-concepts/00300-tables.md @@ -328,6 +328,69 @@ Use idiomatic naming conventions for each language: These conventions align with each language's standard style guides and make your code feel natural within its ecosystem. +## Storage Policy + +A table's cache policy controls the furthest storage tier its pages and blobs may use. It does not change transaction guarantees or table visibility. + +| Policy | Behavior | +| --- | --- | +| `required_in_memory` (default) | Keep pages and blobs resident in memory. | +| `required_on_disk` | Allow eviction to local disk, but not to remote storage alone. | +| `no_requirement` | Allow any configured storage tier, including remote object storage. | + +Choosing a policy permits eviction; it does not force data out of memory or configure a storage backend. Actual eviction depends on the server's configured tiers and memory budget. The standalone server currently uses an unlimited resident-memory budget. Any indexes on tables with non-default policies must be B-trees; hash and direct indexes are not supported on those tables. + + + + +Set `cachePolicy` in the table options: + +```typescript +import { schema, table, t } from 'spacetimedb/server'; + +const archiveEntry = table( + { cachePolicy: 'required_on_disk' }, + { id: t.u64(), payload: t.string() } +); +const spacetimedb = schema({ archiveEntry }); +export default spacetimedb; +``` + + + + +Set `cache_policy` in the table attribute: + +```rust +#[spacetimedb::table(accessor = archive_entry, cache_policy = required_on_disk)] +pub struct ArchiveEntry { + id: u64, + payload: String, +} +``` + + + + +Set `CachePolicy` in the table attribute. The enum variants are `RequiredInMemory`, `RequiredOnDisk`, and `NoRequirement`: + +```csharp +using SpacetimeDB; + +public static partial class Module +{ + [SpacetimeDB.Table(Accessor = "ArchiveEntry", CachePolicy = TableCachePolicy.RequiredOnDisk)] + public partial struct ArchiveEntry + { + public ulong Id; + public string Payload; + } +} +``` + + + + ## Table Visibility Tables can be **private** (default) or **public**: diff --git a/docs/docs/00200-core-concepts/00300-tables/00210-file-storage.md b/docs/docs/00200-core-concepts/00300-tables/00210-file-storage.md index af12f0aa18f..8daf7546028 100644 --- a/docs/docs/00200-core-concepts/00300-tables/00210-file-storage.md +++ b/docs/docs/00200-core-concepts/00300-tables/00210-file-storage.md @@ -10,6 +10,14 @@ import { CppModuleVersionNotice } from "@site/src/components/CppModuleVersionNot SpacetimeDB can store binary data directly in table columns, making it suitable for files, images, and other blobs that need to participate in transactions and subscriptions. +## Reusable File Packages (TypeScript) + +Use [Files](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-files-ts) for database-backed uploads, listing, and download routes. Its limits are package-specific: files are at most 4 MB, with a default total quota of 100 MB per owner. + +Use [S3](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-s3-ts) when file bytes should go directly between the browser and a private S3 bucket. SpacetimeDB stores ownership and upload state; a scheduled reconciliation procedure completes interrupted uploads and deletes. Follow its bucket and initialization requirements, derive ownership on the server, and never expose AWS credentials to clients. Use a dedicated bucket prefix: reconciliation removes objects the database does not know about, so restoring an older database backup can delete newer files under that prefix. + +These packages require SDK, CLI, and server 2.12 or later. Their limits and delivery behavior are separate from the general inline-storage examples below. + ## Storing Binary Data Inline Store binary data using `Vec` (Rust), `List` (C#), `std::vector` (C++), or `t.array(t.u8())` (TypeScript). This approach keeps data within the database, ensuring it participates in transactions and real-time updates. diff --git a/docs/docs/00200-core-concepts/00300-tables/00500-schedule-tables.md b/docs/docs/00200-core-concepts/00300-tables/00500-schedule-tables.md index 1b22efce2c4..a9efe480ca8 100644 --- a/docs/docs/00200-core-concepts/00300-tables/00500-schedule-tables.md +++ b/docs/docs/00200-core-concepts/00300-tables/00500-schedule-tables.md @@ -419,6 +419,10 @@ SpacetimeDB passes the schedule row to the scheduled reducer or procedure as an - Scheduled reducers delete the row after execution, so the row is visible in the schedule table while the reducer runs. - Interval schedules are never deleted automatically. Only one-shot schedules are removed after they run. +### Who Can Call Scheduled Functions + +Scheduled reducers and procedures are private: ordinary clients cannot call them, but the database owner can invoke them directly. If a callback must reject even owner-initiated calls, check that its sender is the database identity (`ctx.sender.isEqual(ctx.databaseIdentity)` in TypeScript, `ctx.sender() == ctx.database_identity()` in Rust, or `ctx.Sender == ctx.DatabaseIdentity` in C#). + ## Use Cases - **Reminders and notifications** - Schedule messages to be sent at specific times diff --git a/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md b/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md index ecc993e4eed..c22dd9d7fe4 100644 --- a/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md +++ b/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md @@ -244,6 +244,8 @@ class DbConnectionBuilder { Called when an established connection is lost, or when the application calls [`disconnect`](#method-disconnect). With automatic reconnection enabled, the trailing parameters describe the next attempt and delay in milliseconds. Both are `undefined` when no retry is scheduled. An explicit `disconnect()` also passes `undefined` for `error`, including when called between reconnect attempts. +If a server message cannot be decoded or applied, the SDK ends the connection without retrying, even when automatic reconnect is enabled. The error reaches `onConnectError` before the first successful handshake, or `onDisconnect` afterwards. Synchronous exceptions thrown by user callbacks are logged and do not prevent other callbacks from running. + #### Method `withToken` ```typescript diff --git a/skills/cli/SKILL.md b/skills/cli/SKILL.md index f5a10924410..4f0fa27bd1b 100644 --- a/skills/cli/SKILL.md +++ b/skills/cli/SKILL.md @@ -81,6 +81,8 @@ when changing build modes. Managed builds alone do not enable C# module unit tes where supported. The CLI manages `SPACETIMEDB_WASM_AOT` and its legacy alias `EXPERIMENTAL_WASM_AOT`; users do not need to set either for .NET 10. +New databases receive a server-allocated identity; a supplied identity can update an existing database, not create one. Only the registered name owner can recreate a deleted database whose name remains registered. + ### Publishing & Deployment ```bash diff --git a/skills/concepts/SKILL.md b/skills/concepts/SKILL.md index db3852e4264..07e7ad920d8 100644 --- a/skills/concepts/SKILL.md +++ b/skills/concepts/SKILL.md @@ -37,7 +37,7 @@ This describes Spacetime 2.x. The API changed substantially from 1.x, so older a - **Auth.** Spacetime works with any OIDC provider, such as Auth0, Clerk, Better Auth, or Firebase Auth. SpacetimeAuth is a first-party provider with magic links, social logins, and user and role management. ([Authentication](https://spacetimedb.com/docs/core-concepts/authentication/)) - **Scheduled work.** Schedule tables run reducers or procedures at a specific time or on a repeating interval. In TypeScript, the Cron module adds calendar schedules with time zones. ([Schedule tables](https://spacetimedb.com/docs/tables/schedule-tables/), [Cron module](https://spacetimedb.com/modules/cron)) - **Ephemeral events.** Event tables broadcast rows to subscribers without storing them, for things like typing indicators. ([Event tables](https://spacetimedb.com/docs/tables/event-tables/)) -- **Files.** Files can be stored as bytes in table columns, or a procedure can store large files in S3 or a similar service and keep a reference in a table. In TypeScript, the Files module handles uploads, listing and download routes. ([File storage](https://spacetimedb.com/docs/tables/file-storage/), [Files module](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-files-ts)) +- **Files.** Files can be stored as bytes in table columns, or a procedure can store large files in S3 or a similar service and keep a reference in a table. In TypeScript, the Files module handles database-backed uploads, listing and download routes; the S3 module keeps bytes in a private bucket and tracks ownership and upload state in the database. ([File storage](https://spacetimedb.com/docs/tables/file-storage/), [Files module](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-files-ts), [S3 module](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-s3-ts)) - **SQL and tools.** Spacetime speaks the PostgreSQL wire protocol, so PostgreSQL drivers, `psql`, and GUI clients can connect. ([PostgreSQL wire protocol](https://spacetimedb.com/docs/how-to/pg-wire/)) - **Dashboard.** On Maincloud, each database's dashboard on spacetimedb.com lets you browse, filter, edit, delete, and export table rows, call reducers, and view logs and metrics. ([Maincloud dashboard](https://spacetimedb.com/docs/how-to/deploy/maincloud/#viewing-your-database-on-the-web-dashboard)) - **Schema changes.** Compatible changes, such as adding tables or columns with defaults, migrate automatically when you republish, and incremental migrations handle the rest. ([Automatic migrations](https://spacetimedb.com/docs/databases/automatic-migrations/)) @@ -134,6 +134,8 @@ Server-side modules can be written in: Rust, C#, TypeScript, C++ Lifecycle: Write → Compile → Publish (`spacetime publish`) → Hot-swap (republish without disconnecting clients) +Scheduled functions are private, but the database owner can still call them directly. To restrict a callback to scheduler execution, compare the sender with the database identity; see the server skills for language-specific syntax. + ## HTTP Handlers A module can expose its own HTTP API. Each handler takes a request and returns a response, and one router per module binds handlers to a method and path. Requests reach them under `/v1/database//route`, so a `/say-hello` route is served at `/v1/database/my-db/route/say-hello`. @@ -144,6 +146,10 @@ A module can expose its own HTTP API. Each handler takes a request and returns a Use HTTP handlers for webhooks and for clients that can't use a SpacetimeDB SDK. See the language-specific server skills for syntax. +## Table Storage Policies + +Tables default to keeping pages and blobs resident in memory. A cache policy can permit eviction to local disk (`required_on_disk`) or any configured tier (`no_requirement`), including remote object storage. It does not configure a backend or force eviction; actual eviction depends on server tiers and memory budgets. Any indexes on tables with non-default policies must be B-trees. See https://spacetimedb.com/docs/tables#storage-policy and the language-specific table options. + ## Reusable Modules and Configuration TypeScript and C# support same-language submodule composition. A namespace has a language accessor and a canonical database name; SQL, CLI calls, and HTTP calls use the canonical name. Changing the canonical namespace drops its tables and their data, so pin it when renaming an accessor. TypeScript supports nested submodules; C# composition requires 2.13+ with .NET 10/C# 14, and nested or repeated C# mounts require 2.14+. See the respective server skills for registration and helper-context rules. diff --git a/skills/csharp-server/SKILL.md b/skills/csharp-server/SKILL.md index e4d10138436..37d7cbbe67e 100644 --- a/skills/csharp-server/SKILL.md +++ b/skills/csharp-server/SKILL.md @@ -47,6 +47,8 @@ spacetime build # CLI selects WASM automatically assemblies. .NET 10 composition uses generated assembly descriptors, not the dependency's standalone WASM exports; no special root/library build flag is needed. +Table attributes also accept `CachePolicy = TableCachePolicy.RequiredInMemory` (default), `TableCachePolicy.RequiredOnDisk`, or `TableCachePolicy.NoRequirement`. See the concepts skill for storage semantics and index restrictions. + ## Module Structure Reducers are static methods in a `static partial class`; tables are `public partial struct`s. This reference keeps everything in one `public static partial class Module`, which needs only `using SpacetimeDB;`: diff --git a/skills/rust-server/SKILL.md b/skills/rust-server/SKILL.md index c2e69876968..ff8114750e8 100644 --- a/skills/rust-server/SKILL.md +++ b/skills/rust-server/SKILL.md @@ -42,7 +42,7 @@ pub struct Entity { } ``` -Options: `accessor = snake_case` (required), `public`, `scheduled(reducer_fn)`, `index(...)` +Options: `accessor = snake_case` (required), `public`, `scheduled(reducer_fn)`, `index(...)`, `cache_policy = required_in_memory | required_on_disk | no_requirement` (default: `required_in_memory`; see the concepts skill for storage semantics). `ctx.db` accessors use the `accessor` name (snake_case). @@ -292,7 +292,7 @@ Construct a connection ID from a numeric representation with `ConnectionId::from A reducer calls a reducer in another database by inserting a row into an outbox table. The call is sent only if the transaction commits, runs exactly once, and runs in order with other calls through the same outbox to the same database. The sending reducer doesn't wait for it. Both databases must be on the same server. -Generate receiver bindings by listing the receiving module under `dependencies` in the sending database's `spacetime.json`, then running `spacetime generate `. Rust bindings are written to `src/remote_bindings/`. +Generate receiver bindings by listing the receiving module under `dependencies` in the sending database's `spacetime.json`, then running `spacetime generate `. Rust bindings are written to `src/remote_bindings/`, with `mod.rs` roots. Regenerate older bindings and remove obsolete `lib.rs` path overrides. With `game_world` imported as a module identifier, `spacetimedb::outbox!(game_world::admit_player);` generates `AdmitPlayerOutbox` with `msg_id`, `target`, and the reducer argument columns. Optional `accessor = custom_outbox` and `name = "custom_outbox"` override table names. Use a manual table (below) for extra columns, reducer arguments named `msg_id` or `target`, or multiple outboxes for the same reducer. ```json { diff --git a/skills/typescript-client/SKILL.md b/skills/typescript-client/SKILL.md index a232086ad3a..d311d31d766 100644 --- a/skills/typescript-client/SKILL.md +++ b/skills/typescript-client/SKILL.md @@ -164,6 +164,8 @@ conn.subscriptionBuilder().subscribe('SELECT * FROM by_id(42)'); Use explicit queries for every table on that connection, not subscribe-all, which skips views with arguments. Only `SELECT * FROM view_name(literal_args)` is supported. All argument values share one cache table; unsubscribe from obsolete arguments to avoid combining their rows. Validate/encode dynamic values as SQL literals rather than concatenating untrusted input. In React, raw SQL subscriptions need explicit lifetime management and cleanup; `useTable` does not supply an argument-bearing view builder. +A server message that cannot be decoded or applied ends the connection without automatic retry: errors go to `onConnectError` before establishment or `onDisconnect` afterwards. Synchronous exceptions thrown by user callbacks are logged without preventing other callbacks from running. TypeScript SDKs containing the row-boundary decoding fix (#6091) can read rows with appended table columns using older generated bindings; removing, reordering, or changing existing column types is not. Regenerate bindings to access added columns. + ## Automatic Reconnect and Token Refresh The React provider's connection manager enables automatic reconnect; the explicit `.withAutomaticReconnect()` above also shows the setting to use for direct connections. Without it, a direct connection does not recover automatically. For direct connections, initial failures are not retried. After an established connection drops, retries use exponential backoff and jitter from `minDelayMs` (default 1 s) up to `maxDelayMs` (default 30 s), until `disconnect()` or a terminal failure. Tune these with `.withAutomaticReconnect({ minDelayMs, maxDelayMs })`; values below the 500 ms and 1 s floors are raised with a warning, so that retrying clients cannot overwhelm the database. While mounted, the React provider also preserves its separate connection-manager retries: it builds a replacement connection after an initial or terminal failure that the core connection will not retry. It respects an explicit `disconnect()`. diff --git a/skills/typescript-server/SKILL.md b/skills/typescript-server/SKILL.md index 946a4159bdb..69c5d670973 100644 --- a/skills/typescript-server/SKILL.md +++ b/skills/typescript-server/SKILL.md @@ -72,7 +72,7 @@ const entity = table( ); ``` -Options: `name` (snake_case, recommended), `public: true`, `event: true`, `indexes: [...]` +Options: `name` (snake_case, recommended), `public: true`, `event: true`, `indexes: [...]`, `cachePolicy: 'required_in_memory' | 'required_on_disk' | 'no_requirement'` (default: `required_in_memory`; see the concepts skill for storage semantics). `ctx.db` accessors are the keys passed to `schema({...})`, verbatim: `schema({ scoreRecord })` -> `ctx.db.scoreRecord`. Keep TypeScript identifiers and accessors camelCase. Use explicit `name: 'snake_case'` strings when you need a canonical database name that differs from the TypeScript identifier. @@ -281,6 +281,10 @@ export default spacetimedb; Official reusable libraries include `@spacetimedb/cron`, `@spacetimedb/retry`, `@spacetimedb/rate-limit`, and `@spacetimedb/crypto`. Their registration shapes differ: `@spacetimedb/rate-limit/submodule` is mountable, cron/retry expose factories, and crypto exports helpers. Consult the chosen package's README/exports rather than assuming every package root is a mountable module. +Additional mountable packages include `@spacetimedb/auth/submodule` (application-managed sign-in and sessions, distinct from hosted SpacetimeAuth), `@spacetimedb/agents/submodule` (conversations/model calls), and `@spacetimedb/files/submodule` (database-backed files). Auth and Agents require root initialization via `install(ctx.as.auth)` / `install(ctx.as.agents)`. Auth HTTP handlers must be delegated from the root router; configure its signing key first. Agents hosts must authenticate callers, derive owners from trusted state, and enforce quotas before paid model calls. Files helpers accept `ctx.as.files` from reducers or `tx.as.files` inside `withTx`. These libraries require SDK/CLI/server 2.12+. Follow the [package integration guides](https://spacetimedb.com/docs/modules#reusable-typescript-packages) for exact exports and initialization rather than assuming all packages share an `install` API. + +For large external files, `@spacetimedb/s3/submodule` supplies the private state tables; `@spacetimedb/s3` supplies `client` and `s3Tick`. Declare AWS credentials on the root environment, construct a client with `client(options)`, call its `initialize(tx)` method during initialization, and schedule its `reconcile(ctx, credentials)` method in a procedure. Derive owners on the server. The [S3 guide](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-s3-ts) specifies bucket constraints and reconciliation behavior; restoring an old database can remove newer S3 objects under its dedicated prefix. + For server-side PostHog analytics, mount `@spacetimedb/posthog/submodule` in the root schema, then call `posthog.install(ctx.as.posthog)` from the root init reducer. After the host reducer's authorization and state change, call `posthog.enqueueEventInTx(ctx.as.posthog, args)` to queue an event in that same transaction; it does not make a network request. Use `tx.as.posthog` inside a procedure's `withTx`, not the procedure context. An administrator must configure the provider before scheduled delivery can send events. See the [package integration guide](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-posthog-ts#integrate-into-an-application) for its exact schema, imports, arguments, and delivery semantics. ## Environment Variables diff --git a/skills/unreal/SKILL.md b/skills/unreal/SKILL.md index b30759ca5e2..144dfaef4b4 100644 --- a/skills/unreal/SKILL.md +++ b/skills/unreal/SKILL.md @@ -153,7 +153,7 @@ void AGameManager::EndPlay(const EEndPlayReason::Type EndPlayReason) void AGameManager::Tick(float DeltaTime) { - if (Conn && Conn->IsActive()) + if (Conn) // Keep ticking during automatic recovery, too. { Conn->FrameTick(); } @@ -222,6 +222,18 @@ Save the `Token` for future reconnection. The `Identity` is the user's persisten --- +## Automatic Reconnect and Token Refresh + +Automatic reconnect is opt-in: add `->WithAutomaticReconnect()` to the builder. Regenerate bindings to get the reconnect methods. Initial connection failures are not retried; after an established connection drops, retries continue with exponential backoff and jitter. Configure `FAutomaticReconnectOptions.MinDelaySeconds` (default 1) and `MaxDelaySeconds` (default 30) with `->WithAutomaticReconnectOptions(Options)`; the effective floors are 0.5 and 1 second. `Disconnect()` cancels recovery. Keep `FrameTick()` running even when `IsActive()` is false; `IsReconnecting()` reports recovery in progress. + +`OnConnect` runs once. `OnAutomaticReconnect` takes the same `FOnConnectDelegate` and runs after recovery, before subscription replay; use it to save the new token. Register subscriptions and row callbacks once, not on every recovery or `OnApplied`: subscriptions replay atomically, their `OnApplied` callbacks run again, and unchanged rows do not fire row callbacks. Cached rows remain readable but stale until reconciliation. + +Existing disconnect/error delegates keep their signatures. `OnDisconnectWithReconnect` and `OnConnectErrorWithReconnect` additionally receive `bWillReconnect`, `NextReconnectAttempt`, and `NextReconnectDelaySeconds`. Do not create a replacement connection while a retry is pending. Calls are never replayed: interrupted calls may have executed and report `UnknownResult`; calls during recovery report `Disconnected`. + +For expiring credentials, use `WithToken` for the initial token and `WithTokenProvider` for recovery. Its `FTokenProviderDelegate` receives `UReconnectTokenRequest*`; complete it asynchronously with `Request->Complete(NewToken, FString())` or an empty token and an error. Tokens must retain the original identity. Provider failures retry; rejection of a fresh token is terminal. The server must support session replacement and batch subscriptions. See https://spacetimedb.com/docs/clients/unreal#method-withautomaticreconnect. + +--- + ## Subscribing to Tables After connecting, subscribe to receive table data: @@ -304,7 +316,7 @@ UFUNCTION() void OnUserUpdate(const FEventContext& Context, const FUserType& OldRow, const FUserType& NewRow); ``` -Register callbacks before connecting or in `HandleSubscriptionApplied`. +Register row callbacks once before subscribing, for example in `HandleConnect`. Do not register them in `HandleSubscriptionApplied`: it runs again after automatic subscription replay. --- From 5f3a9d052eecb03c61f0a03dad8d5237feca8b3d Mon Sep 17 00:00:00 2001 From: clockwork-labs-bot Date: Thu, 19 Nov 2026 09:01:21 -0500 Subject: [PATCH 12/21] docs: resolve migration guidance conflict with master --- .../00500-migrations/00200-automatic-migrations.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/docs/00200-core-concepts/00100-databases/00500-migrations/00200-automatic-migrations.md b/docs/docs/00200-core-concepts/00100-databases/00500-migrations/00200-automatic-migrations.md index d7654e51403..d844f9f6efd 100644 --- a/docs/docs/00200-core-concepts/00100-databases/00500-migrations/00200-automatic-migrations.md +++ b/docs/docs/00200-core-concepts/00100-databases/00500-migrations/00200-automatic-migrations.md @@ -29,6 +29,16 @@ The following changes are always allowed and will not break existing clients: TypeScript and C# SDKs containing the [row-boundary decoding fix](https://github.com/clockworklabs/SpacetimeDB/pull/6091) can read rows with appended columns using bindings generated from the older schema: they skip the trailing fields they do not know. Older SDK versions may fail to decode those rows; keeping old bindings is not the same as keeping an old SDK. Regenerate bindings to access the new fields. Removing, reordering, or changing the types of existing columns is not covered by this compatibility. ::: +## Changing a table's cache policy + +To change which storage tiers an existing table can use, update its [cache policy](../../00300-tables/00700-storage-and-cache-policies.md) in your module and republish. For a database named `my-database` on Maincloud, use: + +```bash +spacetime publish my-database --server maincloud --delete-data=never +``` + +Once the new policy allows paging, SpacetimeDB can evict the table's pages and blobs from memory as it needs room. Changing back to the in-memory policy requires enough room to load and keep the table's data in memory. If there isn't enough room, the migration fails and the existing policy stays in effect. + ## ⚠️ Potentially Breaking Changes These changes are allowed by automatic migration, but may cause runtime errors for clients that haven't been updated: From 0601a441ec825d2ebf6249a0c6d353694e4f03a6 Mon Sep 17 00:00:00 2001 From: clockwork-labs-bot Date: Thu, 19 Nov 2026 09:01:47 -0500 Subject: [PATCH 13/21] docs: preserve compatibility note away from merge insertion --- .../00500-migrations/00200-automatic-migrations.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/docs/00200-core-concepts/00100-databases/00500-migrations/00200-automatic-migrations.md b/docs/docs/00200-core-concepts/00100-databases/00500-migrations/00200-automatic-migrations.md index d844f9f6efd..43efa673b28 100644 --- a/docs/docs/00200-core-concepts/00100-databases/00500-migrations/00200-automatic-migrations.md +++ b/docs/docs/00200-core-concepts/00100-databases/00500-migrations/00200-automatic-migrations.md @@ -25,10 +25,6 @@ The following changes are always allowed and will not break existing clients: - **Adding new reducers.** - **Removing `Unique` constraints.** -:::note Older bindings and newer SDKs -TypeScript and C# SDKs containing the [row-boundary decoding fix](https://github.com/clockworklabs/SpacetimeDB/pull/6091) can read rows with appended columns using bindings generated from the older schema: they skip the trailing fields they do not know. Older SDK versions may fail to decode those rows; keeping old bindings is not the same as keeping an old SDK. Regenerate bindings to access the new fields. Removing, reordering, or changing the types of existing columns is not covered by this compatibility. -::: - ## Changing a table's cache policy To change which storage tiers an existing table can use, update its [cache policy](../../00300-tables/00700-storage-and-cache-policies.md) in your module and republish. For a database named `my-database` on Maincloud, use: @@ -122,3 +118,7 @@ The SpacetimeDB team is working on enhanced migration capabilities, including: - Automatic client compatibility checking Check the [SpacetimeDB documentation](https://spacetimedb.com/docs) and [GitHub repository](https://github.com/clockworklabs/SpacetimeDB) for the latest migration features and capabilities. + +:::note Older bindings and newer SDKs +TypeScript and C# SDKs containing the [row-boundary decoding fix](https://github.com/clockworklabs/SpacetimeDB/pull/6091) can read rows with appended columns using bindings generated from the older schema: they skip the trailing fields they do not know. Older SDK versions may fail to decode those rows; keeping old bindings is not the same as keeping an old SDK. Regenerate bindings to access the new fields. Removing, reordering, or changing the types of existing columns is not covered by this compatibility. +::: From c1970fffbf05db667da64765d0a71fcba5270ec7 Mon Sep 17 00:00:00 2001 From: clockwork-labs-bot Date: Thu, 19 Nov 2026 09:05:25 -0500 Subject: [PATCH 14/21] docs: consolidate storage policies and clarify Rust shutdown --- .../spacetimedb/skills/concepts/SKILL.md | 2 +- .../00200-automatic-migrations.md | 8 +-- docs/docs/00200-core-concepts/00300-tables.md | 61 +------------------ .../00700-storage-and-cache-policies.md | 10 ++- .../00600-clients/00500-rust-reference.md | 2 + skills/concepts/SKILL.md | 2 +- 6 files changed, 17 insertions(+), 68 deletions(-) diff --git a/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md index 07e7ad920d8..291b108efdd 100644 --- a/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md @@ -148,7 +148,7 @@ Use HTTP handlers for webhooks and for clients that can't use a SpacetimeDB SDK. ## Table Storage Policies -Tables default to keeping pages and blobs resident in memory. A cache policy can permit eviction to local disk (`required_on_disk`) or any configured tier (`no_requirement`), including remote object storage. It does not configure a backend or force eviction; actual eviction depends on server tiers and memory budgets. Any indexes on tables with non-default policies must be B-trees. See https://spacetimedb.com/docs/tables#storage-policy and the language-specific table options. +Tables default to keeping pages and blobs resident in memory. A cache policy can permit eviction to local disk (`required_on_disk`) or any configured tier (`no_requirement`), including remote object storage. It does not configure a backend or force eviction; actual eviction depends on server tiers and memory budgets. Any indexes on tables with non-default policies must be B-trees. The standalone server currently uses an unlimited resident-memory budget. Change a policy by republishing without deleting data; moving back to the in-memory policy requires enough memory to load and retain the table. See https://spacetimedb.com/docs/tables/storage-and-cache-policies and the language-specific table options. ## Reusable Modules and Configuration diff --git a/docs/docs/00200-core-concepts/00100-databases/00500-migrations/00200-automatic-migrations.md b/docs/docs/00200-core-concepts/00100-databases/00500-migrations/00200-automatic-migrations.md index 43efa673b28..d844f9f6efd 100644 --- a/docs/docs/00200-core-concepts/00100-databases/00500-migrations/00200-automatic-migrations.md +++ b/docs/docs/00200-core-concepts/00100-databases/00500-migrations/00200-automatic-migrations.md @@ -25,6 +25,10 @@ The following changes are always allowed and will not break existing clients: - **Adding new reducers.** - **Removing `Unique` constraints.** +:::note Older bindings and newer SDKs +TypeScript and C# SDKs containing the [row-boundary decoding fix](https://github.com/clockworklabs/SpacetimeDB/pull/6091) can read rows with appended columns using bindings generated from the older schema: they skip the trailing fields they do not know. Older SDK versions may fail to decode those rows; keeping old bindings is not the same as keeping an old SDK. Regenerate bindings to access the new fields. Removing, reordering, or changing the types of existing columns is not covered by this compatibility. +::: + ## Changing a table's cache policy To change which storage tiers an existing table can use, update its [cache policy](../../00300-tables/00700-storage-and-cache-policies.md) in your module and republish. For a database named `my-database` on Maincloud, use: @@ -118,7 +122,3 @@ The SpacetimeDB team is working on enhanced migration capabilities, including: - Automatic client compatibility checking Check the [SpacetimeDB documentation](https://spacetimedb.com/docs) and [GitHub repository](https://github.com/clockworklabs/SpacetimeDB) for the latest migration features and capabilities. - -:::note Older bindings and newer SDKs -TypeScript and C# SDKs containing the [row-boundary decoding fix](https://github.com/clockworklabs/SpacetimeDB/pull/6091) can read rows with appended columns using bindings generated from the older schema: they skip the trailing fields they do not know. Older SDK versions may fail to decode those rows; keeping old bindings is not the same as keeping an old SDK. Regenerate bindings to access the new fields. Removing, reordering, or changing the types of existing columns is not covered by this compatibility. -::: diff --git a/docs/docs/00200-core-concepts/00300-tables.md b/docs/docs/00200-core-concepts/00300-tables.md index 9611729928a..f1d855c128d 100644 --- a/docs/docs/00200-core-concepts/00300-tables.md +++ b/docs/docs/00200-core-concepts/00300-tables.md @@ -330,66 +330,9 @@ These conventions align with each language's standard style guides and make your ## Storage Policy -A table's cache policy controls the furthest storage tier its pages and blobs may use. It does not change transaction guarantees or table visibility. +A table's cache policy controls which storage tiers its pages and blobs may use. It does not change transaction guarantees, durability, or table visibility. Tables default to keeping their data resident in memory. -| Policy | Behavior | -| --- | --- | -| `required_in_memory` (default) | Keep pages and blobs resident in memory. | -| `required_on_disk` | Allow eviction to local disk, but not to remote storage alone. | -| `no_requirement` | Allow any configured storage tier, including remote object storage. | - -Choosing a policy permits eviction; it does not force data out of memory or configure a storage backend. Actual eviction depends on the server's configured tiers and memory budget. The standalone server currently uses an unlimited resident-memory budget. Any indexes on tables with non-default policies must be B-trees; hash and direct indexes are not supported on those tables. - - - - -Set `cachePolicy` in the table options: - -```typescript -import { schema, table, t } from 'spacetimedb/server'; - -const archiveEntry = table( - { cachePolicy: 'required_on_disk' }, - { id: t.u64(), payload: t.string() } -); -const spacetimedb = schema({ archiveEntry }); -export default spacetimedb; -``` - - - - -Set `cache_policy` in the table attribute: - -```rust -#[spacetimedb::table(accessor = archive_entry, cache_policy = required_on_disk)] -pub struct ArchiveEntry { - id: u64, - payload: String, -} -``` - - - - -Set `CachePolicy` in the table attribute. The enum variants are `RequiredInMemory`, `RequiredOnDisk`, and `NoRequirement`: - -```csharp -using SpacetimeDB; - -public static partial class Module -{ - [SpacetimeDB.Table(Accessor = "ArchiveEntry", CachePolicy = TableCachePolicy.RequiredOnDisk)] - public partial struct ArchiveEntry - { - public ulong Id; - public string Payload; - } -} -``` - - - +See [Table Storage and Cache Policies](./00300-tables/00700-storage-and-cache-policies.md) for policy values, cross-language examples, index restrictions, and migration requirements. ## Table Visibility diff --git a/docs/docs/00200-core-concepts/00300-tables/00700-storage-and-cache-policies.md b/docs/docs/00200-core-concepts/00300-tables/00700-storage-and-cache-policies.md index fbdd7b89cbe..18dcf437909 100644 --- a/docs/docs/00200-core-concepts/00300-tables/00700-storage-and-cache-policies.md +++ b/docs/docs/00200-core-concepts/00300-tables/00700-storage-and-cache-policies.md @@ -12,12 +12,16 @@ SpacetimeDB uses tiered storage to keep frequently accessed data in memory while | Allowed storage tiers | TypeScript / Rust value | C# value | Behavior | |-----------------------|-------------------------|----------|----------| -| Memory only (default) | `required_in_memory` | `RequiredInMemory` | Load all the table's pages and blobs into memory at start up. | +| Memory only (default) | `required_in_memory` | `RequiredInMemory` | Load all the table's pages and blobs into memory at start up. | | Memory and local disk | `required_on_disk` | `RequiredOnDisk` | Allow colder data to page out of memory to local disk. Hot data can remain in memory. | | Any available tier | `no_requirement` | `NoRequirement` | Allow memory, local disk, and object storage where the deployment enables it. | Omitting the setting selects the in-memory policy. SpacetimeDB moves eligible data out of memory as it needs room and loads it again when accessed. See [Resident memory limits](../../00250-how-to/00100-deploy/00100-maincloud.md#resident-memory-limits) for how this works on Maincloud. +Any indexes on tables with `required_on_disk` or `no_requirement` must be **B-trees**. Hash and direct indexes are not supported on those tables. If you change an existing table's policy, check its indexes before republishing. + +The standalone server currently uses an unlimited resident-memory budget, so choosing a policy alone does not make a local database evict data. Eviction depends on the server's configured storage tiers and memory budget; a cache policy does not configure a backend or force eviction. + ## Declare the Policy in Your Module These examples define a table that can page to local disk and a table that can page to any available tier. @@ -105,9 +109,9 @@ pub struct ArchivedHistory { ## Residency, Durability, and Performance -Cache policies control where data can reside while the database is running. They do not affect durability. For example, when a database restarts, SpacetimeDB recovers data even for tables configured to reside fully in memory. +Cache policies control where data can reside while the database is running. They do not affect durability. For example, when a database restarts, SpacetimeDB recovers data even for tables configured to reside fully in memory. -The policy applies to table pages and large values stored as blobs. A blob shared by multiple tables stays in memory if at least one of their policies requires it. +The policy applies to table pages and large values stored as blobs. A blob shared by multiple tables stays in memory if at least one of their policies requires it. Accessing cold data may require storage reads, increasing latency. Use indexed lookups to limit the pages an operation touches, and reserve the in-memory policy for data that needs consistently fast access. Large scans can bring substantial amounts of cold data into the cache. See [Performance Best Practices](./00600-performance.md). diff --git a/docs/docs/00200-core-concepts/00600-clients/00500-rust-reference.md b/docs/docs/00200-core-concepts/00600-clients/00500-rust-reference.md index 462b79d3565..2df3d0af7bb 100644 --- a/docs/docs/00200-core-concepts/00600-clients/00500-rust-reference.md +++ b/docs/docs/00200-core-concepts/00600-clients/00500-rust-reference.md @@ -326,6 +326,8 @@ trait DbContext { Gracefully close the `DbConnection`. Returns an `Err` if the connection is already disconnected. +The close request is queued, so keep advancing the connection (for example, with `run_threaded`, `run_async`, or `frame_tick`) until shutdown is processed. Once an established connection ends, its `on_disconnect` callback runs even if another mutation was queued after the close request. Do not queue new reducer or procedure calls after requesting shutdown; they cannot be sent after the connection closes. + ### Subscribe to queries | Name | Description | diff --git a/skills/concepts/SKILL.md b/skills/concepts/SKILL.md index 07e7ad920d8..291b108efdd 100644 --- a/skills/concepts/SKILL.md +++ b/skills/concepts/SKILL.md @@ -148,7 +148,7 @@ Use HTTP handlers for webhooks and for clients that can't use a SpacetimeDB SDK. ## Table Storage Policies -Tables default to keeping pages and blobs resident in memory. A cache policy can permit eviction to local disk (`required_on_disk`) or any configured tier (`no_requirement`), including remote object storage. It does not configure a backend or force eviction; actual eviction depends on server tiers and memory budgets. Any indexes on tables with non-default policies must be B-trees. See https://spacetimedb.com/docs/tables#storage-policy and the language-specific table options. +Tables default to keeping pages and blobs resident in memory. A cache policy can permit eviction to local disk (`required_on_disk`) or any configured tier (`no_requirement`), including remote object storage. It does not configure a backend or force eviction; actual eviction depends on server tiers and memory budgets. Any indexes on tables with non-default policies must be B-trees. The standalone server currently uses an unlimited resident-memory budget. Change a policy by republishing without deleting data; moving back to the in-memory policy requires enough memory to load and retain the table. See https://spacetimedb.com/docs/tables/storage-and-cache-policies and the language-specific table options. ## Reusable Modules and Configuration From 6f36680c4529ee79ffbdd4b4177756a495959984 Mon Sep 17 00:00:00 2001 From: clockwork-labs-bot Date: Sat, 21 Nov 2026 09:04:08 -0500 Subject: [PATCH 15/21] docs: add shared outbound HTTP timeout guidance --- codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md | 2 ++ skills/concepts/SKILL.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md index 291b108efdd..fe6bdb759cc 100644 --- a/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md @@ -136,6 +136,8 @@ Lifecycle: Write → Compile → Publish (`spacetime publish`) → Hot-swap (rep Scheduled functions are private, but the database owner can still call them directly. To restrict a callback to scheduler execution, compare the sender with the database identity; see the server skills for language-specific syntax. +Outbound HTTP requests from procedures default to a 30-second timeout when none is specified; the host clamps requested timeouts to a maximum of 180 seconds. See [procedure HTTP requests](https://spacetimedb.com/docs/functions/procedures#http-requests) and the language-specific server skills for request syntax. + ## HTTP Handlers A module can expose its own HTTP API. Each handler takes a request and returns a response, and one router per module binds handlers to a method and path. Requests reach them under `/v1/database//route`, so a `/say-hello` route is served at `/v1/database/my-db/route/say-hello`. diff --git a/skills/concepts/SKILL.md b/skills/concepts/SKILL.md index 291b108efdd..fe6bdb759cc 100644 --- a/skills/concepts/SKILL.md +++ b/skills/concepts/SKILL.md @@ -136,6 +136,8 @@ Lifecycle: Write → Compile → Publish (`spacetime publish`) → Hot-swap (rep Scheduled functions are private, but the database owner can still call them directly. To restrict a callback to scheduler execution, compare the sender with the database identity; see the server skills for language-specific syntax. +Outbound HTTP requests from procedures default to a 30-second timeout when none is specified; the host clamps requested timeouts to a maximum of 180 seconds. See [procedure HTTP requests](https://spacetimedb.com/docs/functions/procedures#http-requests) and the language-specific server skills for request syntax. + ## HTTP Handlers A module can expose its own HTTP API. Each handler takes a request and returns a response, and one router per module binds handlers to a method and path. Requests reach them under `/v1/database//route`, so a `/say-hello` route is served at `/v1/database/my-db/route/say-hello`. From fd1680aace88e7134e911494c4914b99c6a90b8e Mon Sep 17 00:00:00 2001 From: clockwork-labs-bot Date: Mon, 23 Nov 2026 09:06:39 -0500 Subject: [PATCH 16/21] docs: explain startup version checks and CPU-budget logs Document metadata compatibility and per-call CPU diagnostics; synchronize shared concepts guidance. Sources: #6666 and #6612. --- .../plugins/spacetimedb/skills/concepts/SKILL.md | 4 ++++ .../00250-how-to/00100-deploy/00200-self-hosting.md | 13 +++++++++++++ docs/docs/00250-how-to/00300-logging.md | 9 ++++++--- skills/concepts/SKILL.md | 4 ++++ 4 files changed, 27 insertions(+), 3 deletions(-) diff --git a/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md index fe6bdb759cc..efed5824b3e 100644 --- a/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md @@ -79,6 +79,10 @@ For questions about older articles, benchmarks, or past reviews, see [Common mis 4. Check server logs for errors (`spacetime logs `) 5. Is the reducer actually being called from the client? +A per-call CPU-budget abort in a reducer or view produces an error-level database log containing `reached the maximum CPU usage allowed per call`, with the function name and elapsed duration, on servers containing that logging change. Check it as the database owner with `spacetime logs --level error `; this message does not by itself mean the account balance is empty. ([Logging](https://spacetimedb.com/docs/how-to/logging/#diagnosing-cpu-budget-aborts)) + +For self-hosted server version changes, stop the service and back up the data directory. The updated `metadata.toml` startup check requires the same edition and, within one major version, a running minor at least as new as recorded; it ignores patch differences and minor/patch prerelease suffixes. A running `X.0.0-*` major prerelease requires an identical recorded version, except that the 1.x-data-to-2.x-server exception is checked first. The restriction is on the running version, not on a previously recorded major prerelease. The recorded version never decreases. Do not edit generated metadata to bypass the check or treat passing it as a blanket rollback guarantee. ([Version compatibility](https://spacetimedb.com/docs/how-to/deploy/self-hosting/#data-directory-version-compatibility)) + --- ## Tables diff --git a/docs/docs/00250-how-to/00100-deploy/00200-self-hosting.md b/docs/docs/00250-how-to/00100-deploy/00200-self-hosting.md index 51a59001f6d..b171c08b838 100644 --- a/docs/docs/00250-how-to/00100-deploy/00200-self-hosting.md +++ b/docs/docs/00250-how-to/00100-deploy/00200-self-hosting.md @@ -251,6 +251,19 @@ Finally, restart the service: sudo systemctl start spacetimedb ``` +### Data-directory version compatibility + +Before changing server versions, stop the service and back up its data directory. The server checks the generated `metadata.toml` before opening existing data; do not edit this file to bypass a compatibility error. + +For server builds containing the [updated metadata check](https://github.com/clockworklabs/SpacetimeDB/pull/6666): + +- The server edition must match the recorded edition. +- Within the same major version, the running minor version must be at least the recorded minor version. Patch downgrades and minor/patch prerelease suffixes are allowed by this check; for example, recorded `2.16.2` accepts running `2.16.0-rc1`. +- A running major prerelease (`X.0.0-*`) requires the identical recorded version. For example, recorded `3.0.0` rejects running `3.0.0-rc1`. This restriction is on the **running** version: recorded `3.0.0-rc1` accepts running `3.0.0` under the same-major rule. +- The explicit exception allowing a 2.x server to open 1.x data is checked before the major-prerelease restriction. Other cross-major changes are rejected. + +After a successful check, the recorded version only increases; opening data with a lower patch version does not lower it. Passing this startup check is not a general rollback guarantee for every storage format or release. Check the target release's migration and rollback requirements before switching binaries. + ## Step 7: Troubleshooting ### SpacetimeDB Service Fails to Start diff --git a/docs/docs/00250-how-to/00300-logging.md b/docs/docs/00250-how-to/00300-logging.md index 864c31f465d..419c23c00e4 100644 --- a/docs/docs/00250-how-to/00300-logging.md +++ b/docs/docs/00250-how-to/00300-logging.md @@ -183,13 +183,16 @@ spacetime logs --level error # Show warnings and errors spacetime logs --level warn - -# Show logs from a specific time range -spacetime logs --since "2023-01-01 00:00:00" ``` For all log viewing options, see the [`spacetime logs` CLI reference](../00300-resources/00100-cli-reference/00100-cli-reference.md#spacetime-logs). +## Diagnosing CPU-Budget Aborts + +When a reducer or view exhausts its per-call CPU budget, the host writes an error-level database log entry containing `aborted after : reached the maximum CPU usage allowed per call`, with the function name attached. `` represents the measured execution duration, not a fixed time limit. This diagnostic is available in server builds containing the [CPU-budget logging change](https://github.com/clockworklabs/SpacetimeDB/pull/6612); older servers may not emit it. + +Read these entries as the database owner with `spacetime logs --level error `. The entry reports per-call CPU-budget exhaustion, not necessarily an empty account balance. Inspect the function's work and queries, especially large scans or loops. + ## Best Practices ### Log Levels diff --git a/skills/concepts/SKILL.md b/skills/concepts/SKILL.md index fe6bdb759cc..efed5824b3e 100644 --- a/skills/concepts/SKILL.md +++ b/skills/concepts/SKILL.md @@ -79,6 +79,10 @@ For questions about older articles, benchmarks, or past reviews, see [Common mis 4. Check server logs for errors (`spacetime logs `) 5. Is the reducer actually being called from the client? +A per-call CPU-budget abort in a reducer or view produces an error-level database log containing `reached the maximum CPU usage allowed per call`, with the function name and elapsed duration, on servers containing that logging change. Check it as the database owner with `spacetime logs --level error `; this message does not by itself mean the account balance is empty. ([Logging](https://spacetimedb.com/docs/how-to/logging/#diagnosing-cpu-budget-aborts)) + +For self-hosted server version changes, stop the service and back up the data directory. The updated `metadata.toml` startup check requires the same edition and, within one major version, a running minor at least as new as recorded; it ignores patch differences and minor/patch prerelease suffixes. A running `X.0.0-*` major prerelease requires an identical recorded version, except that the 1.x-data-to-2.x-server exception is checked first. The restriction is on the running version, not on a previously recorded major prerelease. The recorded version never decreases. Do not edit generated metadata to bypass the check or treat passing it as a blanket rollback guarantee. ([Version compatibility](https://spacetimedb.com/docs/how-to/deploy/self-hosting/#data-directory-version-compatibility)) + --- ## Tables From 993f1193378d9ebad071193d82c507d159b4c39a Mon Sep 17 00:00:00 2001 From: clockwork-labs-bot Date: Tue, 24 Nov 2026 09:08:46 -0500 Subject: [PATCH 17/21] docs: cover Stripe integration and recovery memory budgets Daily commit-impact audit of 7bb7e80c0..c31d45503. Sources: #5906, #6658; SDK compatibility #6681 reviewed. Documentation only. --- .../spacetimedb/skills/concepts/SKILL.md | 3 +++ .../skills/typescript-server/SKILL.md | 2 ++ .../00100-databases/00600-modules.md | 1 + .../00700-storage-and-cache-policies.md | 2 ++ modules/spacetime-stripe-ts/README.md | 24 ++++++++++++++----- modules/spacetime-stripe-ts/example/README.md | 5 ++-- skills/concepts/SKILL.md | 3 +++ skills/typescript-server/SKILL.md | 2 ++ 8 files changed, 34 insertions(+), 8 deletions(-) diff --git a/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md index efed5824b3e..8f2e6c17e6c 100644 --- a/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md @@ -36,6 +36,7 @@ This describes Spacetime 2.x. The API changed substantially from 1.x, so older a - **Access control.** Tables are private by default. Views expose exactly the rows and columns each client should see, including per-caller views filtered by the caller's identity. ([Access permissions](https://spacetimedb.com/docs/tables/access-permissions/)) - **Auth.** Spacetime works with any OIDC provider, such as Auth0, Clerk, Better Auth, or Firebase Auth. SpacetimeAuth is a first-party provider with magic links, social logins, and user and role management. ([Authentication](https://spacetimedb.com/docs/core-concepts/authentication/)) - **Scheduled work.** Schedule tables run reducers or procedures at a specific time or on a repeating interval. In TypeScript, the Cron module adds calendar schedules with time zones. ([Schedule tables](https://spacetimedb.com/docs/tables/schedule-tables/), [Cron module](https://spacetimedb.com/modules/cron)) +- **Payments.** The TypeScript Stripe module supplies Checkout, billing portal, subscription, and signed-webhook helpers. The host application authenticates users and controls ownership and prices. Fulfill purchases from verified webhook payment state, not the browser redirect. ([Stripe module](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-stripe-ts)) - **Ephemeral events.** Event tables broadcast rows to subscribers without storing them, for things like typing indicators. ([Event tables](https://spacetimedb.com/docs/tables/event-tables/)) - **Files.** Files can be stored as bytes in table columns, or a procedure can store large files in S3 or a similar service and keep a reference in a table. In TypeScript, the Files module handles database-backed uploads, listing and download routes; the S3 module keeps bytes in a private bucket and tracks ownership and upload state in the database. ([File storage](https://spacetimedb.com/docs/tables/file-storage/), [Files module](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-files-ts), [S3 module](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-s3-ts)) - **SQL and tools.** Spacetime speaks the PostgreSQL wire protocol, so PostgreSQL drivers, `psql`, and GUI clients can connect. ([PostgreSQL wire protocol](https://spacetimedb.com/docs/how-to/pg-wire/)) @@ -156,6 +157,8 @@ Use HTTP handlers for webhooks and for clients that can't use a SpacetimeDB SDK. Tables default to keeping pages and blobs resident in memory. A cache policy can permit eviction to local disk (`required_on_disk`) or any configured tier (`no_requirement`), including remote object storage. It does not configure a backend or force eviction; actual eviction depends on server tiers and memory budgets. Any indexes on tables with non-default policies must be B-trees. The standalone server currently uses an unlimited resident-memory budget. Change a policy by republishing without deleting data; moving back to the in-memory policy requires enough memory to load and retain the table. See https://spacetimedb.com/docs/tables/storage-and-cache-policies and the language-specific table options. +Recovery temporarily suspends the storage engine's resident-memory hard limit, then re-enables it and attempts eviction before serving transactions. Required-in-memory data can leave usage above budget, so later operations can still fail for lack of memory. This does not bypass process or physical memory limits. See [storage recovery](https://spacetimedb.com/docs/tables/storage-and-cache-policies/#residency-durability-and-performance). + ## Reusable Modules and Configuration TypeScript and C# support same-language submodule composition. A namespace has a language accessor and a canonical database name; SQL, CLI calls, and HTTP calls use the canonical name. Changing the canonical namespace drops its tables and their data, so pin it when renaming an accessor. TypeScript supports nested submodules; C# composition requires 2.13+ with .NET 10/C# 14, and nested or repeated C# mounts require 2.14+. See the respective server skills for registration and helper-context rules. diff --git a/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md index 69c5d670973..5a39dff12b7 100644 --- a/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md @@ -287,6 +287,8 @@ For large external files, `@spacetimedb/s3/submodule` supplies the private state For server-side PostHog analytics, mount `@spacetimedb/posthog/submodule` in the root schema, then call `posthog.install(ctx.as.posthog)` from the root init reducer. After the host reducer's authorization and state change, call `posthog.enqueueEventInTx(ctx.as.posthog, args)` to queue an event in that same transaction; it does not make a network request. Use `tx.as.posthog` inside a procedure's `withTx`, not the procedure context. An administrator must configure the provider before scheduled delivery can send events. See the [package integration guide](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-posthog-ts#integrate-into-an-application) for its exact schema, imports, arguments, and delivery semantics. +For Stripe billing, mount `@spacetimedb/stripe/submodule`, call `stripe.install(ctx.as.stripe)` from the root init reducer, and configure credentials as an administrator. Register a root HTTP handler that calls `stripe.handleStripeWebhook(ctx, req, { stripe: tx => tx.as.stripe })`; the selector receives the host transaction. Call network helpers such as `stripe.createUserCheckoutSession(ctx.as.stripe, args)` from a procedure, outside `withTx`. Derive `userId`, catalog prices, and return URLs from trusted application context; helpers do not authenticate callers. An optional synchronous `onEvent(tx, event)` callback writes fulfillment records in the same transaction as the webhook state; validate event fields and deduplicate by business-object ID, not only event ID. See the [exact integration schema and fulfillment rules](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-stripe-ts#integrate-into-an-application). + ## Environment Variables ```typescript diff --git a/docs/docs/00200-core-concepts/00100-databases/00600-modules.md b/docs/docs/00200-core-concepts/00100-databases/00600-modules.md index 51e0380d96d..38cc67ed175 100644 --- a/docs/docs/00200-core-concepts/00100-databases/00600-modules.md +++ b/docs/docs/00200-core-concepts/00100-databases/00600-modules.md @@ -23,6 +23,7 @@ Official packages provide reusable application features. Follow each package's i - [Files](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-files-ts) stores file contents in database tables and supplies upload, listing, and download helpers. Mount `@spacetimedb/files/submodule`; pass its helper context from a reducer or a procedure transaction. - [S3](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-s3-ts) stores file contents in a private S3 bucket while keeping ownership and upload state in SpacetimeDB. Its guide covers bucket permissions, root environment declarations for credentials, initialization, and a scheduled reconciliation procedure. Derive file ownership on the server, never from a client-supplied owner. - [PostHog](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-posthog-ts) queues analytics events transactionally for scheduled delivery. Mount `@spacetimedb/posthog/submodule`, initialize it from the root, and configure the provider before sending events. +- [Stripe](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-stripe-ts) supplies Checkout, customer billing portal, subscription, and signed-webhook helpers. Mount `@spacetimedb/stripe/submodule`, initialize it from the root, configure its credentials as an administrator, and delegate its webhook handler from the root router. Host procedures must authenticate users and derive ownership, prices, and return URLs from trusted state. Fulfill purchases from verified webhook payment state, not a browser redirect; see the package's [fulfillment guide](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-stripe-ts#checkout-fulfillment). These packages require SpacetimeDB SDK, CLI, and server 2.12 or later. Their tables are private; expose only authorized data through your application's views and operations. Perform network I/O in procedures or HTTP handlers, not inside transactions. diff --git a/docs/docs/00200-core-concepts/00300-tables/00700-storage-and-cache-policies.md b/docs/docs/00200-core-concepts/00300-tables/00700-storage-and-cache-policies.md index 18dcf437909..67ce9dc7326 100644 --- a/docs/docs/00200-core-concepts/00300-tables/00700-storage-and-cache-policies.md +++ b/docs/docs/00200-core-concepts/00300-tables/00700-storage-and-cache-policies.md @@ -111,6 +111,8 @@ pub struct ArchivedHistory { Cache policies control where data can reside while the database is running. They do not affect durability. For example, when a database restarts, SpacetimeDB recovers data even for tables configured to reside fully in memory. +During database recovery, the storage engine temporarily suspends enforcement of the resident-memory hard limit while reconstructing committed data, rebuilding state, and running startup migrations. It then re-enables the limit and attempts to trim eligible data before serving transactions. Required-in-memory data can keep usage above the configured limit; recovery is not a guarantee that subsequent operations have enough memory to succeed. This storage-engine budget is not a process or machine memory limit: recovery still needs enough physical memory to complete. + The policy applies to table pages and large values stored as blobs. A blob shared by multiple tables stays in memory if at least one of their policies requires it. Accessing cold data may require storage reads, increasing latency. Use indexed lookups to limit the pages an operation touches, and reserve the in-memory policy for data that needs consistently fast access. Large scans can bring substantial amounts of cold data into the cache. See [Performance Best Practices](./00600-performance.md). diff --git a/modules/spacetime-stripe-ts/README.md b/modules/spacetime-stripe-ts/README.md index fe76f8545de..4c6db9106a9 100644 --- a/modules/spacetime-stripe-ts/README.md +++ b/modules/spacetime-stripe-ts/README.md @@ -30,9 +30,18 @@ an administrator with `stripe.set_stripe_config`. See the arguments in with Stripe and select the [events listed below](#webhook-events-handled). ```ts -import { Router, SenderError, schema, t } from 'spacetimedb/server'; +import { Router, SenderError, schema, table, t } from 'spacetimedb/server'; import * as stripe from '@spacetimedb/stripe/submodule'; +const storeProduct = table( + { name: 'store_product' }, + { + productId: t.string().primaryKey(), + active: t.bool(), + stripePriceId: t.option(t.string()), + } +); + const spacetimedb = schema({ stripe, storeProduct }); export default spacetimedb; @@ -48,10 +57,13 @@ export const router = spacetimedb.httpRouter( ); ``` -The submodule's procedures are admin-only. Signed-in users reach Stripe through -host procedures that call the host helpers with `ctx.as.stripe`. The host -procedure resolves the user from `ctx.sender`, -takes prices from a server-owned catalog, and fixes the return URLs: +The submodule's billing and query procedures are admin-only. Application users +reach Stripe through host procedures that call the host helpers with +`ctx.as.stripe`. These helpers do not authenticate the caller. The example below +keys customers by the caller's SpacetimeDB identity and accepts any connected +identity; add your application's account authorization and rate limits before +exposing checkout publicly. The host procedure resolves the user from +`ctx.sender`, takes prices from a server-owned catalog, and fixes the return URLs: ```ts const APP_ORIGIN = 'https://store.example.com'; @@ -116,7 +128,7 @@ For `t.option(...)` CLI arguments, use `null` for no value and Verify: ```bash -spacetime call --server http://127.0.0.1:3000 stripe-ts get_stripe_config_status '{}' +spacetime call --server http://127.0.0.1:3000 stripe-ts get_stripe_config_status ``` ## Private tables diff --git a/modules/spacetime-stripe-ts/example/README.md b/modules/spacetime-stripe-ts/example/README.md index 871e017f3c8..191be6ec034 100644 --- a/modules/spacetime-stripe-ts/example/README.md +++ b/modules/spacetime-stripe-ts/example/README.md @@ -5,8 +5,9 @@ with Stripe test payments. ## Run it locally -Requires Node.js 20+, pnpm 10, and the SpacetimeDB CLI and server built from -this checkout. +Requires a supported Node.js release (22.23.4+, 24.22.1+, or 26.12.1+ on +those release lines), pnpm 10.16+, and the SpacetimeDB CLI and server built +from this checkout. Start SpacetimeDB in a separate terminal: diff --git a/skills/concepts/SKILL.md b/skills/concepts/SKILL.md index efed5824b3e..8f2e6c17e6c 100644 --- a/skills/concepts/SKILL.md +++ b/skills/concepts/SKILL.md @@ -36,6 +36,7 @@ This describes Spacetime 2.x. The API changed substantially from 1.x, so older a - **Access control.** Tables are private by default. Views expose exactly the rows and columns each client should see, including per-caller views filtered by the caller's identity. ([Access permissions](https://spacetimedb.com/docs/tables/access-permissions/)) - **Auth.** Spacetime works with any OIDC provider, such as Auth0, Clerk, Better Auth, or Firebase Auth. SpacetimeAuth is a first-party provider with magic links, social logins, and user and role management. ([Authentication](https://spacetimedb.com/docs/core-concepts/authentication/)) - **Scheduled work.** Schedule tables run reducers or procedures at a specific time or on a repeating interval. In TypeScript, the Cron module adds calendar schedules with time zones. ([Schedule tables](https://spacetimedb.com/docs/tables/schedule-tables/), [Cron module](https://spacetimedb.com/modules/cron)) +- **Payments.** The TypeScript Stripe module supplies Checkout, billing portal, subscription, and signed-webhook helpers. The host application authenticates users and controls ownership and prices. Fulfill purchases from verified webhook payment state, not the browser redirect. ([Stripe module](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-stripe-ts)) - **Ephemeral events.** Event tables broadcast rows to subscribers without storing them, for things like typing indicators. ([Event tables](https://spacetimedb.com/docs/tables/event-tables/)) - **Files.** Files can be stored as bytes in table columns, or a procedure can store large files in S3 or a similar service and keep a reference in a table. In TypeScript, the Files module handles database-backed uploads, listing and download routes; the S3 module keeps bytes in a private bucket and tracks ownership and upload state in the database. ([File storage](https://spacetimedb.com/docs/tables/file-storage/), [Files module](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-files-ts), [S3 module](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-s3-ts)) - **SQL and tools.** Spacetime speaks the PostgreSQL wire protocol, so PostgreSQL drivers, `psql`, and GUI clients can connect. ([PostgreSQL wire protocol](https://spacetimedb.com/docs/how-to/pg-wire/)) @@ -156,6 +157,8 @@ Use HTTP handlers for webhooks and for clients that can't use a SpacetimeDB SDK. Tables default to keeping pages and blobs resident in memory. A cache policy can permit eviction to local disk (`required_on_disk`) or any configured tier (`no_requirement`), including remote object storage. It does not configure a backend or force eviction; actual eviction depends on server tiers and memory budgets. Any indexes on tables with non-default policies must be B-trees. The standalone server currently uses an unlimited resident-memory budget. Change a policy by republishing without deleting data; moving back to the in-memory policy requires enough memory to load and retain the table. See https://spacetimedb.com/docs/tables/storage-and-cache-policies and the language-specific table options. +Recovery temporarily suspends the storage engine's resident-memory hard limit, then re-enables it and attempts eviction before serving transactions. Required-in-memory data can leave usage above budget, so later operations can still fail for lack of memory. This does not bypass process or physical memory limits. See [storage recovery](https://spacetimedb.com/docs/tables/storage-and-cache-policies/#residency-durability-and-performance). + ## Reusable Modules and Configuration TypeScript and C# support same-language submodule composition. A namespace has a language accessor and a canonical database name; SQL, CLI calls, and HTTP calls use the canonical name. Changing the canonical namespace drops its tables and their data, so pin it when renaming an accessor. TypeScript supports nested submodules; C# composition requires 2.13+ with .NET 10/C# 14, and nested or repeated C# mounts require 2.14+. See the respective server skills for registration and helper-context rules. diff --git a/skills/typescript-server/SKILL.md b/skills/typescript-server/SKILL.md index 69c5d670973..5a39dff12b7 100644 --- a/skills/typescript-server/SKILL.md +++ b/skills/typescript-server/SKILL.md @@ -287,6 +287,8 @@ For large external files, `@spacetimedb/s3/submodule` supplies the private state For server-side PostHog analytics, mount `@spacetimedb/posthog/submodule` in the root schema, then call `posthog.install(ctx.as.posthog)` from the root init reducer. After the host reducer's authorization and state change, call `posthog.enqueueEventInTx(ctx.as.posthog, args)` to queue an event in that same transaction; it does not make a network request. Use `tx.as.posthog` inside a procedure's `withTx`, not the procedure context. An administrator must configure the provider before scheduled delivery can send events. See the [package integration guide](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-posthog-ts#integrate-into-an-application) for its exact schema, imports, arguments, and delivery semantics. +For Stripe billing, mount `@spacetimedb/stripe/submodule`, call `stripe.install(ctx.as.stripe)` from the root init reducer, and configure credentials as an administrator. Register a root HTTP handler that calls `stripe.handleStripeWebhook(ctx, req, { stripe: tx => tx.as.stripe })`; the selector receives the host transaction. Call network helpers such as `stripe.createUserCheckoutSession(ctx.as.stripe, args)` from a procedure, outside `withTx`. Derive `userId`, catalog prices, and return URLs from trusted application context; helpers do not authenticate callers. An optional synchronous `onEvent(tx, event)` callback writes fulfillment records in the same transaction as the webhook state; validate event fields and deduplicate by business-object ID, not only event ID. See the [exact integration schema and fulfillment rules](https://github.com/clockworklabs/SpacetimeDB/tree/master/modules/spacetime-stripe-ts#integrate-into-an-application). + ## Environment Variables ```typescript From 62ce713ef84f2a20f70fa0b19911a890ae49efad Mon Sep 17 00:00:00 2001 From: clockwork-labs-bot Date: Wed, 25 Nov 2026 09:05:23 -0500 Subject: [PATCH 18/21] docs: clarify testing platforms, runtime limits and connection paths --- .../plugins/spacetimedb/skills/cli/SKILL.md | 4 +++- .../spacetimedb/skills/concepts/SKILL.md | 4 +++- .../spacetimedb/skills/csharp-server/SKILL.md | 8 ++++++-- .../skills/typescript-client/SKILL.md | 2 ++ .../skills/typescript-server/SKILL.md | 4 ++++ docs/README.md | 18 ++++++++++++------ .../00650-inter-database-communication.md | 2 +- .../00700-typescript-reference.md | 2 ++ .../docs/00250-how-to/00050-troubleshooting.md | 4 ++++ docs/docs/00250-how-to/00900-unit-testing.md | 2 ++ skills/cli/SKILL.md | 4 +++- skills/concepts/SKILL.md | 4 +++- skills/csharp-server/SKILL.md | 8 ++++++-- skills/typescript-client/SKILL.md | 2 ++ skills/typescript-server/SKILL.md | 4 ++++ tools/llm-sequential-upgrade/CLAUDE.md | 2 ++ 16 files changed, 59 insertions(+), 15 deletions(-) diff --git a/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md index 4f0fa27bd1b..d63ad63526e 100644 --- a/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md @@ -75,7 +75,9 @@ Use `spacetime init --lang csharp --dotnet-version 10 my-project` to select Do not make the project permanently WASM-only to fix a managed build: keep LLVM package references and WASM settings conditional on the RID. Let dotnet restore -when changing build modes. Managed builds alone do not enable C# module unit tests. +when changing build modes. Managed builds alone do not enable C# module unit tests: +use a separate .NET 10 test project with the matching `SpacetimeDB.Testing` +package and a supported native platform, as described in the C# server skill. .NET 8 retains WASM/JIT by default and requires `--native-aot` to select NativeAOT where supported. The CLI manages `SPACETIMEDB_WASM_AOT` and its legacy alias diff --git a/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md index 8f2e6c17e6c..f5a5741c8c4 100644 --- a/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md @@ -169,12 +169,14 @@ Database environment values are read-only strings, including secrets, supplied a Views can accept arguments in 2.13+ (Rust, TypeScript, C#), queried as `SELECT * FROM view_name(42)`. Use explicit queries instead of subscribe-all on that connection; subscribe-all skips these views. See server skills for definition restrictions and client skills for query/cache rules. -Rust and TypeScript provide in-memory module unit-test harnesses in 2.12+: run native `cargo test` or Vitest with the module-test plugin. These use the real datastore but do not simulate clients, subscriptions, RLS enforcement, lifecycle events, or timer execution. Test those host behaviors against a running database. +Rust and TypeScript provide in-memory module unit-test harnesses in 2.12+: run native `cargo test` or Vitest with the module-test plugin. C# also provides a managed .NET 10 harness via the separate `SpacetimeDB.Testing` package; see the C# server skill for platform and package requirements. These use the real datastore but do not simulate clients, subscriptions, RLS enforcement, lifecycle events, or timer execution. Test those host behaviors against a running database. ## Inter-Database Communication Reducers can't make network requests, but a reducer can call a reducer in another database on the same server through an **outbox table** (async IDC). The reducer inserts a row, and after its transaction commits, the row is delivered as a reducer call to the target database exactly once, in order with other calls through the same outbox to the same database. The sending reducer doesn't wait, and the two databases don't commit together: the receiving reducer runs later in its own transaction and can fail. An optional `on_result` reducer in the sending database receives the result, so it can undo or record the work. +Deliveries can be pipelined. Receiving calls and `on_result` callbacks each retain stream order, but a later receiving call need not wait for an earlier callback in the sending database. Do not use callbacks as barriers for subsequent receiving calls. + Use it to split an application into databases that scale and deploy independently, such as a lobby that sends players to separate game world databases. Only Rust and TypeScript modules can declare outbox tables. See the language-specific server skills for syntax. ## Identity diff --git a/codex-plugin/plugins/spacetimedb/skills/csharp-server/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/csharp-server/SKILL.md index 3c735f6d8ba..1bca49895de 100644 --- a/codex-plugin/plugins/spacetimedb/skills/csharp-server/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/csharp-server/SKILL.md @@ -17,10 +17,14 @@ metadata: Module unit tests use a sibling .NET 10 test project with an ordinary module `ProjectReference` and the separate `SpacetimeDB.Testing` NuGet package, at exactly -the module's Runtime version. Run with `dotnet test`; no server or Rust compiler +the module's Runtime version, from a release publishing both packages. Native +libraries support Linux x64/ARM64 (glibc 2.35+) and Windows x64, not macOS. +Run with `dotnet test`; no server or Rust compiler is required. Keep Testing out of module dependencies and test sources outside the module directory. Use `using var test = ModuleTestContext.Create(typeof(Module).Assembly)` -and `test.WithReducerTx(TestAuth.Internal(), ctx => Module.Reducer(ctx))`. +and, for the module below, +`test.WithReducerTx(TestAuth.Internal(), ctx => Module.AddRecord(ctx, 1))` +with `using SpacetimeDB.Testing;` in the test project. Callbacks are synchronous; one fixture supports one execution flow, while separate fixtures may run in parallel. The chat-console-cs template includes tests for .NET 10 only. See `/how-to/unit-testing` for setup and release availability. diff --git a/codex-plugin/plugins/spacetimedb/skills/typescript-client/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/typescript-client/SKILL.md index d311d31d766..914adaea413 100644 --- a/codex-plugin/plugins/spacetimedb/skills/typescript-client/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/typescript-client/SKILL.md @@ -17,6 +17,8 @@ Generated bindings convert snake_case names to camelCase, including row fields: The examples below use bundler-style extensionless imports. For NodeNext or direct-TypeScript execution, choose the matching binding import extension and use explicit file imports in your application; see https://spacetimedb.com/docs/clients/typescript#import-extensions. +`withUri` takes the server base URI, not a subscription endpoint. It preserves a path prefix: `wss://example.com/stdb` (or `/stdb/`) uses `/stdb/v1/database//subscribe` and the HTTPS token-exchange endpoint `/stdb/v1/identity/websocket-token`. A reverse proxy must forward both endpoints, stripping its prefix when forwarding to a root-mounted server. + ## React: main.tsx ```typescript diff --git a/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md index 5a39dff12b7..120d6296cd5 100644 --- a/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md @@ -13,6 +13,10 @@ metadata: # SpacetimeDB TypeScript SDK Reference +## Runtime Memory + +V8's module memory limit includes `ArrayBuffer` allocations (and typed-array backing buffers), not just ordinary JavaScript objects. Limit peak buffer allocations and copies. This is separate from the storage engine's resident-memory budget; changing table cache policies does not increase the V8 limit. + ## Module Structure Tables are built with `table()`, bound with `schema()`, and exported as default. Reducers and lifecycle hooks are `export const`: diff --git a/docs/README.md b/docs/README.md index a0f10412614..4d34cee9fba 100644 --- a/docs/README.md +++ b/docs/README.md @@ -51,12 +51,18 @@ For more information on how to use Docusaurus, see the #### Installation -1. Make sure you have [Node.js](https://nodejs.org/) installed - (version 22 or higher is recommended). -2. Clone the repository and navigate to the `docs` directory. -3. Install the dependencies: `pnpm install` -4. Run the development server: `pnpm dev`, which will start a local server and open a browser window. - All changes you make to the markdown files will be reflected live in the browser. +1. Install [Node.js](https://nodejs.org/) matching the repository's engines: + `^22.23.4 || ^24.22.1 || >=26.12.1`, and pnpm 10.16.0 (the version pinned in the root `package.json`). +2. Clone the repository and navigate to its root, `SpacetimeDB/`. +3. Install the docs dependencies using the root workspace lockfile: + `pnpm --filter docs... install --frozen-lockfile`. +4. Run `pnpm --filter docs dev`, which starts a local server and opens a browser window. + Markdown edits appear live in the browser. +5. Before opening a PR, run `pnpm --filter docs typecheck` and `pnpm --filter docs build`. + +Repository JavaScript packages use pnpm. Do not create or commit `package-lock.json`; +`cargo ci lockfile-policy` rejects npm lockfiles. This policy applies to this +repository, not to applications consuming the published SDK. ### Cutting Docs Versions diff --git a/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md b/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md index f57ba674e6d..b6dc082c697 100644 --- a/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md +++ b/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md @@ -26,7 +26,7 @@ By contrast, Spacetime async IDC provides a set of important guarantees that red - **Atomic with the sending transaction** An outbox row is part of the transaction that inserts it. If the transaction commits, SpacetimeDB sends the call. If it rolls back, nothing is sent. - **Exactly once semantics** Spacetime retries delivery until the receiving database answers, and the receiving database discards duplicates, so the receiving reducer runs once for each row. This invariant is maintained across crashes and server restarts, without any additional work from the module developer. -- **In order** Calls through one outbox table to one database run in the order their rows were inserted. Calls through different outbox tables, or to different databases, are not ordered relative to each other. +- **In order** Calls through one outbox table to one database run in the order their rows were inserted. Calls through different outbox tables, or to different databases, are not ordered relative to each other. Deliveries may be pipelined, but receiving calls and `on_result` callbacks retain stream order. A later receiving call can run before an earlier call's `on_result`; do not use that callback as a barrier for later receiving calls. - **Durable first** Spacetime sends a call only after the transaction that inserted it is durable, so the receiving database never acts on a call from a transaction that the sending database could lose in a crash. - **Non-blocking** The sending reducer finishes as soon as its transaction commits. The receiving database doesn't need to be available at the time of the call. The call will be made once the receiving database is available. - **Authenticated** In the receiving reducer, `ctx.sender` is the sending database's identity. Spacetime authenticates all async IDC calls, so one database can't pose as another. diff --git a/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md b/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md index c22dd9d7fe4..419c97b2a2e 100644 --- a/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md +++ b/docs/docs/00200-core-concepts/00600-clients/00700-typescript-reference.md @@ -152,6 +152,8 @@ class DbConnectionBuilder { Configure the URI of the SpacetimeDB instance or cluster which hosts the remote database. +The SDK preserves a path prefix, with or without a trailing slash. For example, `wss://example.com/stdb` connects to `/stdb/v1/database//subscribe` and exchanges authentication tokens at `https://example.com/stdb/v1/identity/websocket-token`. Configure your reverse proxy to forward both endpoints to SpacetimeDB, stripping the `/stdb` prefix if the server is mounted at `/`. Supply only the server base URI, not the database subscription endpoint. + #### Method `withDatabaseName` ```typescript diff --git a/docs/docs/00250-how-to/00050-troubleshooting.md b/docs/docs/00250-how-to/00050-troubleshooting.md index 0c75b96741d..99d2540f2be 100644 --- a/docs/docs/00250-how-to/00050-troubleshooting.md +++ b/docs/docs/00250-how-to/00050-troubleshooting.md @@ -65,6 +65,10 @@ If you see `Database resident memory budget exceeded`, the operation couldn't ge 2. **Allow a table to use more storage tiers.** Change its [cache policy](../00200-core-concepts/00300-tables/00700-storage-and-cache-policies.md) to `RequiredOnDisk` to allow paging to local disk, or to `NoRequirement` to allow paging to any available tier. Follow the [migration steps](../00200-core-concepts/00100-databases/00500-migrations/00200-automatic-migrations.md#changing-a-tables-cache-policy) to republish while keeping existing rows. SpacetimeDB can then evict eligible data as it needs room. 3. **Contact Maincloud support if recovery operations also hit the limit.** Include your database identity, the operation that failed, and the full error message. +## TypeScript module memory limit exceeded + +`Javascript module exceeded memory limit` refers to the TypeScript module's V8 runtime, not the database's resident storage budget. `ArrayBuffer` allocations, including typed-array backing buffers, count toward the V8 memory limit as well as ordinary JavaScript objects. Reduce peak allocations: process large inputs in smaller batches and avoid retaining or copying entire buffers unnecessarily. Allowing tables to page to disk does not increase the V8 limit. + ## In Modules ### Identity seen by reducers never changes diff --git a/docs/docs/00250-how-to/00900-unit-testing.md b/docs/docs/00250-how-to/00900-unit-testing.md index 144041ab058..e2f487179a8 100644 --- a/docs/docs/00250-how-to/00900-unit-testing.md +++ b/docs/docs/00250-how-to/00900-unit-testing.md @@ -327,6 +327,8 @@ The rest of this guide shows fragments rather than whole files. Code marked `// Use .NET 10 and a separate test project referencing `SpacetimeDB.Testing`, at exactly the same version as your module's `SpacetimeDB.Runtime` package. These examples use xUnit. No server, Rust compiler, or WASI workload is needed. +The testing package includes native datastore libraries for Linux x64/ARM64 (glibc 2.35 or later) and Windows x64. macOS is not supported; run C# module tests in a supported Linux environment or Windows. Use a release that publishes matching Testing and Runtime packages. + Keep tests in a sibling project, outside the module directory, so the module's default compile glob does not include test code: ```text diff --git a/skills/cli/SKILL.md b/skills/cli/SKILL.md index 4f0fa27bd1b..d63ad63526e 100644 --- a/skills/cli/SKILL.md +++ b/skills/cli/SKILL.md @@ -75,7 +75,9 @@ Use `spacetime init --lang csharp --dotnet-version 10 my-project` to select Do not make the project permanently WASM-only to fix a managed build: keep LLVM package references and WASM settings conditional on the RID. Let dotnet restore -when changing build modes. Managed builds alone do not enable C# module unit tests. +when changing build modes. Managed builds alone do not enable C# module unit tests: +use a separate .NET 10 test project with the matching `SpacetimeDB.Testing` +package and a supported native platform, as described in the C# server skill. .NET 8 retains WASM/JIT by default and requires `--native-aot` to select NativeAOT where supported. The CLI manages `SPACETIMEDB_WASM_AOT` and its legacy alias diff --git a/skills/concepts/SKILL.md b/skills/concepts/SKILL.md index 8f2e6c17e6c..f5a5741c8c4 100644 --- a/skills/concepts/SKILL.md +++ b/skills/concepts/SKILL.md @@ -169,12 +169,14 @@ Database environment values are read-only strings, including secrets, supplied a Views can accept arguments in 2.13+ (Rust, TypeScript, C#), queried as `SELECT * FROM view_name(42)`. Use explicit queries instead of subscribe-all on that connection; subscribe-all skips these views. See server skills for definition restrictions and client skills for query/cache rules. -Rust and TypeScript provide in-memory module unit-test harnesses in 2.12+: run native `cargo test` or Vitest with the module-test plugin. These use the real datastore but do not simulate clients, subscriptions, RLS enforcement, lifecycle events, or timer execution. Test those host behaviors against a running database. +Rust and TypeScript provide in-memory module unit-test harnesses in 2.12+: run native `cargo test` or Vitest with the module-test plugin. C# also provides a managed .NET 10 harness via the separate `SpacetimeDB.Testing` package; see the C# server skill for platform and package requirements. These use the real datastore but do not simulate clients, subscriptions, RLS enforcement, lifecycle events, or timer execution. Test those host behaviors against a running database. ## Inter-Database Communication Reducers can't make network requests, but a reducer can call a reducer in another database on the same server through an **outbox table** (async IDC). The reducer inserts a row, and after its transaction commits, the row is delivered as a reducer call to the target database exactly once, in order with other calls through the same outbox to the same database. The sending reducer doesn't wait, and the two databases don't commit together: the receiving reducer runs later in its own transaction and can fail. An optional `on_result` reducer in the sending database receives the result, so it can undo or record the work. +Deliveries can be pipelined. Receiving calls and `on_result` callbacks each retain stream order, but a later receiving call need not wait for an earlier callback in the sending database. Do not use callbacks as barriers for subsequent receiving calls. + Use it to split an application into databases that scale and deploy independently, such as a lobby that sends players to separate game world databases. Only Rust and TypeScript modules can declare outbox tables. See the language-specific server skills for syntax. ## Identity diff --git a/skills/csharp-server/SKILL.md b/skills/csharp-server/SKILL.md index 3c735f6d8ba..1bca49895de 100644 --- a/skills/csharp-server/SKILL.md +++ b/skills/csharp-server/SKILL.md @@ -17,10 +17,14 @@ metadata: Module unit tests use a sibling .NET 10 test project with an ordinary module `ProjectReference` and the separate `SpacetimeDB.Testing` NuGet package, at exactly -the module's Runtime version. Run with `dotnet test`; no server or Rust compiler +the module's Runtime version, from a release publishing both packages. Native +libraries support Linux x64/ARM64 (glibc 2.35+) and Windows x64, not macOS. +Run with `dotnet test`; no server or Rust compiler is required. Keep Testing out of module dependencies and test sources outside the module directory. Use `using var test = ModuleTestContext.Create(typeof(Module).Assembly)` -and `test.WithReducerTx(TestAuth.Internal(), ctx => Module.Reducer(ctx))`. +and, for the module below, +`test.WithReducerTx(TestAuth.Internal(), ctx => Module.AddRecord(ctx, 1))` +with `using SpacetimeDB.Testing;` in the test project. Callbacks are synchronous; one fixture supports one execution flow, while separate fixtures may run in parallel. The chat-console-cs template includes tests for .NET 10 only. See `/how-to/unit-testing` for setup and release availability. diff --git a/skills/typescript-client/SKILL.md b/skills/typescript-client/SKILL.md index d311d31d766..914adaea413 100644 --- a/skills/typescript-client/SKILL.md +++ b/skills/typescript-client/SKILL.md @@ -17,6 +17,8 @@ Generated bindings convert snake_case names to camelCase, including row fields: The examples below use bundler-style extensionless imports. For NodeNext or direct-TypeScript execution, choose the matching binding import extension and use explicit file imports in your application; see https://spacetimedb.com/docs/clients/typescript#import-extensions. +`withUri` takes the server base URI, not a subscription endpoint. It preserves a path prefix: `wss://example.com/stdb` (or `/stdb/`) uses `/stdb/v1/database//subscribe` and the HTTPS token-exchange endpoint `/stdb/v1/identity/websocket-token`. A reverse proxy must forward both endpoints, stripping its prefix when forwarding to a root-mounted server. + ## React: main.tsx ```typescript diff --git a/skills/typescript-server/SKILL.md b/skills/typescript-server/SKILL.md index 5a39dff12b7..120d6296cd5 100644 --- a/skills/typescript-server/SKILL.md +++ b/skills/typescript-server/SKILL.md @@ -13,6 +13,10 @@ metadata: # SpacetimeDB TypeScript SDK Reference +## Runtime Memory + +V8's module memory limit includes `ArrayBuffer` allocations (and typed-array backing buffers), not just ordinary JavaScript objects. Limit peak buffer allocations and copies. This is separate from the storage engine's resident-memory budget; changing table cache policies does not increase the V8 limit. + ## Module Structure Tables are built with `table()`, bound with `schema()`, and exported as default. Reducers and lifecycle hooks are `export const`: diff --git a/tools/llm-sequential-upgrade/CLAUDE.md b/tools/llm-sequential-upgrade/CLAUDE.md index b83f19f48a9..608cdfa3eda 100644 --- a/tools/llm-sequential-upgrade/CLAUDE.md +++ b/tools/llm-sequential-upgrade/CLAUDE.md @@ -41,6 +41,8 @@ POSIX: `mkdir -p` not `New-Item`, `sleep` not `Start-Sleep`, `2>/dev/null` not ` Do NOT read any files under: - `../llm-oneshot/apps/chat-app/typescript/` (reference implementations) - `../llm-oneshot/apps/chat-app/staging/` +- Published reference apps in the `spacetimedb-llm-oneshot-results` and + `spacetimedb-llm-sequential-upgrade-results` checkouts, wherever they are located - Any other AI-generated app code in this workspace Only read files you created, the backend instructions, and the feature prompts. From 6ead98aa75c3fbc56cce146c0938bc704b90e178 Mon Sep 17 00:00:00 2001 From: clockwork-labs-bot Date: Thu, 26 Nov 2026 09:02:01 -0500 Subject: [PATCH 19/21] docs: reconcile IDC language tabs before master merge --- .../00650-inter-database-communication.md | 43 ++++++++++++++++--- 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md b/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md index b6dc082c697..5fb7b0266eb 100644 --- a/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md +++ b/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md @@ -390,7 +390,12 @@ spacetime sql lobby "SELECT * FROM admit_player_outbox" ### Generated outbox declarations -You can always declare an outbox by manually specifying the table and types. TypeScript and Rust receiver bindings also provide shorthand declarations. In TypeScript, `gw.outbox.admitPlayer()` returns an outbox table with a `msgId` message ID column, a `target` column, and a column for each parameter of the reducer: +You can always declare an outbox by manually specifying the table and types. However, the receiver bindings can also declare an outbox for you, with a message ID column, a target column, and a column for each parameter of the reducer: + + + + +`gw.outbox.admitPlayer()` returns an outbox table with a `msgId` message ID column and a `target` column: ```typescript const spacetimedb = schema({ @@ -404,17 +409,37 @@ ctx.db.admitPlayerOutbox.insert({ msgId: 0n, target: world, name }); Like `table()`, it takes an optional `name`. Without one, the table is named after its key in `schema()`. It can't declare an outbox for a reducer with a parameter named `msgId` or `target`. For that reducer, use `table()` to manually declare an outbox table, and give the message ID and target columns other names. -In Rust, import the receiving module and use `spacetimedb::outbox!`: + + -```rust -use remote_bindings::game_world; +Put `[Outbox]` on an empty `partial struct`, in place of `[Table]`, and pass it the reducer from the bindings. It declares the struct as an outbox table with a `MsgId` message ID column, a `Target` column, and a column for each parameter, named in Pascal case: + +```csharp +[Outbox(typeof(Gw.Reducers.AdmitPlayer), Accessor = "AdmitPlayerOutbox")] +public partial struct AdmitPlayerOutbox { } + +// Inside a reducer: +ctx.Db.AdmitPlayerOutbox.Insert(new AdmitPlayerOutbox { MsgId = 0, Target = world, Name = name }); +``` + +Like `[Table]`, it takes an `Accessor`, and optionally a `Name` and `Public`. It can't declare an outbox for a reducer with a parameter named `msg_id` or `target`. For that reducer, use `[Table]` to manually declare an outbox table, and give the message ID and target columns other names. + + + + +`outbox!(game_world::admit_player)` declares an `admit_player_outbox` table, with an `AdmitPlayerOutbox` row type, a `msg_id` message ID column and a `target` column: +```rust spacetimedb::outbox!(game_world::admit_player); + +// Inside a reducer: +ctx.db.admit_player_outbox().insert(AdmitPlayerOutbox { msg_id: 0, target: world, name }); ``` -For the `admit_player(name: String)` reducer above, this creates `AdmitPlayerOutbox` with `msg_id: u64`, `target: game_world::Identity`, and `name: String`, accessed through `ctx.db.admit_player_outbox()`. Insert `msg_id: 0` to allocate the message ID. Optional `accessor = custom_outbox` and `name = "custom_outbox"` arguments override the accessor and canonical table name. The receiver must be in scope as a module identifier. If its arguments include `msg_id` or `target`, or you need multiple outboxes for the same reducer or extra columns, declare the table manually instead. +Pass `accessor = ...` or `name = "..."` to name the table differently. It can't declare an outbox for a reducer with a parameter named `msg_id` or `target`, or a second outbox for the same reducer. For those, use `#[table]` to manually declare an outbox table, and give the message ID and target columns other names. -Rust receiver bindings now use `mod.rs` as their root. Regenerate older bindings and remove any obsolete `#[path = "remote_bindings/game_world/lib.rs"]` override; the normal `mod remote_bindings;` declaration works with the generated directory structure. + + ## Receiving calls @@ -565,3 +590,9 @@ To change a reducer without failing calls from databases that haven't regenerate - See [Receiver dependencies](../../00300-resources/00100-cli-reference/00300-spacetime-json.md#receiver-dependencies) for every way to configure receiver bindings in `spacetime.json`. - Learn how [transactions](./00100-transactions-atomicity.md) make each reducer's changes, including its outbox rows, all-or-nothing. - Use a [schedule table](../00300-tables/00500-schedule-tables.md) to call a reducer in the same database at a later time. + +### Rust generated-binding details + +For the `admit_player(name: String)` reducer above, this creates `AdmitPlayerOutbox` with `msg_id: u64`, `target: game_world::Identity`, and `name: String`, accessed through `ctx.db.admit_player_outbox()`. Insert `msg_id: 0` to allocate the message ID. Optional `accessor = custom_outbox` and `name = "custom_outbox"` arguments override the accessor and canonical table name. The receiver must be in scope as a module identifier. If its arguments include `msg_id` or `target`, or you need multiple outboxes for the same reducer or extra columns, declare the table manually instead. + +Rust receiver bindings now use `mod.rs` as their root. Regenerate older bindings and remove any obsolete `#[path = "remote_bindings/game_world/lib.rs"]` override; the normal `mod remote_bindings;` declaration works with the generated directory structure. From a694122c2c7a0e6fc5a2d3982bee8bb57267b3dd Mon Sep 17 00:00:00 2001 From: clockwork-labs-bot Date: Thu, 26 Nov 2026 09:11:09 -0500 Subject: [PATCH 20/21] docs: cover C# IDC, unique index accessors and SDK licenses --- README.md | 2 ++ .../plugins/spacetimedb/skills/cli/SKILL.md | 4 +++- .../spacetimedb/skills/concepts/SKILL.md | 4 +++- .../spacetimedb/skills/csharp-server/SKILL.md | 18 ++++++++++++++++-- .../00650-inter-database-communication.md | 14 +++++--------- .../00300-tables/00300-indexes.md | 2 ++ skills/cli/SKILL.md | 4 +++- skills/concepts/SKILL.md | 4 +++- skills/csharp-server/SKILL.md | 18 ++++++++++++++++-- 9 files changed, 53 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index e905a7adf47..79e539112de 100644 --- a/README.md +++ b/README.md @@ -272,6 +272,8 @@ Full documentation is available at **[spacetimedb.com/docs](https://spacetimedb. SpacetimeDB is licensed under the [Business Source License 1.1 (BSL)](LICENSE.txt). It converts to the AGPL v3.0 with a linking exception after a few years. The linking exception means you are **not** required to open-source your own code if you use SpacetimeDB. You only need to contribute back changes to SpacetimeDB itself. +The [Rust client SDK](sdks/rust/LICENSE) and the [TypeScript client SDK and module library](crates/bindings-typescript/LICENSE.txt) are licensed under [Apache 2.0](licenses/apache2.txt), rather than the server's BSL. Check each component's license file for its terms. + **Why did we choose this license?** We chose to license SpacetimeDB under the MariaDB Business Source License for 4 years because we can't compete with AWS while also building our products for them. diff --git a/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md index d63ad63526e..94eeac92eda 100644 --- a/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/cli/SKILL.md @@ -58,10 +58,12 @@ For TypeScript client bindings, `spacetime generate --lang typescript --import-e ### Client and Module Bindings -`spacetime generate --bindings client` (default) generates bindings for clients connecting to a database. `--bindings module` generates receiver bindings used inside a **sending database module** to call reducers in another **receiving database** through asynchronous IDC. Rust and TypeScript module bindings are supported; C#/C++ module bindings are not implemented yet. `unrealcpp` is client-only; `cpp` is accepted only in module mode. +`spacetime generate --bindings client` (default) generates bindings for clients connecting to a database. `--bindings module` generates receiver bindings used inside a **sending database module** to call reducers in another **receiving database** through asynchronous IDC. Rust, TypeScript, and C# module bindings are supported; C++ module bindings are not implemented yet. `unrealcpp` is client-only; `cpp` is accepted only in module mode. In `spacetime.json`, each sending database's non-inherited `dependencies` array requires its own `module-path` and dependency `name` plus receiving-module `module-path` or `database`. A `database` reference resolves another target's local source/build settings in the same config; it does not fetch a running database's schema. A direct receiving module source takes precedence. Dependencies do not themselves publish receiving databases or inherit the sending module's build settings. `generate ` processes both its regular `generate` entries (client bindings by default) and `dependencies` (module bindings automatically); no `--bindings` flag or second `generate` entry is needed for a dependency. For dependencies, module binding language defaults to the sending module's language and Rust/TypeScript output defaults to `/src/remote_bindings`. Explicit config `out-dir` is config-relative. A regular `generate` entry can select `"bindings": "module"`, but does not use dependency language or output defaults. The CLI `--bindings` override is allowed only when a single generation entry is selected. +C# dependency output defaults to `/remote_bindings/`, with namespace `RemoteBindings.`. Set `namespace` on that dependency to override it. Direct `--bindings module --lang csharp` generation without a dependency name defaults to `RemoteBindings`; client bindings still default to `SpacetimeDB.Types`. `--namespace` overrides the C# namespace. In a module-bindings namespace, later segments cannot be `System`, `SpacetimeDB`, or the first segment: for example, `RemoteBindings.System` is rejected. + `dev` generates only root dependencies before building the sending module, and watches their source paths. Child targets are available for source lookup, not recursive dependency generation. `--skip-generate` skips receiver/client generation and receiver-only watching; `--skip-publish` does not. See https://spacetimedb.com/docs/cli-reference/spacetime-json#receiver-dependencies for examples. ### C# Build Modes diff --git a/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md index f5a5741c8c4..d191c9731f4 100644 --- a/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/concepts/SKILL.md @@ -177,7 +177,9 @@ Reducers can't make network requests, but a reducer can call a reducer in anothe Deliveries can be pipelined. Receiving calls and `on_result` callbacks each retain stream order, but a later receiving call need not wait for an earlier callback in the sending database. Do not use callbacks as barriers for subsequent receiving calls. -Use it to split an application into databases that scale and deploy independently, such as a lobby that sends players to separate game world databases. Only Rust and TypeScript modules can declare outbox tables. See the language-specific server skills for syntax. +Outbox rows are insert-only for module code. The host removes them after delivery and the optional result callback; do not update or delete pending rows yourself. + +Use it to split an application into databases that scale and deploy independently, such as a lobby that sends players to separate game world databases. Rust, TypeScript, and C# modules can declare outbox tables. See the language-specific server skills for syntax. ## Identity diff --git a/codex-plugin/plugins/spacetimedb/skills/csharp-server/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/csharp-server/SKILL.md index 1bca49895de..c3d51a28dfc 100644 --- a/codex-plugin/plugins/spacetimedb/skills/csharp-server/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/csharp-server/SKILL.md @@ -143,7 +143,7 @@ The complete set of column attributes: [PrimaryKey] // primary key [AutoInc] // auto-increment (use 0 as placeholder on insert) [Unique] // unique constraint; indexes the column, enables .Find() -[SpacetimeDB.Index.BTree] // btree index (enables .Filter() on this column) +[SpacetimeDB.Index.BTree] // non-unique btree index enables .Filter() [Default(true)] // migration-safe default for a newly appended field ``` @@ -167,6 +167,8 @@ public partial struct Membership { public ulong GroupId; public Identity UserId; Prefer a multi-column index over filtering by one column and looping. +A declared single-column B-tree index on a `[Unique]` or `[PrimaryKey]` column is that column's unique index, not a second non-unique index. Its declared `Accessor` is the only accessor and supports `Find`/`Update`/`Delete`, not `Filter`. For example, declaring `Accessor = "ById"` on the `Id` primary-key column changes calls from `.Id.Find(id)` to `.ById.Find(id)`. Remove the redundant index attribute to retain the column-named accessor. Do not change an unconstrained column's `Filter` calls to `Find`. + ## Reducers ```csharp @@ -212,7 +214,7 @@ public static void ClientConnected(ReducerContext ctx) { ... } public static void ClientDisconnected(ReducerContext ctx) { ... } ``` -Reducer and procedure method names must not start with `On`, `on`, or `__`; the code generator rejects them (STDB0010), so name lifecycle reducers `ClientConnected`, not `OnConnect`. +Ordinary reducer and procedure method names must not start with `On`, `on`, or `__`; the code generator rejects them (STDB0010), so name lifecycle reducers `ClientConnected`, not `OnConnect`. A reducer marked `[OnResult]` may start with `On` or `on`, but not `__`. `ctx.ConnectionId` is `ConnectionId?`, including in connection lifecycle reducers. Check or unwrap it before storing it in a non-nullable column or passing it to an index accessor. @@ -309,6 +311,16 @@ The marker is any accessible type in the dependency assembly. Root code uses `ct In 2.14+, any module can mount its own dependencies, and the same assembly can be mounted more than once with independent tables at each path; 2.13 allows only root mounts, once per assembly. Cross-language composition is unsupported. Named dependencies cannot declare lifecycle reducers, nonempty environments, or RLS filters. Define RLS in the root with canonical qualified table names. Named-submodule routes are ignored; root handlers may delegate to library helpers. Dependencies in `public` can contribute lifecycle reducers (subject to uniqueness), environment declarations, and routes. +## Inter-Database Communication + +Generate C# receiver bindings with `spacetime generate --bindings module --lang csharp`, or use the sending module's `dependencies` in `spacetime.json` (see the CLI skill). For a dependency named `game_world`, the default namespace is `RemoteBindings.GameWorld`; import it as `using Gw = RemoteBindings.GameWorld;`. This is independent-database messaging, not assembly composition. + +For a receiver reducer `admit_player(name: string)`, `[Outbox(typeof(Gw.Reducers.AdmitPlayer), Accessor = "AdmitPlayerOutbox")]` on an empty `public partial struct AdmitPlayerOutbox` generates `MsgId`, `Target` (a `Gw.Identity`), and `Name`. Insert through `ctx.Db.AdmitPlayerOutbox.Insert(...)` inside a reducer, with `MsgId = 0` for automatic allocation. Use the generated receiver identity type, not an unwrapped `SpacetimeDB.Identity`. + +Alternatively, declare `[Table(Accessor = "AdmitPlayerOutbox", Outbox = typeof(Gw.Reducers.AdmitPlayer))]` with a `ulong` `[PrimaryKey, AutoInc]` field, exactly one `[Target]` field of type `Gw.Identity`, and matching parameter fields. Field names map to receiver parameters in snake_case; `[Param("name")]` maps a differently named field to the canonical `name` parameter. Additional fields are local callback metadata. Use the manual form if receiver parameters collide with shorthand's `msg_id` or `target`. Outboxes must be in the root assembly, not a referenced library; they cannot also be event or scheduled tables. + +Apply both `[Reducer]` and `[OnResult(typeof(AdmitPlayerOutbox))]` to a `public static void` method with parameters `(ReducerContext ctx, AdmitPlayerOutbox row, Result result)`. Match errors as `Result.ErrR(var error)`. If a row type has several outboxes, select one with `Table = "AccessorName"` on `[OnResult]`; `[Target]` and `[Param]` also accept `Table`. The callback is private: only the host, database owner, and team collaborators can run it, not ordinary clients. See the concepts skill for delivery/transaction guarantees and `/databases/inter-database-communication` for the complete receiver, sender, and callback example. + ## Environment Variables ```csharp @@ -438,6 +450,8 @@ public enum Status { Online, Away, Offline } public partial struct Point { public float X; public float Y; } ``` +`[SpacetimeDB.Type(Name = "game_world.Point")]` overrides a custom type's canonical schema name without renaming the C# type. The runtime accepts `.` or `::` between scope segments. C# receiver bindings use dependency-scoped type names to keep types from different receivers distinct; preserve their generated `Type(Name = ...)` attributes rather than editing generated files. + Tagged enums (discriminated unions): a `partial record` with empty body and no constructor parameters. Payloads are `[Type] partial struct`s: ```csharp diff --git a/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md b/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md index af38cc9e14c..955b9e146e3 100644 --- a/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md +++ b/docs/docs/00200-core-concepts/00100-databases/00650-inter-database-communication.md @@ -64,7 +64,7 @@ In the `game_world` module, write `admit_player` as an ordinary reducer. It may // game_world/src/index.ts import { schema, table, t, SenderError } from 'spacetimedb/server'; -const MAX_PLAYERS = 2n; +const maxPlayers = 2n; const player = table({ public: true }, { name: t.string().primaryKey() }); @@ -74,7 +74,7 @@ export default spacetimedb; export const admitPlayer = spacetimedb.reducer( { name: t.string() }, (ctx, { name }) => { - if (ctx.db.player.count() >= MAX_PLAYERS) { + if (ctx.db.player.count() >= maxPlayers) { throw new SenderError('The world is full'); } ctx.db.player.insert({ name }); @@ -578,7 +578,9 @@ spacetimedb::outbox!(game_world::admit_player); ctx.db.admit_player_outbox().insert(AdmitPlayerOutbox { msg_id: 0, target: world, name }); ``` -Pass `accessor = ...` or `name = "..."` to name the table differently. It can't declare an outbox for a reducer with a parameter named `msg_id` or `target`, or a second outbox for the same reducer. For those, use `#[table]` to manually declare an outbox table, and give the message ID and target columns other names. +For the `admit_player(name: String)` reducer above, this creates `AdmitPlayerOutbox` with `msg_id: u64`, `target: game_world::Identity`, and `name: String`, accessed through `ctx.db.admit_player_outbox()`. Insert `msg_id: 0` to allocate the message ID. Optional `accessor = custom_outbox` and `name = "custom_outbox"` arguments override the accessor and canonical table name. The receiver must be in scope as a module identifier. If its arguments include `msg_id` or `target`, or you need multiple outboxes for the same reducer or extra columns, declare the table manually instead. + +Rust receiver bindings now use `mod.rs` as their root. Regenerate older bindings and remove any obsolete `#[path = "remote_bindings/game_world/lib.rs"]` override; the normal `mod remote_bindings;` declaration works with the generated directory structure. @@ -812,9 +814,3 @@ To change a reducer without failing calls from databases that haven't regenerate - See [Receiver dependencies](../../00300-resources/00100-cli-reference/00300-spacetime-json.md#receiver-dependencies) for every way to configure receiver bindings in `spacetime.json`. - Learn how [transactions](./00100-transactions-atomicity.md) make each reducer's changes, including its outbox rows, all-or-nothing. - Use a [schedule table](../00300-tables/00500-schedule-tables.md) to call a reducer in the same database at a later time. - -### Rust generated-binding details - -For the `admit_player(name: String)` reducer above, this creates `AdmitPlayerOutbox` with `msg_id: u64`, `target: game_world::Identity`, and `name: String`, accessed through `ctx.db.admit_player_outbox()`. Insert `msg_id: 0` to allocate the message ID. Optional `accessor = custom_outbox` and `name = "custom_outbox"` arguments override the accessor and canonical table name. The receiver must be in scope as a module identifier. If its arguments include `msg_id` or `target`, or you need multiple outboxes for the same reducer or extra columns, declare the table manually instead. - -Rust receiver bindings now use `mod.rs` as their root. Regenerate older bindings and remove any obsolete `#[path = "remote_bindings/game_world/lib.rs"]` override; the normal `mod remote_bindings;` declaration works with the generated directory structure. diff --git a/docs/docs/00200-core-concepts/00300-tables/00300-indexes.md b/docs/docs/00200-core-concepts/00300-tables/00300-indexes.md index d192a722cad..415c3840e6c 100644 --- a/docs/docs/00200-core-concepts/00300-tables/00300-indexes.md +++ b/docs/docs/00200-core-concepts/00300-tables/00300-indexes.md @@ -151,6 +151,8 @@ const user = table( Never use bare `Index` — it conflicts with `System.Index`. Always write `SpacetimeDB.Index.BTree`. For table-level indexes, use `Columns = new[] { nameof(Col) }` or `new[] { "Col1", "Col2" }`, not collection expressions like `[nameof(X)]`. ::: +A single-column `[SpacetimeDB.Index.BTree]` on a `[Unique]` or `[PrimaryKey]` column is now that column's **unique index**, not an additional non-unique index. Only the declared index accessor remains, with `Find`, `Update`, and `Delete`, not `Filter`. For example, if you declare `Accessor = "ById"` for the `Id` primary key below, use `ctx.Db.User.ById.Find(id)`, not `ctx.Db.User.Id.Find(id)` or `ctx.Db.User.ById.Filter(id)`. When updating an existing module, adjust those calls or remove the redundant index declaration to keep the column-named accessor. Indexes on non-unique columns, such as `Name` and `Age` below, still support `Filter`. + ```csharp [SpacetimeDB.Table(Accessor = "User", Public = true)] public partial struct User diff --git a/skills/cli/SKILL.md b/skills/cli/SKILL.md index d63ad63526e..94eeac92eda 100644 --- a/skills/cli/SKILL.md +++ b/skills/cli/SKILL.md @@ -58,10 +58,12 @@ For TypeScript client bindings, `spacetime generate --lang typescript --import-e ### Client and Module Bindings -`spacetime generate --bindings client` (default) generates bindings for clients connecting to a database. `--bindings module` generates receiver bindings used inside a **sending database module** to call reducers in another **receiving database** through asynchronous IDC. Rust and TypeScript module bindings are supported; C#/C++ module bindings are not implemented yet. `unrealcpp` is client-only; `cpp` is accepted only in module mode. +`spacetime generate --bindings client` (default) generates bindings for clients connecting to a database. `--bindings module` generates receiver bindings used inside a **sending database module** to call reducers in another **receiving database** through asynchronous IDC. Rust, TypeScript, and C# module bindings are supported; C++ module bindings are not implemented yet. `unrealcpp` is client-only; `cpp` is accepted only in module mode. In `spacetime.json`, each sending database's non-inherited `dependencies` array requires its own `module-path` and dependency `name` plus receiving-module `module-path` or `database`. A `database` reference resolves another target's local source/build settings in the same config; it does not fetch a running database's schema. A direct receiving module source takes precedence. Dependencies do not themselves publish receiving databases or inherit the sending module's build settings. `generate ` processes both its regular `generate` entries (client bindings by default) and `dependencies` (module bindings automatically); no `--bindings` flag or second `generate` entry is needed for a dependency. For dependencies, module binding language defaults to the sending module's language and Rust/TypeScript output defaults to `/src/remote_bindings`. Explicit config `out-dir` is config-relative. A regular `generate` entry can select `"bindings": "module"`, but does not use dependency language or output defaults. The CLI `--bindings` override is allowed only when a single generation entry is selected. +C# dependency output defaults to `/remote_bindings/`, with namespace `RemoteBindings.`. Set `namespace` on that dependency to override it. Direct `--bindings module --lang csharp` generation without a dependency name defaults to `RemoteBindings`; client bindings still default to `SpacetimeDB.Types`. `--namespace` overrides the C# namespace. In a module-bindings namespace, later segments cannot be `System`, `SpacetimeDB`, or the first segment: for example, `RemoteBindings.System` is rejected. + `dev` generates only root dependencies before building the sending module, and watches their source paths. Child targets are available for source lookup, not recursive dependency generation. `--skip-generate` skips receiver/client generation and receiver-only watching; `--skip-publish` does not. See https://spacetimedb.com/docs/cli-reference/spacetime-json#receiver-dependencies for examples. ### C# Build Modes diff --git a/skills/concepts/SKILL.md b/skills/concepts/SKILL.md index f5a5741c8c4..d191c9731f4 100644 --- a/skills/concepts/SKILL.md +++ b/skills/concepts/SKILL.md @@ -177,7 +177,9 @@ Reducers can't make network requests, but a reducer can call a reducer in anothe Deliveries can be pipelined. Receiving calls and `on_result` callbacks each retain stream order, but a later receiving call need not wait for an earlier callback in the sending database. Do not use callbacks as barriers for subsequent receiving calls. -Use it to split an application into databases that scale and deploy independently, such as a lobby that sends players to separate game world databases. Only Rust and TypeScript modules can declare outbox tables. See the language-specific server skills for syntax. +Outbox rows are insert-only for module code. The host removes them after delivery and the optional result callback; do not update or delete pending rows yourself. + +Use it to split an application into databases that scale and deploy independently, such as a lobby that sends players to separate game world databases. Rust, TypeScript, and C# modules can declare outbox tables. See the language-specific server skills for syntax. ## Identity diff --git a/skills/csharp-server/SKILL.md b/skills/csharp-server/SKILL.md index 1bca49895de..c3d51a28dfc 100644 --- a/skills/csharp-server/SKILL.md +++ b/skills/csharp-server/SKILL.md @@ -143,7 +143,7 @@ The complete set of column attributes: [PrimaryKey] // primary key [AutoInc] // auto-increment (use 0 as placeholder on insert) [Unique] // unique constraint; indexes the column, enables .Find() -[SpacetimeDB.Index.BTree] // btree index (enables .Filter() on this column) +[SpacetimeDB.Index.BTree] // non-unique btree index enables .Filter() [Default(true)] // migration-safe default for a newly appended field ``` @@ -167,6 +167,8 @@ public partial struct Membership { public ulong GroupId; public Identity UserId; Prefer a multi-column index over filtering by one column and looping. +A declared single-column B-tree index on a `[Unique]` or `[PrimaryKey]` column is that column's unique index, not a second non-unique index. Its declared `Accessor` is the only accessor and supports `Find`/`Update`/`Delete`, not `Filter`. For example, declaring `Accessor = "ById"` on the `Id` primary-key column changes calls from `.Id.Find(id)` to `.ById.Find(id)`. Remove the redundant index attribute to retain the column-named accessor. Do not change an unconstrained column's `Filter` calls to `Find`. + ## Reducers ```csharp @@ -212,7 +214,7 @@ public static void ClientConnected(ReducerContext ctx) { ... } public static void ClientDisconnected(ReducerContext ctx) { ... } ``` -Reducer and procedure method names must not start with `On`, `on`, or `__`; the code generator rejects them (STDB0010), so name lifecycle reducers `ClientConnected`, not `OnConnect`. +Ordinary reducer and procedure method names must not start with `On`, `on`, or `__`; the code generator rejects them (STDB0010), so name lifecycle reducers `ClientConnected`, not `OnConnect`. A reducer marked `[OnResult]` may start with `On` or `on`, but not `__`. `ctx.ConnectionId` is `ConnectionId?`, including in connection lifecycle reducers. Check or unwrap it before storing it in a non-nullable column or passing it to an index accessor. @@ -309,6 +311,16 @@ The marker is any accessible type in the dependency assembly. Root code uses `ct In 2.14+, any module can mount its own dependencies, and the same assembly can be mounted more than once with independent tables at each path; 2.13 allows only root mounts, once per assembly. Cross-language composition is unsupported. Named dependencies cannot declare lifecycle reducers, nonempty environments, or RLS filters. Define RLS in the root with canonical qualified table names. Named-submodule routes are ignored; root handlers may delegate to library helpers. Dependencies in `public` can contribute lifecycle reducers (subject to uniqueness), environment declarations, and routes. +## Inter-Database Communication + +Generate C# receiver bindings with `spacetime generate --bindings module --lang csharp`, or use the sending module's `dependencies` in `spacetime.json` (see the CLI skill). For a dependency named `game_world`, the default namespace is `RemoteBindings.GameWorld`; import it as `using Gw = RemoteBindings.GameWorld;`. This is independent-database messaging, not assembly composition. + +For a receiver reducer `admit_player(name: string)`, `[Outbox(typeof(Gw.Reducers.AdmitPlayer), Accessor = "AdmitPlayerOutbox")]` on an empty `public partial struct AdmitPlayerOutbox` generates `MsgId`, `Target` (a `Gw.Identity`), and `Name`. Insert through `ctx.Db.AdmitPlayerOutbox.Insert(...)` inside a reducer, with `MsgId = 0` for automatic allocation. Use the generated receiver identity type, not an unwrapped `SpacetimeDB.Identity`. + +Alternatively, declare `[Table(Accessor = "AdmitPlayerOutbox", Outbox = typeof(Gw.Reducers.AdmitPlayer))]` with a `ulong` `[PrimaryKey, AutoInc]` field, exactly one `[Target]` field of type `Gw.Identity`, and matching parameter fields. Field names map to receiver parameters in snake_case; `[Param("name")]` maps a differently named field to the canonical `name` parameter. Additional fields are local callback metadata. Use the manual form if receiver parameters collide with shorthand's `msg_id` or `target`. Outboxes must be in the root assembly, not a referenced library; they cannot also be event or scheduled tables. + +Apply both `[Reducer]` and `[OnResult(typeof(AdmitPlayerOutbox))]` to a `public static void` method with parameters `(ReducerContext ctx, AdmitPlayerOutbox row, Result result)`. Match errors as `Result.ErrR(var error)`. If a row type has several outboxes, select one with `Table = "AccessorName"` on `[OnResult]`; `[Target]` and `[Param]` also accept `Table`. The callback is private: only the host, database owner, and team collaborators can run it, not ordinary clients. See the concepts skill for delivery/transaction guarantees and `/databases/inter-database-communication` for the complete receiver, sender, and callback example. + ## Environment Variables ```csharp @@ -438,6 +450,8 @@ public enum Status { Online, Away, Offline } public partial struct Point { public float X; public float Y; } ``` +`[SpacetimeDB.Type(Name = "game_world.Point")]` overrides a custom type's canonical schema name without renaming the C# type. The runtime accepts `.` or `::` between scope segments. C# receiver bindings use dependency-scoped type names to keep types from different receivers distinct; preserve their generated `Type(Name = ...)` attributes rather than editing generated files. + Tagged enums (discriminated unions): a `partial record` with empty body and no constructor parameters. Payloads are `[Type] partial struct`s: ```csharp From cb1d55693d528b190d1658247e15f0c19434a806 Mon Sep 17 00:00:00 2001 From: clockwork-labs-bot Date: Fri, 27 Nov 2026 09:04:38 -0500 Subject: [PATCH 21/21] docs: explain TypeScript submodule view accessor names --- .../skills/typescript-server/SKILL.md | 2 ++ .../00100-databases/00600-modules.md | 21 +++++++++++++++++++ skills/typescript-server/SKILL.md | 2 ++ 3 files changed, 25 insertions(+) diff --git a/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md b/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md index 120d6296cd5..18f2987af7d 100644 --- a/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md +++ b/codex-plugin/plugins/spacetimedb/skills/typescript-server/SKILL.md @@ -283,6 +283,8 @@ export default spacetimedb; `myAuth` is the accessor (`ctx.db.myAuth.`); `auth_data` is the canonical namespace used in SQL and wire names. Without an explicit `name`, the root's case policy derives it (`myAuth` → `my_auth` by default). Pin `name` when renaming an accessor: changing the canonical namespace drops its tables and their data. The library keeps its own flat `ctx.db` accessors. To call a library function directly, pass `ctx.as.myAuth`; inside `withTx`, use `tx.as.myAuth`. Nested TypeScript submodules are supported. Lifecycle reducers and nonempty environment declarations belong in the root. Submodule routers are ignored; register delegated handlers on the root router. Composition is not cross-language. +Inside a submodule view, `ctx.from` also uses the library's local schema keys. For `schema({ sessions })` where the table declares `name: 'auth_sessions'`, return `ctx.from.sessions`, not `ctx.from.auth_sessions` or a consumer namespace prefix. Mount qualification is automatic, including explicitly named tables. Raw SQL uses the full canonical path; never mix an accessor namespace with a canonical table name. See the [submodule view example](https://spacetimedb.com/docs/modules#accessor-and-canonical-namespace-names). + Official reusable libraries include `@spacetimedb/cron`, `@spacetimedb/retry`, `@spacetimedb/rate-limit`, and `@spacetimedb/crypto`. Their registration shapes differ: `@spacetimedb/rate-limit/submodule` is mountable, cron/retry expose factories, and crypto exports helpers. Consult the chosen package's README/exports rather than assuming every package root is a mountable module. Additional mountable packages include `@spacetimedb/auth/submodule` (application-managed sign-in and sessions, distinct from hosted SpacetimeAuth), `@spacetimedb/agents/submodule` (conversations/model calls), and `@spacetimedb/files/submodule` (database-backed files). Auth and Agents require root initialization via `install(ctx.as.auth)` / `install(ctx.as.agents)`. Auth HTTP handlers must be delegated from the root router; configure its signing key first. Agents hosts must authenticate callers, derive owners from trusted state, and enforce quotas before paid model calls. Files helpers accept `ctx.as.files` from reducers or `tx.as.files` inside `withTx`. These libraries require SDK/CLI/server 2.12+. Follow the [package integration guides](https://spacetimedb.com/docs/modules#reusable-typescript-packages) for exact exports and initialization rather than assuming all packages share an `install` API. diff --git a/docs/docs/00200-core-concepts/00100-databases/00600-modules.md b/docs/docs/00200-core-concepts/00100-databases/00600-modules.md index 38cc67ed175..d298dd2291a 100644 --- a/docs/docs/00200-core-concepts/00100-databases/00600-modules.md +++ b/docs/docs/00200-core-concepts/00100-databases/00600-modules.md @@ -170,6 +170,27 @@ const spacetimedb = schema({ }); ``` +Inside a TypeScript submodule view, `ctx.from` uses the library's local schema keys, just like `ctx.db`, even when a table has an explicit canonical `name`. For example, the library can export: + +```typescript +import { schema, table, t } from 'spacetimedb/server'; + +const sessions = table( + { name: 'auth_sessions', public: true }, + { id: t.u64().primaryKey().autoInc() }, +); +const authSchema = schema({ sessions }); +export default authSchema; + +export const allSessions = authSchema.anonymousView( + { public: true }, + t.array(sessions.rowType), + ctx => ctx.from.sessions, +); +``` + +Mount the full library namespace under `myAuth` as above. The view still uses `ctx.from.sessions`, not `ctx.from.auth_sessions` or a consumer namespace prefix. The query builder qualifies the table for the mount automatically. When writing raw SQL, use the complete canonical path instead; do not combine an accessor namespace with a canonical table name. + :::warning Changing a canonical namespace re-creates its tables The canonical namespace is part of every table's identity. Publishing a module whose namespace canonicalizes differently than before, for example after renaming the key from `myauth` to `myAuth` without a `name`, is a migration that removes the tables under the old namespace and creates empty ones under the new namespace. To rename the key without touching the tables, pin the canonical name with `name`: changing only the key while keeping the same `name` only updates the accessor aliases. ::: diff --git a/skills/typescript-server/SKILL.md b/skills/typescript-server/SKILL.md index 120d6296cd5..18f2987af7d 100644 --- a/skills/typescript-server/SKILL.md +++ b/skills/typescript-server/SKILL.md @@ -283,6 +283,8 @@ export default spacetimedb; `myAuth` is the accessor (`ctx.db.myAuth.
`); `auth_data` is the canonical namespace used in SQL and wire names. Without an explicit `name`, the root's case policy derives it (`myAuth` → `my_auth` by default). Pin `name` when renaming an accessor: changing the canonical namespace drops its tables and their data. The library keeps its own flat `ctx.db` accessors. To call a library function directly, pass `ctx.as.myAuth`; inside `withTx`, use `tx.as.myAuth`. Nested TypeScript submodules are supported. Lifecycle reducers and nonempty environment declarations belong in the root. Submodule routers are ignored; register delegated handlers on the root router. Composition is not cross-language. +Inside a submodule view, `ctx.from` also uses the library's local schema keys. For `schema({ sessions })` where the table declares `name: 'auth_sessions'`, return `ctx.from.sessions`, not `ctx.from.auth_sessions` or a consumer namespace prefix. Mount qualification is automatic, including explicitly named tables. Raw SQL uses the full canonical path; never mix an accessor namespace with a canonical table name. See the [submodule view example](https://spacetimedb.com/docs/modules#accessor-and-canonical-namespace-names). + Official reusable libraries include `@spacetimedb/cron`, `@spacetimedb/retry`, `@spacetimedb/rate-limit`, and `@spacetimedb/crypto`. Their registration shapes differ: `@spacetimedb/rate-limit/submodule` is mountable, cron/retry expose factories, and crypto exports helpers. Consult the chosen package's README/exports rather than assuming every package root is a mountable module. Additional mountable packages include `@spacetimedb/auth/submodule` (application-managed sign-in and sessions, distinct from hosted SpacetimeAuth), `@spacetimedb/agents/submodule` (conversations/model calls), and `@spacetimedb/files/submodule` (database-backed files). Auth and Agents require root initialization via `install(ctx.as.auth)` / `install(ctx.as.agents)`. Auth HTTP handlers must be delegated from the root router; configure its signing key first. Agents hosts must authenticate callers, derive owners from trusted state, and enforce quotas before paid model calls. Files helpers accept `ctx.as.files` from reducers or `tx.as.files` inside `withTx`. These libraries require SDK/CLI/server 2.12+. Follow the [package integration guides](https://spacetimedb.com/docs/modules#reusable-typescript-packages) for exact exports and initialization rather than assuming all packages share an `install` API.