Skip to content

[Bug]: stale global sysvar refresh can overwrite a committed SET GLOBAL value #26270

Closed

Description

@XuPeng-SH

Is there an existing issue for the same bug?

  • I have checked the existing issues.

Related but not a duplicate:

Branch Name

main / CI run for PR #26251

Commit ID

d074e33040f83d924ba0f8dd728ef79a42ec56ec

Other Environment Information

Actual Behavior

The BVT executes successfully until:

SET GLOBAL password_history = default;
SET GLOBAL password_reuse_interval = default;
SELECT @@global.password_history;

password_history has default value 0, but the immediate read returns its old value 5:

expected: 0
actual:   5

The SQL statement succeeds; there is no disconnect, timeout, or SQL error.

A local black-box stress reproduction confirms a logical stale-snapshot lost update on a single CN:

  • no concurrent global-sysvar refresh: 5,000 iterations of SET 5 -> SET DEFAULT -> SELECT had no mismatch;
  • one concurrent connection repeatedly executing SHOW GLOBAL VARIABLES LIKE 'password_history': mismatch at iteration 55;
  • twelve concurrent refreshers: mismatch at iteration 3; three subsequent runs each mismatched at iteration 1.

At mismatch time:

SELECT @@global.password_history  => 5
catalog variable_value             => 0

So the committed catalog value is correct, but the in-memory cache has been reverted to the old value.

A separate two-CN check also confirms that SET GLOBAL has no cross-CN cache invalidation: after CN1 commits 0, a pre-existing CN2 session still reads 5 until it performs a global-sysvar refresh. This widens the impact, but the above same-CN race alone reproduces the CI symptom.

Expected Behavior

After successful SET GLOBAL password_history = DEFAULT, an immediate SELECT @@global.password_history must return 0.

A refresh of global system variables must never overwrite a value committed by a concurrent later SET GLOBAL with an older catalog snapshot. The behavior must remain correct for all dynamic global system variables, not only password settings.

Steps to Reproduce

Use two connections to the same CN.

Connection A repeatedly refreshes global system variables:

SHOW GLOBAL VARIABLES LIKE 'password_history';

Connection B loops:

SET GLOBAL password_history = 5;
SET GLOBAL password_history = DEFAULT;
SELECT @@global.password_history;

Eventually Connection B can read 5 while querying mo_catalog.mo_mysql_compatibility_mode shows password_history = 0.

Root Cause

GlobalSysVarsMgr.Get obtains sysVarsMp from catalog before acquiring the manager/system-variable locks, then later replaces the entire cache map:

sysVarsMp, err := ses.getGlobalSysVars(ctx, bh) // old snapshot
...
sysVars.mp = sysVarsMp // can overwrite a newer SET GLOBAL update

In contrast, SetGlobalSysVar persists the value and then updates only the in-memory entry:

if err = doSetGlobalSystemVariable(...); err != nil { ... }
ses.gSysVars.Set(name, val)

Interleaving:

  1. refresher reads catalog snapshot password_history=5;
  2. setter commits password_history=0 and calls Set(..., 0);
  3. refresher acquires the lock and replaces the complete map with its old snapshot;
  4. @@global.password_history reads 5.

This is mutex-protected at the Go memory level, but it is a logical lost-update race.

Refreshes are triggered not only by SHOW GLOBAL VARIABLES (added by #24844), but also by session/global-system-variable initialization. Therefore the trigger can be an unrelated concurrent connection or monitoring query.

Possible Fix Approaches

Whichever implementation is selected, it should preserve these invariants:

  1. Once a successful SET GLOBAL returns, the calling CN must immediately expose the committed value and must never regress to an older value.
  2. Cache publication must be monotonic: a snapshot captured before a newer committed update cannot overwrite that update.
  3. The catalog remains the durable source of truth; CN caches are derived state and must converge after missed notifications or restart.
  4. The solution must apply to every dynamic global system variable and account, not special-case password variables or this BVT.

Option A: local generation guard

Maintain an account-level cache generation, or per-variable generations if finer granularity is needed.

  • A refresh records the current generation before reading the catalog.
  • After the catalog query completes, it acquires the publication lock and compares the generation again.
  • If the generation changed, the snapshot is stale and must be discarded or re-read; it must not replace the cache.
  • After the catalog update commits, SET GLOBAL updates the local entry and increments the generation under the same publication ordering.

This directly closes the observed race without holding the cache read/write lock during catalog I/O. A bounded retry or singleflight refresh can prevent concurrent stale refreshes from causing unbounded re-reads.

Option B: serialize refresh and SET GLOBAL publication

Use a separate sequencing mutex for global-sysvar mutation; do not hold the hot cache RW lock across catalog I/O.

Both of these operations participate in the same sequence:

  • refresh: read the complete catalog snapshot, then publish it;
  • SET GLOBAL: persist the new value, then publish the local cache update.

If refresh runs first, SET GLOBAL publishes last. If SET GLOBAL runs first, refresh reads the committed value. This is simpler than versioning, but catalog reads and writes for the same account become serialized, so contention and lock scope must be evaluated carefully.

Serializing refreshes alone is insufficient: the SET GLOBAL write/publication path must participate in the same ordering, or must guarantee a final fresh publication before returning.

Option C: persistent revision and versioned cache updates

Associate global-sysvar changes with a monotonically increasing catalog revision or commit timestamp.

  • Cache entries or snapshots carry their source revision.
  • A CN only applies an update whose revision is not older than the cached revision.
  • Whole-map replacement should be avoided unless the snapshot has a well-defined consistent revision; otherwise merge versioned entries individually.
  • Reset-to-default and deletion need versioned tombstone semantics so an older explicit value cannot be resurrected.

This provides a foundation for cross-CN convergence and makes refresh/reconnect/restart ordering explicit, but requires a catalog/schema and propagation design.

Cross-CN invalidation and reconciliation

The same-CN lost update can be fixed independently, but distributed correctness additionally requires propagation:

  • after catalog commit, publish an account/variable invalidation or a versioned change event to other CNs;
  • receivers ignore duplicate or older revisions and refresh/apply only newer state;
  • periodically reconcile against the catalog as a fallback for missed notifications;
  • initialize new/restarted CNs from the durable catalog before serving dependent reads.

The local SET GLOBAL path should not wait for every CN to acknowledge unless strong cluster-wide synchronous visibility is an explicit requirement. However, the calling CN must be correct before the statement returns, and remote CN convergence should have a defined, testable bound.

Recommended direction

For the immediate bug, Option A is a small and robust local fix. Combine it with versioned cross-CN invalidation/reconciliation so the design also closes the already-confirmed multi-CN stale-cache gap. Option B is viable if its serialization and latency impact are acceptable. Option C is the strongest long-term model when a durable cluster-wide revision can be introduced.

Do not fix this by adding sleeps/retries to BVT, weakening the immediate-read assertion, refreshing only password variables, or updating the in-memory cache before the catalog transaction commits.

Regression Coverage

Add deterministic coverage that blocks a refresh after it captures an old snapshot, commits SET GLOBAL ... = DEFAULT, then releases the refresh and verifies @@global remains at the new value.

Also add concurrent refresh-vs-SET GLOBAL coverage and a multi-CN visibility test for existing sessions/CN caches.

Activity

  1. added
    kind/bug
    on Jul 27, 2026
  2. self-assigned this
    on Jul 27, 2026
  3. added
    severity/s0
    and removed on Jul 27, 2026
  4. iamlinjunhong commented on Nov 1, 2026

    @iamlinjunhong
    Contributor

    The cross-CN stale global-variable cache gap described in this issue reproduces on current official 4.2-dev and explains a new protected-database CI failure, independently of PR #31754.

    Source PR head: ebab89c15e2e17e503b7a837385a863f1a7902fc. Run https://github.com/matrixorigin/matrixone/actions/runs/41313690351, attempt 1. Failed job: https://github.com/matrixorigin/matrixone/actions/runs/41313690351/job/124872194147, multi cn e2e bvt test docker compose(PROXY), step Start BVT Test. The runner executes bash optools/run_bvt_group.sh <mo-tester> <test/distributed/cases> 0.

    The full failed-step console and BVT execution artifact show exactly four failures, all in test/distributed/cases/tenant/privilege/protected_database.sql:186-189 under a restricted tenant writer:

    create database protectedcasedb;
    drop database protectedcasedb;
    create database ProtectedCaseDB;
    drop database ProtectedCaseDB;

    Each expected internal error: do not have privilege to execute the statement[12,0,0]; each actually returned null (success). The complete BVT summary is 70534 statements, 70087 successes, 4 failures, 443 ignored. The admin sets lower_case_table_names=0 and protected_databases='ProtectedCaseDB' while a previously opened writer session remains connected.

    Clean official-target comparison: built unmodified 4.2-dev 7a161fda57d53e0f15131b26372c71b67cc5db87 from a source export verified against that exact Git tree, using Go 1.26.4, -race -tags=matrixone_test, CGo, Darwin/arm64. The service's version output reported that full SHA. Ran two independent CN OS processes with one LOG and one TN, shared disk-backed storage, unique ports/data paths, and persistent direct SQL connections to pin the two CNs. This is a cross-CN mechanism reproduction, not a claim to have run Docker/PROXY locally.

    Reproduction steps:

    1. Create a fresh tenant, set protected_databases='initial_placeholder', create a restricted writer role with CREATE/DROP DATABASE privileges, and disable the session privilege cache.
    2. Open and retain the writer connection on CN1; confirm its initial global value is initial_placeholder.
    3. On the admin connection pinned to CN0, set lower_case_table_names=0 and protected_databases='ProtectedCaseDB'.
    4. The existing CN1 writer still reads initial_placeholder and all four SQL statements above succeed.
    5. A control writer on CN0 reads ProtectedCaseDB and CREATE DATABASE ProtectedCaseDB correctly fails with Error 20101 (HY000): internal error: do not have privilege to execute the statement.

    The diagnostic client returned exit 0 only after asserting all those observations. An earlier same-process embedded multi-CN diagnostic correctly denied the writes and did not reproduce the issue; separate CN processes were necessary for this cache-isolation witness. All owned services have exited and their logs/configuration/data were retained outside the repository.

    Causal check: pkg/frontend/authenticate2.go, types.go, variables.go, and the exact protected_database SQL/result are identical between this baseline and the PR head. getProtectedDatabaseSet reads GetGlobalSysVar, which reads the session's CN-local gSysVars; SET GLOBAL publishes the local entry after catalog persistence. The two-process witness directly demonstrates the cross-CN cache visibility gap already documented here. The full PR diff changes vector RANK options, HTTP object-storage tracing and unrelated DROP INDEX test cleanup; it does not alter this permission/global-variable mechanism or the BVT harness. The same head's owning fileservice/protobuf/parser/planner checks and vector rank-options BVT passed.

    This also has an access-control consequence: a stale CN can allow CREATE/DROP on the newly protected database for an existing restricted session. It is an independent release-branch defect; this PR does not repair it. This closed issue is being reused as a tracking record based on the new clean-target reproduction, without reopening it or using it as an open-defect exemption.

    Coverage job https://github.com/matrixorigin/matrixone/actions/runs/41313690351/job/124882466150 failed its prerequisites because a producer lacked a complete profile; no coverage verdict was calculated. CI Required https://github.com/matrixorigin/matrixone/actions/runs/41313690351/job/124882509858 propagated the UT/Compose failures. The separate Iceberg setup failure is recorded in #26107. After these two records, only one failed-jobs rerun of this unique workflow run is planned; no code or test expectations were weakened.

  5. gouhongshen commented on Nov 10, 2026

    @gouhongshen
    Contributor

    Another occurrence of the cross-CN stale global-variable/protected-database failure, independent of PR #32490.

    • Workflow/run: MatrixOne ALL CI run 42829319422, attempt 1.
    • Failed job: multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC), step Start BVT Test.
    • PR head: b47686a7d7f35058b4b5f7d07def618366a78948; target: 4.2-dev at a7bc2008e9236708fee0328376f2c2c6b6f0d3fc.
    • Observed: test/distributed/cases/tenant/privilege/protected_database.sql:186-189 ran create database protectedcasedb, drop database protectedcasedb, create database ProtectedCaseDB, and drop database ProtectedCaseDB as the restricted tenant writer. Every statement expected internal error: do not have privilege to execute the statement[12,0,0] and actually returned null (success). The BVT summary was TOTAL 70992, SUCCESS 70545, FAILED 4, IGNORED 443, ABNORAML 0.
    • Why unrelated to PR fix: preserve composite index access for joins #32490: its exact target-to-head diff changes only pkg/sql/plan/apply_indices.go, its unit tests, and optimizer/issue_32460.sql/.result. The failing SQL file and the frontend privilege/global-variable paths are unchanged. The PR's new optimizer/issue_32460.sql passed all 11 statements in this same job.

    This repeats the exact four-statement signature and clean-4.2-dev cross-CN cache mechanism recorded above. No product code, test expectations, or CI configuration were changed to hide the failure.

    Downstream Coverage occurrence in the same run:

    • Workflow/job: MatrixOne ALL CI run 42829319422, attempt 1, Coverage job 129902950137, at PR head b47686a7d7f35058b4b5f7d07def618366a78948.
    • Observed: Verify coverage prerequisites exited 1 with PREREQUISITES_READY=false; no coverage verdict was calculated. The calling workflow requires every producer workflow to succeed, and the pessimistic BVT producer failed with the four-statement protected-database signature above. UT Coverage and proxy BVT succeeded, and all three UT/BVT profile artifacts were published, but the aggregator stopped before processing them.
    • Why unrelated to PR fix: preserve composite index access for joins #32490: this Coverage failure is a direct downstream consequence of the unrelated product failure documented above. It did not reject the PR for changed-code coverage, and the PR does not alter the privilege/global-variable mechanism or CI configuration.

    Evidence: Coverage terminal log and workflow run.

    Downstream CI Required occurrence after the workflow completed:

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

Metadata

Metadata

Assignees

Labels

kind/bugseverity/s0

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions