Skip to content

fix: add mysql user-level lock functions - #25019

Merged
mergify[bot] merged 66 commits into
matrixorigin:mainfrom
jiangxinmeng1:cherry-pick-pr-24909-main
Jul 27, 2026
Merged

mergify[bot] merged 66 commits into
matrixorigin:mainfrom
jiangxinmeng1:cherry-pick-pr-24909-main

Conversation

@jiangxinmeng1

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #24728

What this PR does / why we need it:

  • Add MySQL-compatible GET_LOCK, RELEASE_LOCK, and IS_FREE_LOCK built-in functions.
  • Register function IDs, name mappings, and overloads for SQL planning.
  • Implement process-local named user-level lock behavior keyed by connection ID.
  • Add tests for acquire, release, free-state checks, non-owner release, missing locks, and NULL inputs.
  • Add function lookup coverage for the new built-ins.

jiangxinmeng1 and others added 6 commits June 17, 2026 10:57
1. RELEASE_LOCK now returns NULL (via isNull flag) when the named lock
   does not exist or was already released, matching MySQL behavior.
   When local refcount is 0, the code probes the lockservice with
   FastFail to distinguish 'lock does not exist' (NULL) from 'lock
   exists but held by another session' (0).

2. Enforce MySQL-compatible 64-character limit on lock names in
   getUserLevelLock, releaseUserLevelLock, and isUserLevelLockFree.

3. Add tests:
   - RELEASE_LOCK on never-created lock returns NULL
   - RELEASE_LOCK on already-released lock returns NULL
   - RELEASE_LOCK on lock held by another session returns 0
   - Overlong lock names are rejected
   - Exactly-max-length lock names work

Co-Authored-By: Claude Fable 5 <[email protected]>
- Replace validateUserLevelLockName with normalizeUserLevelLockName that
  lowercases names for case-insensitive matching (MySQL requirement).
- Enforce 64-character limit using utf8.RuneCountInString (character
  count), not len() (byte count), matching MySQL's documented behavior.
- Reject empty lock names in GET_LOCK, RELEASE_LOCK, and IS_FREE_LOCK.
- Add tests for empty-name rejection, case-insensitive contention, and
  multibyte character boundary (64/65 Chinese characters).

Co-Authored-By: Claude Fable 5 <[email protected]>
@jiangxinmeng1
jiangxinmeng1 requested a review from a user June 17, 2026 03:33
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex automated review

The latest cleanup-handoff changes still introduce a blocking failure mode under sustained lockservice failure.

P1 - A full cleanup backlog can block lock operations indefinitely (pkg/sql/plan/function/func_unary.go:7562)

After the detached-cleanup map and overflow shards are full, this sends synchronously to a 64-entry backlog. Callers pass context.Background(), so the send cannot be cancelled. The sole backlog worker retries admission forever while existing entries cannot drain during a persistent lockservice outage (line 7705). Once the backlog fills, subsequent failed GET_LOCK/probe cleanup blocks the SQL request indefinitely; session close can likewise block before freeing the process. The handoff needs bounded, cancellation-aware backpressure or another ownership-preserving mechanism that cannot hang request and teardown paths forever.

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex automated review

Three P1 lifecycle/compatibility defects remain at the current head.

P1 - Do not abandon failed-attempt cleanup when the bounded handoff times out (pkg/sql/plan/function/func_unary.go:7277)

The new 100ms handoff can return false when the entry/overflow maps and backlog are full. cleanupFailedUserLevelLockTxn then returns an error, but its txn was never added to userLevelLocks, so neither RELEASE_ALL_LOCKS nor Session.Close will retry it. The concrete lockservice creates the active txn before attempting the row lock and restores it after a bounded UnlockWithContext failure; a failed GET_LOCK/probe can therefore leave an active txn and possibly a remote lock with no cleanup owner indefinitely. The added test only proves prompt failure of handoff, not eventual cleanup after that failure.

P1 - Make split close-cleanup fallback admission atomic (pkg/sql/plan/function/func_unary.go:7658)

After atomic enqueueDetachedUserLevelLockCleanups rejects a large session-close batch, this fallback hands chunks off one at a time. With a saturated cleanup map and a backlog with room for only the first chunk, chunk 0 is accepted, a later chunk times out, and the function returns false. The caller consequently does not detach the session state, but Session.Close destroys the only process that could release the unsubmitted chunks. A session holding more than 2048 distinct locks during an outage can thus leave its remaining synthetic txns/locks permanently unretried. Reserve all fallback chunks before reporting success, or transfer ownership of every chunk once any is accepted.

P1 - Include the actual pre-PR session-id owner in legacy unlock candidates (pkg/sql/plan/function/func_unary.go:7117)

origin/main generated user-lock owners from the bare SessionInfo.SessionId.String(), so its transaction IDs contain mo-user-level-lock\0<uuid>\0<name>.... The current fallback candidates include only account:uuid and account:connectionID, never that bare UUID. When exact tracked IDs are unavailable, RELEASE_LOCK/RELEASE_ALL_LOCKS therefore unlock only non-existent candidate IDs (which lockservice treats as success), untrack local state, and leave the base-version lock held. TestReleaseLockPreGenerationLegacyTxnIDCompatible tests account:uuid, not the owner format used by origin/main.

…9-main

# Conflicts:
#	pkg/frontend/routine.go
#	pkg/frontend/routine_manager.go

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex automated review

A session-close cleanup failure can still leave advisory locks without a live cleanup owner.

P1 - Do not destroy a session after detached-cleanup handoff fails (pkg/sql/plan/function/func_unary.go:8348)

The new five-second handoff timeout is still not a guaranteed ownership transfer. When the bounded cleanup entries/overflow shards cannot admit the work and the 64-request backlog stays full, handoffDetachedUserLevelLockCleanups returns false; this branch only logs and leaves the state attached to the closing session. Session.Close then continues and frees the process, while failed UnlockWithContext restores the active transaction (pkg/lockservice/service.go:548). No worker owns the retained per-session entries, so the underlying user lock can remain held indefinitely after the client disconnects. Require a durable/service-owned handoff or retain/backpressure the session until ownership is transferred, and add a saturation-plus-recovery test that verifies a contender can acquire the lock after close.

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex automated review

Two blocking unhappy-path ownership/resource failures remain. The latest update prevents one ownerless-close case, but turns cleanup saturation into unbounded session teardown and does not protect failed lock attempts. Focused tests could not execute because the environment has no Go executable.

P1 - Timed-out GET_LOCK can abandon its cleanup transaction (pkg/sql/plan/function/func_unary.go:7277)

GET_LOCK passes its lock-wait context into cleanupFailedUserLevelLockTxn. For a positive timeout that context is already expired when Lock returns, so the bounded unlock cannot run and backlog handoff immediately fails if direct admission is saturated. The function then returns an error without recording the random attempt txn ID in userLevelLocks or transferring it to another owner. The concrete UnlockWithContext path restores an active transaction after bounded cleanup failure (pkg/lockservice/service.go:548), so a timed-out remote acquisition can remain active—and may still own a lock—with no path for RELEASE_ALL_LOCKS or Session.Close to discover it. The existing full-backlog test only verifies prompt handoff failure, not eventual ownership or cleanup.

P1 - Cleanup saturation now blocks Session.Close forever (pkg/sql/plan/function/func_unary.go:8355)

The latest commit calls handoffDetachedUserLevelLockCleanups with context.Background(). When the bounded entry/overflow maps are saturated and the backlog worker is permanently retrying during a lockservice outage, the backlog remains full and handoffDetachedUserLevelLockBacklogCleanups loops forever. Session.Close invokes this before closing the transaction handler, prepared statements, and other session resources (pkg/frontend/session.go:858), so every later disconnect retains its full session and cleanup goroutine indefinitely, defeating the cleanup subsystem's memory bounds. The new test proves blocking until a slot is manually freed but does not cover permanent saturation. Cleanup ownership needs a durable/service-owned transfer or another bounded teardown contract that cannot accumulate unbounded blocked sessions.

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex automated review

Migration-loss and pre-protocol migration blockers are fixed by failing closed; coordinator placement/identity fixes remain effective. Case handling is now internally consistent and accepted as non-blocking. The latest change bounds Session.Close handoff and retains a basic failed GET_LOCK cleanup, but its new retained-cleanup path still has blocking ownership and resource failures.

P1 - Retain successful probe cleanup when detached admission is saturated (pkg/sql/plan/function/func_unary.go:8024)

Author response: b041 retains failed GET_LOCK cleanup in pendingCleanups after bounded handoff fails. Why this remains blocking: RELEASE_LOCK and IS_FREE_LOCK can successfully acquire a probe, then fail its Unlock; unlockUserLevelLockProbe only tries the bounded handoff and returns here when it cannot enqueue. The probe is never tracked in userLevelLocks or pendingCleanups. UnlockWithContext restores its active transaction on failure (pkg/lockservice/service.go:547-548), so recovery can leave the probe lock held with no cleanup owner and future GET_LOCK calls blocked. Route this path through the retained ownership mechanism (or a service-owned record) and add a saturated-handoff/recovery regression for successful probes.

P1 - Do not discard cleanup IDs added during a retained-worker attempt (pkg/sql/plan/function/func_unary.go:7825)

Author response: b041 coalesces failed-attempt transaction IDs by cleanup key and retries them from one retained worker. Why this remains blocking: the worker snapshots pendingCleanups outside the mutex (7798-7817); another failed attempt for the same owner/name/kind can merge a new transaction ID at 7726-7736 while the old snapshot is unlocking. On success, or after a later detached handoff, this unconditional delete removes the current map entry rather than only the snapshot IDs (also 7835). The newer transaction is then untracked, while a failed bounded unlock restores its active transaction, leaving a possible held lock with no retry owner. Use versioned/CAS removal or subtract only processed IDs, and test admission of a second ID while the first attempt is in flight.

P1 - Keep retained cleanup fallback resource-bounded (pkg/sql/plan/function/func_unary.go:7725)

Author response: b041 replaces the previously blocking close-side handoff with asynchronous retained cleanup. Why this remains blocking: pendingCleanups and retainedCloseCleanups have no entry bound, admission control, or shutdown ownership. Once the 1024-entry detached map, overflow shards, and backlog are saturated during an outage, every distinct failed attempt or closing session is inserted into these unbounded maps (7736, 7747) and retried serially until recovery. A client can create arbitrary distinct lock names/sessions, bypassing all existing cleanup limits and eventually exhausting CN memory; after 2048 IDs for one key, the next failed cleanup is again ownerless. Use an enforced bounded, durable/service-owned queue or explicit backpressure, and test sustained saturation with many unique attempts and disconnects.

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex automated review

Migration loss and old-CN migration are fixed by failing closed; coordinator placement, immutable ownership, successful-probe retention, and concurrent retained-ID removal are fixed. Case handling is accepted as non-blocking. The new retention cap addresses unbounded maps but introduces two still-blocking saturation paths: ownerless probe locks and indefinitely blocked session teardown. Focused tests could not start because Go is unavailable locally.

P1 - Do not abandon a probe lock when retained cleanup is full (pkg/sql/plan/function/func_unary.go:8049)

Author response: f9a5 routes failed successful-probe cleanup through pendingCleanups and caps retained cleanup at 1,024 entries. Why this remains blocking: once detached entries, overflow shards, backlog, and the new retained map are saturated, both handoffDetachedUserLevelLockTxnCleanup and retainDetachedUserLevelLockTxnCleanup return false. A successful RELEASE_LOCK/IS_FREE_LOCK probe has definitely acquired the named lock; if UnlockWithContext fails, lockservice restores its active transaction at service.go:547-548. This branch then returns an error without recording the probe transaction anywhere, so recovery has no owner that can retry its unlock and the lock can remain held indefinitely. The new admission test explicitly verifies rejection at the cap but does not verify ownership of the rejected transaction. Close this by guaranteeing durable/service-owned cleanup ownership or applying bounded backpressure before acquiring another probe; add a saturation-and-recovery test proving a contender can acquire afterward.

P1 - Do not retry session teardown forever when retained cleanup is full (pkg/sql/plan/function/func_unary.go:8565)

Author response: f9a5 bounds pendingCleanups plus retainedCloseCleanups to prevent unbounded cleanup memory. Why this remains blocking: when that shared cap is full, retainUserLevelLockCloseCleanup rejects a new closing session. If the detached maps/backlog are also saturated during a persistent lockservice outage, this loop repeatedly spends up to five seconds on release and handoff, then sleeps and retries forever. Session.Close calls it synchronously before closing the frontend session, transaction handler, and prepared statements (session.go:858-883), so every subsequent disconnect can retain its full session indefinitely. The bound therefore recreates the previously reported teardown availability failure. Close this with a bounded close-side contract backed by guaranteed cleanup ownership/admission, and test permanent saturation without manually freeing a slot.

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex automated review

Follow-up disposition: migration safety, coordinator placement, immutable ownership, ordinary-filter duplication, sharded txn restore, partial-admission, retry-generation, probe-retention, and retained-ID concurrency issues are fixed. Case semantics is accepted as non-blocking. The prior UUID-holder IS_USED_LOCK compatibility issue is unchanged and not repeated per the follow-up rule. One current P1 remains: close-cleanup retention bypasses its bound and can grow without limit during an outage.

P1 - Retained close cleanup bypasses the cap and grows without bound (pkg/sql/plan/function/func_unary.go:7819)

Author response: f9a5 states that pendingCleanups plus retainedCloseCleanups are bounded to prevent unbounded cleanup memory. Why this remains blocking: the admission check rejects only when byOwner[owner] == nil. The caller at line 8602 has just obtained non-empty states from that same byOwner map, so every real closing session that still holds a lock bypasses the 1024-entry cap. Once detached cleanup admission is saturated and the lockservice remains unavailable, each distinct session is added to retainedCloseCleanups while its counts/byOwner state remains attached because the retry worker cannot make progress. Repeated disconnects therefore accumulate one retained owner and its lock state per session indefinitely, causing process-memory growth and eventual OOM. Enforce the cap for closing owners as well, while ensuring rejected cleanup has a live bounded backpressure or durable ownership path before the session is destroyed.

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex automated review

The latest blocker is fixed: active lock owners now consume bounded cleanup capacity before acquisition and reuse that slot during retained close cleanup. Earlier migration, coordinator-placement, immutable-identity, filter-duplication, sharded-restore, admission, retry, and probe-cleanup blockers remain fixed. Case semantics and legacy UUID compatibility are non-blocking. No new findings. Focused tests could not run because go is unavailable; static inspection and git diff --check found no issue.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep review completed on df55109. User-lock cleanup remains bounded and retains retry ownership across lockservice failures; migration fails closed for held locks and old-CN protocol; side effects run on the coordinator. Changes after the prior approval only merge main and stabilize cleanup tests. Focused lockservice, function, compile, frontend, and proxy tests passed, along with go vet and git diff --check. No blocking findings.

@mergify

mergify Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-07-27 06:20 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ❌ Checks failed · in-place
  • 🚫 Left the queue — 2026-07-27 07:00 UTC · at 74be22ee111fb31633e3714aaed58ab56cc01974

This pull request spent 40 minutes 14 seconds in the queue, with no time running CI.

Waiting for
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64
    • check-success = Matrixone CI / SCA Test on Linux/arm64
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
    • check-success = Matrixone Utils CI / Coverage
All conditions
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64
    • check-success = Matrixone CI / SCA Test on Linux/arm64
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
    • check-success = Matrixone Utils CI / Coverage
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection] (documentation)
  • github-review-decision = APPROVED [🛡 GitHub branch protection] (documentation)
  • any of [🛡 GitHub branch protection]:
    • check-success = Iceberg E2E Local
    • check-neutral = Iceberg E2E Local
    • check-skipped = Iceberg E2E Local
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-neutral = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-skipped = Matrixone UT Coverage / UT Coverage on Ubuntu/x86

Reason

The merge conditions cannot be satisfied due to failing checks

Failing checks:

Hint

You may have to fix your CI before adding the pull request to the queue again.
If you update this pull request, to fix the CI, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Requeued — the merge queue status continues in this comment ↓.

@mergify

mergify Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-07-27 08:22 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-07-27 10:10 UTC · at 1a315295fc11b4d760fe1939e9471af338b48afa · squash

This pull request spent 1 hour 47 minutes 55 seconds in the queue, including 37 minutes 24 seconds running CI.

Required conditions to merge
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection] (documentation)
  • github-review-decision = APPROVED [🛡 GitHub branch protection] (documentation)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-neutral = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / e2e BVT Test on Linux/x64(LAUNCH, PESSIMISTIC)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone CI / SCA Test on Linux/arm64
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone Utils CI / Coverage
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
  • any of [🛡 GitHub branch protection]:
    • check-success = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-neutral = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-skipped = Matrixone UT Coverage / UT Coverage on Ubuntu/x86

This branch was previously deployed

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

Labels

kind/bug Something isn't working size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants