Skip to content

fix(storage): coordinate routed scope initialization and invalidation - #331

Merged
loveRhythm1990 merged 6 commits into
matrixorigin:mainfrom
loveRhythm1990:fix/coalesce-user-initialization
Oct 19, 2026
Merged

loveRhythm1990 merged 6 commits into
matrixorigin:mainfrom
loveRhythm1990:fix/coalesce-user-initialization

Conversation

@loveRhythm1990

@loveRhythm1990 loveRhythm1990 commented Oct 17, 2026 •

Copy link
Copy Markdown
Collaborator

What type of PR is this?

  • fix (bug fix)

Which issue(s) this PR fixes

Fixes #330.

What this PR does / why we need it

Concurrent cold requests for one routed user or group can initialize independently and return different stores. Cache invalidation can finish before an initializer publishes, leaving its later cache entries intact. User IDs that match the old group:<id> cache namespace can also return an unrelated group's store.

Use a generic process-local keyed gate with typed ScopeKey::User / ScopeKey::Group identities shared by cold user database-mapping lookups, user/group store initialization, registration, and invalidation. Store/schema caches use the same typed identity, so user input cannot collide with a group key. The database-mapping cache now contains only users: remove the unused group mapping insert and its matching invalidation.

Ready cache hits continue to bypass the gate. Cold callers recheck after acquiring it, and hold it through cache publication. Same-key callers reuse the published store; different keys remain independently eligible under the existing global initialization budget. Group dispatch through scope_store() is included. The weak registry reclaims inactive gates, including cancellation paths, and pointer-checked cleanup cannot remove a replacement gate. No registry mutex is held across an await; Moka async initializers are not reinstated.

Bounded operations and API change

One shared operation helper bounds the complete cold path, including gate/semaphore waits, database lookup, provisioning, and migration. It does not spawn detached work: expiry drops the work future and releases the gate. SQL/DDL already submitted to the database is not rolled back by dropping a future.

  • MEMORIA_ROUTER_INIT_TIMEOUT_SECS: default 120 seconds for cold mapping lookup, user/group initialization, and user database registration.
  • MEMORIA_ROUTER_INVALIDATION_TIMEOUT_SECS: default 15 seconds for invalidation. Both settings are clamped to 1–3600 seconds and documented in the existing architecture guide.
  • invalidate_user(), invalidate_group(), and invalidate_scope() now return Result<(), MemoriaError>. A timeout is an explicit error, not a successful invalidation. A timed-out waiter does not clear caches or bypass the active initializer. Migration propagates the error; in-repository test callers check it.

These deadlines prevent unbounded gate waits; invalidation may require a retry after a longer-running initializer finishes or reaches its own deadline.

Registration and cache coherence

register_user_db() now takes the same user gate as cold initialization and its compensating registry DELETE. A successful registration therefore follows any earlier failed initialization cleanup instead of being silently deleted by it. This also orders registration with invalidation and cold mapping-cache publication.

While holding that gate, registration clears the user's mapping, schema-readiness, and store caches before its first SQL write. A successful retarget refreshes all three on subsequent access; an interrupted or timed-out write cannot leave the old caches intact when the database outcome is uncertain. Cache removal is shared with invalidation through a synchronous helper, avoiding recursive gate acquisition. Previously returned store handles are not revoked.

Recovery and diagnostics

The scope gate also covers the global initialization-permit wait, so remove redundant schema-readiness rechecks after that wait in both user and group initialization.

When compensating registry cleanup fails after a migration error, emit a warning containing only a bounded error category. Preserve the original initialization error. A retained active registry mapping does not bypass schema migration on the next cold access.

A MySQL-protocol fault proxy forwards real DDL, follows prepared statements through their actual EXECUTE acknowledgement, then withholds the backend's OK packet until the router's own deadline expires. The regression covers user/group fresh CREATE and compatibility ALTER paths. It verifies a committed schema prefix, a still-missing later step, no current schema marker/store publication before success, and same-router recovery on retry. A separate scenario in the same regression rejects both initialization and its compensating DELETE, verifies the warning is redacted, and proves retained registration still migrates on retry. Two added registration scenarios pause a real failed initializer before its compensating DELETE to check registration ordering and surviving registry state, and retarget a fully warmed user to an empty replacement database to verify mapping/store/schema cache refresh. Packet framing is shared with the existing schema-metadata visibility proxy. The proxy now tracks per-connection PREPARE_OK statement IDs, resolves cached EXECUTEs back to SQL, and removes associations on statement close. Both rejection and DDL-response pauses are applied to execution rather than preparation.

Validation

Rebased onto upstream main c62bf68 for this follow-up.

  • Storage unit tests: 65 passed, 1 existing ignored, including the registration entry point's gate-wait deadline. Existing operation timeout, cancellation, gate reclamation, typed cache identity, and invalidation tests remain.
  • Workspace Clippy with warnings denied, Clippy for all four affected integration targets, API E2E target compilation, changed-file formatting, and git diff --check passed. The API E2E suite was compiled, not executed.
  • The registration follow-up adds two database regression scenarios inside router_initialization_recovery (seven database scenarios in one current-thread test, plus a separate database-free protocol regression). It also adjusts the existing mapping-invalidation fixture to mutate the registry directly, so registration's own invalidation does not mask the behavior being tested.
  • Database execution limitation for this follow-up: the local disposable database is unavailable and the local container runtime API is unresponsive. The new database scenarios compile but have not been executed locally; the normal PR database CI must pass before merge. No shared QA/production environment was changed to work around this.
  • Before this follow-up, the preceding PR revision passed 18 database integration tests across router_multi_db (11), schema_meta_visibility (1), call_log_schema_upgrade (5), and router_initialization_recovery (1). Those earlier results do not validate the newly added registration scenarios.
  • The original regressions were checked against their unfixed baselines in earlier revisions: same-user/group coalescing, lost invalidation, and user/group namespace collisions. No red-baseline execution is claimed for this registration follow-up.
  • Follow-up review coverage: all four registration-change Rust files reviewed, none skipped (100%); the changed configuration documentation was reviewed separately. Both changed Rust files in the CI repair were reviewed, none skipped (100%).
  • CI follow-up: the c44a575 run passed Unit Tests and Clippy, then failed the DB test's required cleanup-fault counter (0 instead of 1). A prior scenario had cached the DELETE; the proxy only matched SQL at PREPARE/QUERY, so cached EXECUTE bypassed injection. The new loopback protocol regression reproduces this on the old proxy and passes with the fix. It also verifies one-shot rejection, successful retry, and retirement on CLOSE. Focused Clippy and formatting checks passed. Full database CI is pending for this repair; no assertion was removed or weakened.

Scope

Coordination is local to a router family/process, not distributed across replicas. Invalidation does not revoke store handles already returned or serialize the full database reset/migration operation. Cancellation/deadlines do not undo database work already executed; later retries use existing migration/recovery behavior. The DDL fault test covers a statement committed by the backend but not yet acknowledged to the client; it does not assert rollback of server-side work on cancellation. Prefix-based personal/group scope dispatch remains separate work tracked in #334. MatrixOne cross-CN freshness configuration remains separate work tracked in #329. No deployment or environment changes are included.

@loveRhythm1990 loveRhythm1990 changed the title fix(storage): coalesce concurrent routed user initialization fix(storage): coordinate routed scope initialization and invalidation Oct 17, 2026
@loveRhythm1990

Copy link
Copy Markdown
Collaborator Author

Code Review (automated, round 2)

Re-reviewed after the latest changes (new keyed_gates.rs Weak-registry/pointer-identity cleanup replacing the earlier per-user-only lock). The core gate mechanism held up under close inspection this round, including the replacement-race and cancellation tests.

Findings:

1. crates/memoria-storage/src/router.rs:461 — invalidate_user/invalidate_group/invalidate_scope now block indefinitely on the same per-key tokio::Mutex a cold initializer holds, with no timeout — this removes the previous lock-free fast-invalidation path. If a cold user_store()/group_store() call hangs (stuck DB connection, a wedged migrate_user(), an unbounded retry) while holding the gate for that key, an operator calling invalidate_user(user_id) to force-clear the broken cached entry now waits forever on gate.mutex.lock().await instead of clearing the cache immediately — no way to recover a user/group whose init is stuck, short of restarting the process.

2. crates/memoria-storage/src/router.rs:39 — cache_gates, user_schema_cache, and user_store_cache share one key space between raw user_id (user path) and "group:{group_id}" (group path), with no validation that a user_id can never collide with that namespace. If any upstream caller ever produces/accepts a user_id literally equal to "group:<x>", that user's init gate, schema-cache and store-cache entries collide with an unrelated group's — invalidating or coalescing one scope silently invalidates/coalesces the other.

3. crates/memoria-storage/src/router.rs:314 — the check-cache / acquire-gate / recheck-cache double-checked-locking sequence is hand-duplicated three times (user_db_name ~314, user_store ~353, group_store ~592-600) instead of one shared helper. A future fix to this pattern (adding a metric, fixing an ordering subtlety, adding a timeout) is easy to apply to two of the three call sites and miss the third, silently reintroducing the exact coalescing/invalidation race this PR was written to close.

4. crates/memoria-storage/src/router.rs:637 — group_store() writes user_db_cache.insert(group_id.to_string(), db_name) under the bare group_id, but nothing ever reads user_db_cache with a bare group_id key (group_db_name() always re-queries mem_groups directly; the only readers of user_db_cache key by user_id for users). Every cold/invalidated group_store() call performs a dead-weight Moka insert, and invalidate_group()'s matching user_db_cache.invalidate(group_id) call is equally inert — easy for a future reader to mistake for a real, consulted cache path.


#1 is the one I'd treat as a real operational regression — losing the ability to force-invalidate a stuck key is a meaningful step back from the previous lock-free invalidation path. #2–#4 are lower-severity (a latent key-collision risk, duplication risk, and dead code) but worth cleaning up.

🤖 Generated with Claude Code

@loveRhythm1990

Copy link
Copy Markdown
Collaborator Author

Code Review (automated, round 3)

Re-verified the actual diff (git diff github/main...pr-331, base 23d43e4 / head 728dc71, 8 files, +1041/-131 — matching the PR's own stats). No project-level conventions doc governs this code, so the Conventions angle returned nothing.

Findings:

1. crates/memoria-storage/src/keyed_gates.rs:33 — KeyedGates::run wraps both the per-key gate wait and the entire cold-init work (schema bootstrap / compat-migration DDL) in one tokio::time::timeout, so a slow migration is cancelled mid-flight by dropping the future — only a clean pre-existing failure is covered by tests, not an actually-interrupted DDL statement. If MEMORIA_ROUTER_INIT_TIMEOUT_SECS (default 120s) elapses while migrate_user() is mid-way through a multi-statement ALTER TABLE/ADD INDEX sequence (or queued behind the global user_init_semaphore, default 6-way budget), the timeout drops the future, the DDL already sent is not rolled back (DDL auto-commits in MySQL), and the next retry's migrate_user() runs against whatever half-applied schema state was left. router_retries_initialization_after_a_schema_failure does not reproduce this — it simulates a clean pre-existing failure, not a cut-off DDL.

2. crates/memoria-storage/src/router.rs:480 — the new typed ScopeKey was meant to make the scope_id.starts_with("grp_") heuristic unnecessary, but invalidate_scope() and the pre-existing scope_store() (line 704) both still use it, and it's only rejected at one auth entry point (auth.rs:70, the owner-scoped master-key path) — not at the API-key-resolved user_id path. A user_id resolved via API-key auth that happens to start with grp_ is misrouted into the group branch instead of the user branch; invalidating or re-reading that user's store silently touches the wrong ScopeKey — the same class of cross-scope bug this PR exists to fix, just moved to the dispatch layer.

3. crates/memoria-storage/src/router.rs:423 — after a failed cold migrate_user() for a newly-provisioned user, the compensating DELETE FROM mem_user_registry is fired with let _ = ..., discarding its Result. If that rollback delete itself hits a transient error, the registry row stays active, pointing at a database whose schema never finished migrating. The next cold call for that user sees an existing row (needs_init = false) and skips re-provisioning, serving a store against an incomplete schema with no log or metric indicating the inconsistency.

4. crates/memoria-storage/src/router.rs:97 — user_db_cache was left as Cache<String, String> while user_schema_cache/user_store_cache were migrated to the typed ScopeKey, so the PR's stated invariant ("user input cannot collide with a group key") holds for only two of the three router caches. Currently benign since group_store/group_db_name never read or write user_db_cache today, but any future optimization that starts resolving a group's db name through this cache would silently reintroduce the exact string-collision bug (group:<id> vs. a user literally named group:<id>) this PR was written to eliminate — with no test guarding against it, since this cache was excluded from the typed-key migration.

5. crates/memoria-storage/src/router.rs:336 — user_db_name() now routes through the same per-user cache_gates key and init_timeout (120s default) as the full user_store() cold-initialization path, so a cheap mapping-only lookup can block behind an unrelated heavy schema migration for the same user. A concurrent lightweight caller (e.g. an admin/status endpoint that only needs the routed db name) can stall on the same gate and return a "database mapping lookup timed out" error purely from contention, even though the mapping was already resolvable independently of the migration.

Lower-severity / cleanup:

6. router.rs:407 (and mirrored in group_store() ~663-672) — the user_schema_cache.get(&cache_key).is_none() recheck after acquiring user_init_semaphore is now dead code: the per-key cache_gates gate already excludes every other writer of that cache entry (including invalidate_user/invalidate_group) for the whole duration of the gated work. Independently flagged by three separate review passes as a maintenance hazard — a future contributor may assume it still guards a real race.

7. router.rs:519 — cache_operation() maps every gate/semaphore timeout to the generic MemoriaError::Database variant with the category embedded only in a free-text message, rather than a dedicated Timeout-style variant. Both production callers and this PR's own tests can only detect a coordination timeout by substring-matching the message — any future rewording silently breaks that detection.

8. router.rs:488 — invalidate_cached_store() special-cases ScopeKey::User inline instead of exposing that behavior as a method on ScopeKey itself; future scope-specific caches will need the same hand-remembered branching.

9. router.rs:49 — configured_router_timeout re-implements the "parse env var → default → clamp" pattern that already exists independently in pool_config.rs and store.rs's connection-limit helpers — now three near-identical copies.


#1–#3 are the ones I'd treat as real correctness/operational risk before merge (interrupted-DDL state, dispatch-layer scope collision, silent registry corruption on rollback failure). #4–#5 are worth a decision. #6–#9 are lower-priority cleanups.

🤖 Generated with Claude Code

@loveRhythm1990
loveRhythm1990 force-pushed the fix/coalesce-user-initialization branch from 9e179f7 to c44a575 Compare October 18, 2026 13:04
@loveRhythm1990
loveRhythm1990 merged commit 4b9496f into matrixorigin:main Oct 19, 2026
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.

Bug: routed scope initialization races with concurrent access and cache invalidation

1 participant