Repository navigation
fix(storage): coordinate routed scope initialization and invalidation - #331
loveRhythm1990 merged 6 commits into
Conversation
Code Review (automated, round 2)Re-reviewed after the latest changes (new Findings: 1. 2. 3. 4. #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 |
Code Review (automated, round 3)Re-verified the actual diff ( Findings: 1. 2. 3. 4. 5. Lower-severity / cleanup: 6. 7. 8. 9. #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 |
728dc71 to
9e179f7
Compare
9e179f7 to
c44a575
Compare
What type of PR is this?
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::Groupidentities 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(), andinvalidate_scope()now returnResult<(), 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
c62bf68for this follow-up.git diff --checkpassed. The API E2E suite was compiled, not executed.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.router_multi_db(11),schema_meta_visibility(1),call_log_schema_upgrade(5), androuter_initialization_recovery(1). Those earlier results do not validate the newly added registration scenarios.c44a575run passed Unit Tests and Clippy, then failed the DB test's required cleanup-fault counter (0instead of1). 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.