Skip to content

Split proSync store into per-database sync/auth status (ADR-053) - #2322

Merged
mstomar125 merged 3 commits into
mainfrom
issue-1535-per-database-cloud-sync
Sep 1, 2026
Merged

mstomar125 merged 3 commits into
mainfrom
issue-1535-per-database-cloud-sync

Conversation

@mstomar125

Copy link
Copy Markdown
Contributor

Summary

Addresses part of #1535 (ADR-053 §4-6, core-side surface). The tenant-binding/single-active-session backend already landed substantially in the private nodespace-sync repo (sync#350, #352, #354, #356, #358, all Done) and the build-time NODESPACED_PRO_SCHEMA/NODESPACED_PRO_COLLECTION env injection is already gone from daemon_setup.rs. The one concretely-scoped, verifiable-in-this-environment gap left was the frontend: pro-sync.svelte.ts was still a single GLOBAL store, so switching the active database could show stale or leaked-over sync/auth status from whichever database last synced.

  • Split ProSyncStore (packages/desktop-app/src/lib/stores/pro-sync.svelte.ts) so state/detail/userEmail/authRequiredEpisode/dismissedReloginEpisode are keyed by database id, resolved against the ACTIVE database on every read. tier/isPro/signedInEpisode/consentPromptOpen/consentDeclinedEpisode stay global (Pro-ness is a daemon-binary capability; per-database consent persistence already exists via first-pro-consent-slot.svelte's localStorage keying).
  • Added a synthetic 'local-only' SyncState, forced for the active database when it has no boundTenantSchema — short-circuits any cached entry, but only once the registry has actually resolved the active database (fails safe to the cached entry otherwise, so this doesn't fire during boot/tests before databaseStore.load() runs).
  • Backend: SyncStatusEvent carries no database_id (the daemon's single-active-session design). ProClient now tracks the database id last passed to ActivateDatabase and attributes every forwarded sync:status / pro:tier-detected / pro_current_status payload to it. database.svelte.ts now also calls pro_activate_database from load()'s first resolution (not just switchTo()), so this tracking is seeded from the very first launch.
  • Fixed a real bug this surfaced: resolveProSyncVariant()'s authed check falls back to proSync.userEmail !== '', which — while global — could leak a signed-in email from one database into the variant resolution of a totally different, never-signed-in database.
  • Bonus: added toJSON() to ProSyncStore — every $state/$derived class field compiles to a prototype accessor (verified via svelte.compileModule), invisible to plain JSON.stringify, so debug-channel.ts's captureStoreDump() was already silently dumping proSync as {} before this change (pre-existing, unrelated to this refactor, but cheap to fix while touching this file).

No consumer components changed — the pill, re-login slot, and consent slot all read the same public getter names as before, now resolving against the active database automatically.

Acceptance criteria (from #1535)

  • Sync pill reflects the active database only; per-database status is correct after switches — closed by this PR
  • Build-time tenant env injection is gone; a community build is unaffected — already true before this PR (verified, zero references repo-wide)
  • A synced and a local-only database coexist; switching starts/stops sync with catch-up on activation (integration test against a test tenant) — mechanism lands server-side (sync#350, Done); needs a real Supabase test tenant to integration-test end to end. Not attempted here — no live infra in this environment.
  • Deactivation drains pending pushes before stopping — server-side (sync#350). Same live-infra gap.
  • Binding a second local database to an already-bound tenant is rejected — server-side (sync#354, Done). Not independently re-verified here.
  • Sign-in/sign-out operate per database; keychain holds independent entries per tenant — pro_initiate_oauth/pro_signout are generic pass-throughs to whatever the daemon's single active session currently is, which is already correct by construction given the daemon's per-database identity model (sync#350/352/356). The keychain layout itself is server-side and not independently verified here.
  • Add-synced-database-from-cloud flow works on a fresh profile (catch-up + local re-embed) — genuinely not wired on the core side yet, not just blocked on infra: I grepped the vendored proto/nodespace_pro.proto and commands/pro_sync.rs and there is no BindTenant/tenant-listing RPC surfaced in core at all, even though the private repo has landed BindTenant (sync#352/356). Closing this needs vendoring an updated proto, new Tauri commands, and a new "add synced database" frontend flow — a separate, larger piece of work I did not attempt.

Test plan

  • bun run test:all — 227 frontend test files / 4817 tests, 3 script/skill test files / 40 tests, and every Rust suite, all green (0 failures)
  • bun run quality:fix — clean (0 eslint errors/warnings, svelte-check clean, cargo fmt/clippy --fix clean)
  • New regression tests in pro-sync.test.ts: switching between a synced and a local-only database (no state leak either direction), forced local-only only once the registry resolves, per-database authRequiredEpisode/dismissedReloginEpisode isolation, userEmail not leaking into a different database's variant resolution, event-with-no-database_id attributing to whichever database is active at receipt, and toJSON() actually surfacing the reactive fields
  • New Rust unit tests in pro_client.rs for the database_id normalization (empty → None)

Not independently tested (needs live infra, out of scope): the actual daemon-side activate/deactivate/catch-up/bind behavior — that's covered by the already-Done sync#350/352/354/356/358 test suites in the private repo, not re-verified here.

pro-sync.svelte.ts held one global state/detail/userEmail/authRequiredEpisode
tuple fed by the sync:status stream, so switching the active database showed
stale or leaked-over status from whichever database last synced — including a
signed-in database's userEmail leaking into resolveProSyncVariant's `authed`
check for a totally different, never-signed-in database.

Backend: SyncStatusEvent carries no database_id (single-active-session design
in the private nodespace-sync daemon), so ProClient now tracks the database id
last passed to ActivateDatabase and attributes every forwarded sync:status /
pro:tier-detected / pro_current_status payload to it. database.svelte.ts now
also calls pro_activate_database from load()'s first resolution, not just
switchTo(), so this tracking is seeded from the very first launch rather than
only after a manual switch.

Frontend: ProSyncStore now keys state/detail/userEmail/authRequiredEpisode/
dismissedReloginEpisode by database id (falling back to whichever database is
active at receipt time for the proto's empty-database_id convention), and every
consumer-facing getter resolves against the ACTIVE database — so the pill,
re-login slot, and consent slot need no changes. A new synthetic 'local-only'
SyncState is forced for a database with no boundTenantSchema, short-circuiting
any cached entry, but only once the registry has actually resolved the active
database (fails safe to the entry otherwise). tier/isPro/signedInEpisode/
consentPromptOpen/consentDeclinedEpisode stay global — Pro-ness is a daemon
capability, and per-database consent persistence already exists via
first-pro-consent-slot.svelte's localStorage keying.

Added a toJSON() to ProSyncStore: every $state/$derived class field compiles
to a prototype accessor, invisible to JSON.stringify, so the debug-channel
store dump was already silently serializing proSync to {} before this change.

Regression tests cover switching between a synced and a local-only database,
per-database episode isolation, and the userEmail-leak fix.

Remaining acceptance criteria for #1535 need live infra (a real Supabase test
tenant, real OAuth) this environment doesn't have — see the PR description and
issue comment for the full breakdown.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
mstomar125 and others added 2 commits September 1, 2026 11:46
… an unsequenced activate race found in adversarial review

Three real bugs surfaced by /code-review on PR #2322:

1. pro_current_status read active_database_id and last_status via two
   separate lock acquisitions, so a database switch racing between them
   could attribute a PREVIOUS database's stale cached status to the NEWLY
   active one. Added ProClient::status_snapshot() to read both fields
   together under one lock, and made set_active_database_id clear
   last_status on a genuine re-target (Some -> Some(different)) while
   leaving it alone on the first-ever activation (None -> Some, e.g.
   load()'s first resolution) so #1647 reload re-hydration still works for
   the common steady-state case.

2. ProSyncStore's 'local-only' override only forced the `state` getter, not
   userEmail/detail/authRequiredEpisode/dismissedReloginEpisode — a stray
   cached entry under an unbound database's id could still leak a signed-in
   email into the pill's `signedIn` check even while `state` correctly read
   'local-only'. Introduced a frozen LOCAL_ONLY_ENTRY and a single
   `activeEntry` resolver every read-only getter now funnels through, so the
   override is complete rather than per-field.

3. database.svelte.ts's activateProSync() fired pro_activate_database as an
   unsequenced fire-and-forget invoke, so a rapid A -> B -> A switch could
   have its underlying RPCs resolve (and land on the Rust side) out of send
   order. Added a serialized promise chain so a later call's invoke is never
   even dispatched until the previous one has settled.

Added Rust unit tests for the retarget/status-clearing behavior and
frontend regression tests for the complete local-only override and the
serialized-dispatch guarantee. bun run test:all and bun run quality:fix
both clean.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…e_id-attribution default

Adds ProClient::attributed_database_id() so every sync-status emit site
shares one place for the active_database_id().unwrap_or_default()
convention instead of repeating it at each call site.

Fixes a real bug: ProSyncStore.setUserEmail bumped the global
signedInEpisode on any database's empty->non-empty sign-in transition,
even when that database was backgrounded. first-pro-consent-slot.svelte
compares signedInEpisode against consentDeclinedEpisode (both global) to
decide whether to auto-open the first-Pro consent modal, so a background
database's sign-in could re-arm an already-dismissed consent modal for
whatever database happens to be active — leaking one database's sign-in
into another's UI, the exact class of bug this per-database store exists
to prevent. Gated the bump on key === this.activeKey, matching the guard
setState already has on its own global side effect.

Added regression tests for both the backgrounded-sign-in-does-not-leak
case and the active-database-sign-in-still-bumps case. bun run test:all
clean.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@mstomar125
mstomar125 merged commit 95125ac into main Sep 1, 2026
@mstomar125
mstomar125 deleted the issue-1535-per-database-cloud-sync branch September 1, 2026 10:12
@mstomar125

Copy link
Copy Markdown
Contributor Author

Independent adversarial re-review pass (per this repo's core-PR policy) on top of the two rounds already documented in the commit history. (Posted as a comment, not a formal review — GitHub blocks self-approval on your own PR at the API level.)

Checked in detail:

  • pro-sync.svelte.ts's per-database keying (byDatabase, entryFor, patch, targetKey) — the active-database resolution is consistent across all read/write paths, activeIsUnbound correctly falls through to the cached entry rather than defaulting to a misleading 'local-only' before the registry resolves, and the round-2 signedInEpisode gating (key === this.activeKey) closes the cross-database leak correctly.
  • pro_client.rs's active_database_id/set_active_database_id — only recorded on a successful ActivateDatabase (the ? short-circuits before the tracking write on failure), correctly normalizes empty string to None.
  • pro_sync.rs/lib.rs attribution call sites — all three sync:status emit points (subscribe-error, stream-item, stream-ended) and the boot-time pro:tier-detected snapshot now attribute consistently.
  • database.svelte.ts's activateProSync extraction — correctly fire-and-forget/best-effort at both call sites (load()'s first resolution and switchTo()), matching the existing pinWindowDatabase contract.

No further defects found. The two accepted-limitation notes in pro_client.rs's doc comments (narrow local-tracking race, failed-activation attribution staying on the old target) are real but low-blast-radius and self-correcting on the next genuine event — agree with leaving them documented rather than adding complexity.

The PR body's acceptance-criteria checklist is accurate: what's closed here is closed, what's blocked on live infra or unbuilt server-side RPCs is honestly marked as such. Merged.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant