Skip to content

fix(logtail): add linearizable read barrier - #27842

Merged
XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/issue27834-linearizable-logtail-barrier
Aug 29, 2026
Merged

XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/issue27834-linearizable-logtail-barrier

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

What changed

Replace the fixed HLC uncertainty wait used by authentication with a generic,
TN-ordered logtail read barrier:

  • place a barrier marker in the same TN FIFO as committed transactions and
    return the exact published frontier;
  • order logtail updates, forced filtered progress, and the barrier response
    through the existing per-session stream;
  • correlate concurrent barrier requests and wait for the normal CN apply
    pipeline before returning;
  • use the generic engine capability from authentication without adding
    catalog-specific TN logic;
  • fail closed on cancellation, reconnect, missing capabilities, queue
    pressure, and regressing apply timestamps;
  • introduce the wire contract at MORPC v39; protocol <=38 retains the legacy
    HLC fence during rolling upgrades.

The invariant is:

commit completes before barrier begins
  => commit precedes TN marker
  => its logtail precedes the barrier response
  => CN apply reaches the exact frontier before the barrier returns

The full ordering, ownership, upgrade, and failure model is documented in
docs/design/authentication_catalog_freshness.md.

Systemic overload and hot-path fixes

The final design bounds barrier work across every shared stage instead of only
making queue insertion cancellable:

  • each CN retains at most 100 in-flight request correlations;
  • the logtail server admits at most 100 barriers globally and keeps each slot
    owned through TN processing, notifier ordering, and response hand-off;
  • the manager independently caps markers at 100, one queue batch, so barriers
    cannot fill the 10,000-entry commit FIFO;
  • shutdown drains queued barrier ownership, while cancellation before and
    after TN admission has distinct, exactly-once cleanup;
  • adjacent markers at one FIFO frontier are completed together without empty
    collection segments.

Normal commit traffic keeps the original direct SafeQueue.Enqueue channel
send. Context checks/selects exist only in EnqueueWithContext; transaction-
only manager batches perform one atomic pending-barrier load and do not scan or
type-assert the batch twice.

Root cause and performance

#27763 fenced every login beyond the HLC uncertainty upper bound. With the
default 500ms max clock offset, each fresh connection paid about 500ms even
when there was no real logtail lag. TPCH reconnects for each query, so 22
queries accumulated about 11 seconds, matching #27834's regression.

Initial candidate validation on 10.222.1.55 (exact commit 14c0181070):

Check Result
main fresh login about 513-527ms each
main, 22 sequential fresh connections 11.415s
candidate, 30 sequential fresh connections 649ms total, 21ms average, p95 31ms
password mutation followed immediately by login 20/20 new password accepted; 0 stale old-password accepts
role revoke/grant followed immediately by authorization 0 stale revoke accepts; 20/20 regrants visible

On the final code, the focused SafeQueue benchmark (Apple M4, 1s x 3,
0 alloc/op) changed from a median 76.95ns/op at the prior PR head to
58.59ns/op after restoring the background hot path, about 24% lower.

Actual TPCH-10G must still be rerun on the final head as a merge acceptance
gate; synthetic connection timing is supporting evidence, not a replacement.

Validation

  • rebased onto main@f779dff860; historical main-merge commits were removed, the three logical commits were preserved, and range-diff is patch-equivalent except for the required v38-to-v39 capability allocation;
  • focused rebase validation passed for the v38 legacy authentication fallback, v39 TN-ordered barrier, fail-closed/cancellation paths, and the independent v38 temporary-table migration contract;
  • CGo-aware normal tests passed for logstore/sm, TAE logtail manager/service,
    disttae, engine/frontend, and status;
  • race tests passed three times for logstore/sm, TAE logtail manager/service;
  • the new shared-cluster acceptance test ran three times: CN-0 repeatedly
    changes credentials and revokes/grants an explicit role, while each fresh
    login is immediately routed to CN-1 with no sleep or retry;
  • deterministic tests cover CN/server/manager admission bounds, caller cancel,
    post-admission cancel, queue/send failure, shutdown Drain, response
    correlation, ordered progress, and slot reuse;
  • git diff --check passes; tests are additive and do not reduce coverage or
    assertions.

Fixes #27834

@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 →

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Deep review result: blocking. GitHub does not allow this account to submit REQUEST_CHANGES on its own PR, so this comment records the equivalent review decision.

The main linearizability chain looks sound: a completed commit precedes the TN FIFO marker; accepted pre-marker updates precede the correlated barrier response; the CN then waits for the normal multi-worker apply watermark. Response correlation, cancellation/reconnect cleanup, non-regressing session frontiers, fail-closed behavior, and the v37 fallback are also directionally correct.

However, I found two production blockers and one mandatory evidence gap:

  1. [P1 performance] Preserve the existing non-cancellable SafeQueue.Enqueue fast path.

    Enqueue now delegates every caller through context.Background(), ctx.Err() and a select send in safeq.go. This utility is not private to the new barrier: it is on WAL pre/write/apply queues, logservice commit/truncate queues, batch-store queues, object-I/O queues, checkpoints, GC, CDC, and the logtail commit path. Normal transaction-only logtail batches are also scanned/type-asserted once in the new outer loop and again in orderedCollectAndPublish (mgr.go). This contradicts the design's claim that the ordinary commit path retains its prior shape and adds no work beyond recognizing a rare marker.

    Keep Enqueue on its original direct-send path and isolate cancellation overhead in EnqueueWithContext; avoid the second normal-batch scan or provide before/after TP commit/logtail benchmarks proving no regression across the affected queues.

  2. [P1 availability] One unauthenticated connection currently creates one unthrottled global TN marker.

    Authentication invokes the barrier before tenant/user/password validation (session.go). Unlike subscribe/unsubscribe, ReadBarrier bypasses the client's request limiter (client.go), and every concurrent login inserts its own marker into the exact same bounded queue used by OnEndPrepareWAL (mgr.go, mgr.go). A connection/login flood can therefore fill and continuously consume the TN publication FIFO and block transaction commit completion before credentials are accepted.

    Add bounded/coalesced barrier admission (without weakening the real-time invariant) or an equivalent mechanism that prevents authentication load from starving commits. Add a deterministic stress test proving sustained concurrent login/barrier traffic does not stall transaction publication and that cancellation releases every waiter/marker owner.

  3. [P1 acceptance evidence] Close the PR's own distributed and regression criteria.

    The design requires mutation on CN-A and later login on a distinct CN-B, without sleeps/retries. The committed tests mock individual seams, and the PR description reports semantic loops without identifying distinct-CN routing. Please add reproducible two-CN evidence for both deny and allow directions (password plus revoke/grant is appropriate), and rerun the actual TPCH-10G workload that triggered #27834. Synthetic connection timing explains the 11-second delta well, but it is not the issue's end-to-end acceptance result.

CI is green at 47fc63e437, and I found no generated-protobuf or diff-integrity issue. The blockers above concern production hot-path scope, pre-auth resource amplification, and missing acceptance closure rather than flaky CI.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Systemic follow-up pushed in 9c3a44d303 after two ownership/performance review passes.

The previous blockers are addressed in code:

  • restored the original direct SafeQueue.Enqueue hot path; only request-scoped enqueue pays context/select overhead;
  • removed the normal transaction-batch double scan (one atomic pending-barrier check, then the original collector path);
  • added bounded admission at CN (100), logtail server globally (100 end-to-end), and TN manager (100 / one batch);
  • the server slot remains owned through manager FIFO, notifier ordering, and response hand-off, so a multi-CN login flood cannot move the backlog downstream and stall ordinary publication;
  • made cancel-before-admission, cancel-after-admission, queue rejection, send failure, and shutdown Drain release ownership exactly once;
  • coalesced adjacent markers at the same frontier;
  • added a real two-CN acceptance test: mutations are committed on CN-0 and fresh password/explicit-role logins are immediately checked on CN-1, without sleep/retry. It passed with -count=3.

Validation also includes three race runs for the affected queue/manager/service packages and the broader frontend/disttae/status suites. The focused queue benchmark improved from median 76.95ns/op at the previous PR head to 58.59ns/op (about 24%, 0 alloc/op).

One acceptance item remains intentionally explicit: rerun actual TPCH-10G on this final head before merge. The existing connection benchmark explains the regression and validates the latency mechanism, but does not substitute for the requested workload-level result.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Deep review result at 601eebc523: implementation and design PASS; no code blocker found.

GitHub does not allow this account to approve its own PR, so this COMMENTED review records the equivalent approval decision. I reviewed the mandatory design at this exact revision and approve it for implementation: the linearization point, ownership transfers, capacity bounds, rolling-upgrade behavior, failure containment, and validation plan are internally consistent with the code.

The four-stage correctness chain closes:

  1. a commit cannot complete before OnEndPrepareWAL has admitted it to the TN FIFO;
  2. the marker is processed only after all pre-marker transactions have been collected and handed to the publisher in order, and captures previousSaveTS exactly;
  3. pre-marker updates, any required empty progress response, and the correlated barrier response enter the same per-session response order;
  4. the CN consumes the control response internally and still waits for the existing multi-consumer apply watermark before returning the frontier. Authentication then preserves any later session minimum and creates its single catalog transaction only after that wait.

The previous blockers are closed:

  • ordinary SafeQueue.Enqueue retains its direct-send hot path; request cancellation is isolated to EnqueueWithContext, and transaction-only manager batches pay one atomic load without a second scan;
  • unauthenticated barrier work is bounded independently at the CN correlation map (100), logtail server publication path (100), and TN marker FIFO (100 / one batch); cancellation, queue rejection, stream failure, response hand-off, and notifier drain each have one effective release owner;
  • the deterministic two-CN acceptance test routes mutations to CN-0 and fresh password/revoke/grant logins to CN-1 without sleep or retry.

Q1-Q3 audit: no leak, double release, hung wait chain, or unbounded accumulation was found. CN pending entries/slots are removed on every return; admitted TN markers own buffered completion until queue processing; server admission is released by the local pre-transfer owner, or transfers exactly once to sender hand-off/shutdown drain. Reachable authentication waits terminate through caller/root context, stream breakage, queue shutdown, or bounded send behavior. Shared queues and retained correlations remain explicitly bounded.

The rebase is clean. range-diff shows the final two logical commits are patch-equivalent; the first differs only because current main already owns MORPC v38 for temporary-table migration. The barrier correctly moved to v39, protocol <=38 uses the HLC fallback, and the independent v38 migration gate remains unchanged.

Evidence:

  • exact-head focused CGo-aware tests passed for v38 fallback, v39 barrier/fail-closed/cancellation, the two-CN issue reproduction, and v38 temporary-table migration;
  • the patch-equivalent pre-rebase head passed full Linux UT, SCA, coverage, shared build, and multi-CN BVT; focused and owning-package race runs passed for queue, manager, service, and disttae state boundaries;
  • focused race stress passed 100 times for queue cancellation, post-admission marker ownership, concurrent response correlation, ordered filtered progress, and reconnect generation capture;
  • current hot-path benchmark remained at 0 alloc/op (60.78/61.96/69.81 ns/op across three 1s runs); git diff --check passed.

One non-code merge gate remains exactly as declared in the PR body: run the actual TPCH-10G workload on final head and attach the result before merging. The 21ms fresh-connection evidence and the removal of the fixed 500ms fence strongly validate the mechanism, but they do not replace that workload-level acceptance result.

@XuPeng-SH
XuPeng-SH merged commit fcc8ff3 into matrixorigin:main Aug 29, 2026
27 checks passed
@XuPeng-SH
XuPeng-SH deleted the codex/issue27834-linearizable-logtail-barrier branch August 29, 2026 16:12
XuPeng-SH added a commit that referenced this pull request Aug 29, 2026
Fixes #27833.
Related to #27718 and #26087.

Rebased onto `main@fcc8ff3`, which contains the merged TN-ordered
logtail barrier from #27842. The complete feature-only range is now
`fcc8ff3b03..66e95cf`; no dependency merge history remains in this
PR.

Design:
[`docs/design/feature_quota_admission.md`](https://github.com/matrixorigin/matrixone/blob/codex/issue27833-feature-limit-barrier/docs/design/feature_quota_admission.md)
(**Review required**).

## Why

Feature quota is admission-control state, but `CREATE SNAPSHOT` and
`DATA BRANCH CREATE` could read a stale CN catalog snapshot immediately
after an administrator committed `mo_feature_limit_upsert` on another
CN. A stale lower value falsely rejects an allowed operation; a stale
higher value can persist an object after the feature was disabled or
reduced. Concurrent creators could also count the same pre-publication
metadata and exceed a finite limit.

Required contract:

- a registry/quota commit completed before an operation starts
constrains it on every CN;
- finite admission and metadata publication are one serialized
transaction;
- the check does not advance or downgrade a caller's fixed SI
transaction;
- cancellation, missing dependencies, and freshness failures fail
closed.

## What changed

- Establish a TN-ordered logtail barrier before reading feature
registry/quota state, then advance the owning RC workspace to the
applied frontier.
- For finite branch quota, retain the account quota-row lock, establish
a second frontier after any lock wait, re-read the locked quota, count
usage, and publish metadata in the same transaction.
- Preserve explicit SI semantics with an independent short
pessimistic-RC control transaction. Disabled rejects, unlimited
proceeds, and finite quota asks the caller to retry outside the active
transaction.
- Preserve rolling-upgrade compatibility: protocol v38 and below use the
HLC uncertainty fallback; v39 uses the TN-ordered barrier.
- Fail closed for barrier, logtail, workspace, transaction, and
typed-nil executor failures.
- Add a bounded two-CN branch acceptance sequence on one pre-opened CN-B
connection: `1 -> 0 -> -1 -> 0 -> 1`, with no sleep or retry between
CN-A's committed quota mutation and admission.
- Reuse the existing shared two-CN cluster; no extra embedded-cluster
startup was added.
- Make catalog-readiness polling synchronous and context-bounded,
preserve the last SQL error, close partial executor results, and avoid
calling `testing.T` from a polling worker goroutine.
- Strengthen unlimited snapshot and SI snapshot-preservation assertions.

## Performance and risk

- Ordinary SQL and authentication add no new barrier, lock, scan,
allocation, or goroutine from this feature change.
- Snapshot create: one v39 barrier and the existing lineage-owner lock.
- Disabled/unlimited branch create: one v39 barrier and no quota lock.
- Finite branch create: two v39 barriers and serialization only on that
target account's quota row; different accounts remain concurrent.
- The v38 fallback is correct but can wait about one `MaxOffset` for
disabled/unlimited and two for finite branch admission.
- Every wait is request-context-bound; topology readiness has one
30-second total bound and preserves the causal probe error.

The merged #27842 queue/RPC hot path is byte-identical to `main`. On
this final tree, `BenchmarkSafeQueueEnqueue` (Apple M4, 1s x3) reports 0
alloc/op; the background path is 72.08/65.79/65.25 ns/op (median 65.79
ns/op), and the request-context path is 93.54/109.6/87.28 ns/op. TPCH
acceptance belongs to the already-merged barrier change; this
feature-only delta does not add work to TPCH query execution.

## Validation

Exact head `66e95cf25b` on `main@fcc8ff3`:

- 17 selected frontend quota/authentication/protocol-boundary test
functions, including all nested fail-closed cases: PASS (`pkg/frontend`,
1.067s).
- `BenchmarkSafeQueueEnqueue`, background and request-context paths, 1s
x3: PASS, 0 alloc/op.
- `git diff --check origin/main...HEAD`: PASS.
- `git range-diff` against the pre-rebase feature commit:
patch-equivalent.
- Production and test trees are byte-identical to the previously
validated #27844 head; the rebase changed ancestry and the two design
clarifications only.

Semantically reused because the relevant code, tests, build mode,
topology, and current-main dependency tree are unchanged:

- `TestIssue26087ConcurrentDataBranchQuota`,
`TestIssue27718ConcurrentSnapshotQuota`, and
`TestWaitForCatalogVisibilityPreservesProbeError`: PASS on the shared
two-CN cluster (15.310s on the pre-rebase identical tree).
- v38 temporary-table migration compatibility tests across
frontend/proxy.
- normal and focused race evidence for the TN queue, manager,
service/RPC correlation, cancellation, CN consumer apply, and
authentication barrier paths from merged #27842.
- two-CN authentication acceptance and dependency SCA validation from
merged #27842.

Fresh CI was triggered by the force-rebase and was not awaited.
XuPeng-SH added a commit that referenced this pull request Aug 30, 2026
Fixes #27775

> [!IMPORTANT]
> **Draft status on exact head `f48843c9e2`, rebased on `main`
`07fe9a69c6`: deterministic implementation/code closure is complete. The
causal A/B, 100M/1B endpoint evidence, and exact-head SQL/compile plus
lockservice owner approvals are still required. Do not merge or call
#27775 fixed from local tests.**

Design: `docs/design/load_data_unique_index_locking.md`, revision v8.

## Problem and evidence boundary

The reported 100M/1B indexed `LOAD DATA` regression correlates with
hidden-UNIQUE per-batch lock encoding/submission, lock coarsening,
higher mutex delay, and lower CPU utilization. The no-index control is
comparatively stable.

This is still a hypothesis, not proven causality. The exact #26706
parent/merge A/B (`6742f958d466` vs `35db232dfc3b`) has not been run.
The earlier 5M experiment changed the normalized indexed/no-index ratio
by only about 2.5%, so it is mechanism evidence, not proof that #27775
is fixed. Implementation was explicitly requested before that external
gate; the PR therefore remains Draft.

## Current v8 design and implementation

Only a positively identified large modern `LOAD DATA` can qualify:

- fresh physical generation zero, retry enabled, non-internal and
non-prepared;
- statement-owned autocommit pessimistic RC (`Autocommit=true`,
`ByBegin=false`);
- finite effective input estimate `Cost*Rowsize >= 1 GiB`, uncompressed
CSV/JSONLINE remote source;
- one ordinary non-FK/non-partitioned/non-temporary user base table;
- synchronous default/BTREE indexes with at least one regular UNIQUE
hidden table;
- v39 protocol and a real underlying `engine.LogtailReadBarrier`
capability;
- authoritative base/hidden PK types whose lockop table range covers the
complete physical keyspace.

Missing, contradictory, duplicated, unsupported, reused, or ambiguous
state fails closed to exact `main` behavior. FLOAT/DOUBLE remain
ineligible because the current finite table-range endpoints do not cover
infinities and every NaN payload. Real production shapes such as a
`uint32` base PK and binary-`varchar` composite hidden PK are admitted.

The canonical logical plan is never mutated. Before source
initialization, generation zero:

1. acquires the existing metadata/general and base full-domain locks;
2. acquires an Exclusive full-domain lock for every promotable hidden
UNIQUE table, sorted by physical table ID;
3. invokes the existing v39 TN-ordered logtail read barrier;
4. advances the same pessimistic-RC transaction snapshot strictly beyond
the applied frontier; and
5. returns one ordinary physical retry.

The retry validates an exact coordinator-local proof: transaction ID,
logical plan identity, physical generation, installed snapshot,
frontier, and target value. It filters only covered hidden row targets
from a local `LockOp` copy. Logical rebuild, reused generation,
capability/protocol mismatch, or proof mismatch permanently disables the
optimization for that `Compile.Run`.

No protobuf/wire/catalog/durable-state change, planner cache policy,
generic lock ordering, goroutine, channel, or production log site is
introduced.

## Correctness and unhappy-path closure

- The promotion creates one bounded context: `min(lock_wait_timeout,
120s, caller deadline)`.
- That context's **absolute deadline** is copied into every lock RPC and
clamped by any shorter session timeout. Remote owners therefore see the
same authoritative deadline; target N cannot restart the budget consumed
by targets 1..N-1.
- Caller cancellation/deadline is preserved. Only expiry of the internal
aggregate budget maps to lock timeout.
- Hidden-lock, barrier, snapshot-update, capability, protocol, or proof
failure publishes no proof and never initializes the source.
- A successful lock wait may refresh the transaction snapshot. The
narrow helper suppresses only the incomplete ordinary retry; the
stronger common barrier still runs before proof publication. Definition
changes keep the existing retry behavior.
- Locks remain transaction/lockservice-owned. Compiler cancellation
stops the wait but does not unlock a partially acquired prefix behind
the transaction owner's back. Existing terminal autocommit rollback
releases the whole transaction exactly once.
- A real two-target test proves target 1 is owned while target 2 waits,
cancellation returns, no barrier runs, rollback releases target 1, and a
FastFail point contender then succeeds.
- A real binary-`varchar` full-range test proves an interior Exclusive
writer waits, the fenced retry is reentrant with no second barrier, and
transaction rollback lets the writer proceed.
- Admission tests cover the positive implicit-autocommit pessimistic-RC
case and reject `BEGIN`, `autocommit=0`, SI, optimistic, mirror,
aborted, and missing-ID transactions.

Lifecycle audit:

| Question | Closure |
| --- | --- |
| Q1: who owns cleanup? | The transaction/lockservice owns every
acquired lock; compiler owns only schema-bounded proof metadata and
disables/clears it on failure/rebuild. |
| Q2: what can wait? | Each target wait ends through holder release,
caller cancellation, aggregate deadline, lock timeout, deadlock, or
service error; barrier/update use the same bounded context. No new
goroutine or join edge exists. |
| Q3: what can grow? | Targets and proof state are bounded by schema
index count; there is one deadline, one barrier attempt, one retry, and
one fixed-cardinality metric sample per admitted run. |

## Performance and operational risk

The intended complexity change is:

```text
before: O(input batches * UNIQUE targets * encoded keys)
after:  O(UNIQUE targets log targets) + one applied-logtail barrier + one physical recompile
```

Safeguards:

- the ordinary non-LOAD top-level gate remains about 1.76 ns/op, 0 B/op,
0 allocs/op on Apple M4;
- the complete eligible-plan classifier remains about 1.69 us/op, 1120
B/op, 14 allocs/op, once per fresh candidate LOAD;
- retry proof lookup is binary over sorted physical IDs;
- ordinary `doLock` callers pass a zero scalar deadline; no
`LockOptions` growth, wrapper call around the existing non-inlined lock
function, allocation, goroutine, log, or retained state was added;
- `time.Now()` is not evaluated when neither the existing session
timeout nor the promotion deadline is present;
- the barrier metric has four pre-bound outcomes and fixed buckets;
there is no dynamic label or log-amplification path.

These checks bound implementation overhead only. Eligible LOAD still
holds base and hidden domains through barrier, retry, execution, and
commit, and pays one barrier plus recompile. Exact-main/final-head
endpoint runs must decide whether that tradeoff is worthwhile.

## Why review kept finding new blockers, and what changed

The repeated `Request changes` loop was a review-process failure, not
one endlessly recurring defect:

1. implementation started before causal evidence and owner-approved
design;
2. each pass repaired the latest counterexample and declared convergence
without freezing the complete decision surface;
3. the design promised a broader matrix than committed tests actually
proved;
4. code correctness, causal/performance evidence, and owner acceptance
were mixed together, so an external pending gate repeatedly appeared as
a new code defect.

V8 separates three gates: deterministic code closure, causal/endpoint
evidence, and owner acceptance. A missing code oracle requires code/test
change; pending scale evidence or approval does not. Conversely, local
green tests are not promoted into causal proof.

Concrete issues found and resolved or explicitly removed from scope:

- replaced the early planner/protobuf/FK-routing mechanism with a
compiler-local, no-wire-change design;
- rejected non-total FLOAT/DOUBLE key ranges;
- normalized target ordering and static-NULL UNIQUE handling;
- removed explicit transaction admission, redundant planner cache
mutation, and a lock-held metric/fence design;
- reused the existing close-aware v39 TN barrier instead of introducing
a future-HLC/client protocol;
- bound physical retry/source state to the installed snapshot and kept
the canonical plan immutable;
- aligned stated tests with reachable feature-owned contracts instead of
duplicating all generic lockservice fault matrices;
- fixed the final v7 gap where one context existed locally but each
remote lock RPC recomputed its deadline;
- fixed incomplete Apache headers that caused SCA failure.

## Exact-head local validation

On `f48843c9e2` / base `07fe9a69c6`:

- normal affected packages passed: `./pkg/sql/compile`,
`./pkg/sql/colexec/lockop`, `./pkg/util/metric/v2`;
- full owning-package race passed for compile and lockop;
- measured focused race stress used `B=30s`, `N=100` and passed for both
real-lockservice success/reentry and
cancellation/deadline/prefix-release tests;
- `go vet` passed for all three affected packages;
- `license-eye header check`: 5906 checked, 4840 valid, 0 invalid, 1066
ignored;
- `license-eye dep check` passed;
- `git diff --check` passed.

The isolated macOS worktree reused unchanged, platform-matched CGo and
third-party artifacts from the primary checkout for these tests; no CGo
source changes are in this PR. The reusable platform/provenance guard is
submitted separately as #27852.

## Remaining merge gates and residual risks

1. **Causality:** alternating #26706 parent/merge 100M A/B with same-run
no-index control and aligned lock/mutex evidence. If that boundary does
not reproduce, abandon this mechanism and bisect the original range.
2. **Endpoint performance:** alternate exact current `main` and exact
final head for at least three successful 100M runs per indexed shape
plus no-index control; require >=80% recovery of the normalized
regression gap and <=15% no-index median regression, then one 1B
confirmation.
3. **Availability/deadlock:** direct/internal writers to hidden physical
tables can wait behind a long full-domain LOAD lock and can add a
multi-table deadlock edge. The real conflict/release contract is tested,
but scale/cycle observations and lockservice-owner acceptance remain
required.
4. **Optimistic writers:** they do not honor the promoted pessimistic
lock. This PR preserves exact-main TN conflict/retry behavior and does
not claim stronger exclusion.
5. **Lock retention:** successful LOAD retains base and hidden locks
through retry, source initialization, execution, and commit; terminal
failure relies on existing whole-transaction rollback.
6. **Shared prerequisite:** the design depends on #27842's v39
TN-ordered barrier and fails closed for older protocol/capability
states.
7. **Mandatory exact-head review:** one SQL planner/compile owner and
one lockservice owner must approve the same final commit. The existing
`fengttt` approval is on the pre-v8 head and does not close this gate.
@ck89119 ck89119 mentioned this pull request Sep 3, 2026
1 of 7 tasks
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
## What changed

Replace the fixed HLC uncertainty wait used by authentication with a
generic,
TN-ordered logtail read barrier:

- place a barrier marker in the same TN FIFO as committed transactions
and
  return the exact published frontier;
- order logtail updates, forced filtered progress, and the barrier
response
  through the existing per-session stream;
- correlate concurrent barrier requests and wait for the normal CN apply
  pipeline before returning;
- use the generic engine capability from authentication without adding
  catalog-specific TN logic;
- fail closed on cancellation, reconnect, missing capabilities, queue
  pressure, and regressing apply timestamps;
- introduce the wire contract at MORPC v39; protocol <=38 retains the
legacy
  HLC fence during rolling upgrades.

The invariant is:

```text
commit completes before barrier begins
  => commit precedes TN marker
  => its logtail precedes the barrier response
  => CN apply reaches the exact frontier before the barrier returns
```

The full ordering, ownership, upgrade, and failure model is documented
in
`docs/design/authentication_catalog_freshness.md`.

## Systemic overload and hot-path fixes

The final design bounds barrier work across every shared stage instead
of only
making queue insertion cancellable:

- each CN retains at most 100 in-flight request correlations;
- the logtail server admits at most 100 barriers globally and keeps each
slot
  owned through TN processing, notifier ordering, and response hand-off;
- the manager independently caps markers at 100, one queue batch, so
barriers
  cannot fill the 10,000-entry commit FIFO;
- shutdown drains queued barrier ownership, while cancellation before
and
  after TN admission has distinct, exactly-once cleanup;
- adjacent markers at one FIFO frontier are completed together without
empty
  collection segments.

Normal commit traffic keeps the original direct `SafeQueue.Enqueue`
channel
send. Context checks/selects exist only in `EnqueueWithContext`;
transaction-
only manager batches perform one atomic pending-barrier load and do not
scan or
type-assert the batch twice.

## Root cause and performance

matrixorigin#27763 fenced every login beyond the HLC uncertainty upper bound. With
the
default 500ms max clock offset, each fresh connection paid about 500ms
even
when there was no real logtail lag. TPCH reconnects for each query, so
22
queries accumulated about 11 seconds, matching matrixorigin#27834's regression.

Initial candidate validation on `10.222.1.55` (exact commit
`14c0181070`):

| Check | Result |
|---|---:|
| main fresh login | about 513-527ms each |
| main, 22 sequential fresh connections | 11.415s |
| candidate, 30 sequential fresh connections | 649ms total, 21ms
average, p95 31ms |
| password mutation followed immediately by login | 20/20 new password
accepted; 0 stale old-password accepts |
| role revoke/grant followed immediately by authorization | 0 stale
revoke accepts; 20/20 regrants visible |

On the final code, the focused `SafeQueue` benchmark (Apple M4, 1s x 3,
0 alloc/op) changed from a median 76.95ns/op at the prior PR head to
58.59ns/op after restoring the background hot path, about 24% lower.

Actual TPCH-10G must still be rerun on the final head as a merge
acceptance
gate; synthetic connection timing is supporting evidence, not a
replacement.

## Validation

- rebased onto `main@f779dff`; historical main-merge commits were
removed, the three logical commits were preserved, and range-diff is
patch-equivalent except for the required v38-to-v39 capability
allocation;
- focused rebase validation passed for the v38 legacy authentication
fallback, v39 TN-ordered barrier, fail-closed/cancellation paths, and
the independent v38 temporary-table migration contract;
- CGo-aware normal tests passed for logstore/sm, TAE logtail
manager/service,
  disttae, engine/frontend, and status;
- race tests passed three times for logstore/sm, TAE logtail
manager/service;
- the new shared-cluster acceptance test ran three times: CN-0
repeatedly
changes credentials and revokes/grants an explicit role, while each
fresh
  login is immediately routed to CN-1 with no sleep or retry;
- deterministic tests cover CN/server/manager admission bounds, caller
cancel,
  post-admission cancel, queue/send failure, shutdown Drain, response
  correlation, ordered progress, and slot reuse;
- `git diff --check` passes; tests are additive and do not reduce
coverage or
  assertions.

Fixes matrixorigin#27834
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
Fixes matrixorigin#27833.
Related to matrixorigin#27718 and matrixorigin#26087.

Rebased onto `main@fcc8ff3`, which contains the merged TN-ordered
logtail barrier from matrixorigin#27842. The complete feature-only range is now
`fcc8ff3b03..66e95cf`; no dependency merge history remains in this
PR.

Design:
[`docs/design/feature_quota_admission.md`](https://github.com/matrixorigin/matrixone/blob/codex/issue27833-feature-limit-barrier/docs/design/feature_quota_admission.md)
(**Review required**).

## Why

Feature quota is admission-control state, but `CREATE SNAPSHOT` and
`DATA BRANCH CREATE` could read a stale CN catalog snapshot immediately
after an administrator committed `mo_feature_limit_upsert` on another
CN. A stale lower value falsely rejects an allowed operation; a stale
higher value can persist an object after the feature was disabled or
reduced. Concurrent creators could also count the same pre-publication
metadata and exceed a finite limit.

Required contract:

- a registry/quota commit completed before an operation starts
constrains it on every CN;
- finite admission and metadata publication are one serialized
transaction;
- the check does not advance or downgrade a caller's fixed SI
transaction;
- cancellation, missing dependencies, and freshness failures fail
closed.

## What changed

- Establish a TN-ordered logtail barrier before reading feature
registry/quota state, then advance the owning RC workspace to the
applied frontier.
- For finite branch quota, retain the account quota-row lock, establish
a second frontier after any lock wait, re-read the locked quota, count
usage, and publish metadata in the same transaction.
- Preserve explicit SI semantics with an independent short
pessimistic-RC control transaction. Disabled rejects, unlimited
proceeds, and finite quota asks the caller to retry outside the active
transaction.
- Preserve rolling-upgrade compatibility: protocol v38 and below use the
HLC uncertainty fallback; v39 uses the TN-ordered barrier.
- Fail closed for barrier, logtail, workspace, transaction, and
typed-nil executor failures.
- Add a bounded two-CN branch acceptance sequence on one pre-opened CN-B
connection: `1 -> 0 -> -1 -> 0 -> 1`, with no sleep or retry between
CN-A's committed quota mutation and admission.
- Reuse the existing shared two-CN cluster; no extra embedded-cluster
startup was added.
- Make catalog-readiness polling synchronous and context-bounded,
preserve the last SQL error, close partial executor results, and avoid
calling `testing.T` from a polling worker goroutine.
- Strengthen unlimited snapshot and SI snapshot-preservation assertions.

## Performance and risk

- Ordinary SQL and authentication add no new barrier, lock, scan,
allocation, or goroutine from this feature change.
- Snapshot create: one v39 barrier and the existing lineage-owner lock.
- Disabled/unlimited branch create: one v39 barrier and no quota lock.
- Finite branch create: two v39 barriers and serialization only on that
target account's quota row; different accounts remain concurrent.
- The v38 fallback is correct but can wait about one `MaxOffset` for
disabled/unlimited and two for finite branch admission.
- Every wait is request-context-bound; topology readiness has one
30-second total bound and preserves the causal probe error.

The merged matrixorigin#27842 queue/RPC hot path is byte-identical to `main`. On
this final tree, `BenchmarkSafeQueueEnqueue` (Apple M4, 1s x3) reports 0
alloc/op; the background path is 72.08/65.79/65.25 ns/op (median 65.79
ns/op), and the request-context path is 93.54/109.6/87.28 ns/op. TPCH
acceptance belongs to the already-merged barrier change; this
feature-only delta does not add work to TPCH query execution.

## Validation

Exact head `66e95cf25b` on `main@fcc8ff3`:

- 17 selected frontend quota/authentication/protocol-boundary test
functions, including all nested fail-closed cases: PASS (`pkg/frontend`,
1.067s).
- `BenchmarkSafeQueueEnqueue`, background and request-context paths, 1s
x3: PASS, 0 alloc/op.
- `git diff --check origin/main...HEAD`: PASS.
- `git range-diff` against the pre-rebase feature commit:
patch-equivalent.
- Production and test trees are byte-identical to the previously
validated matrixorigin#27844 head; the rebase changed ancestry and the two design
clarifications only.

Semantically reused because the relevant code, tests, build mode,
topology, and current-main dependency tree are unchanged:

- `TestIssue26087ConcurrentDataBranchQuota`,
`TestIssue27718ConcurrentSnapshotQuota`, and
`TestWaitForCatalogVisibilityPreservesProbeError`: PASS on the shared
two-CN cluster (15.310s on the pre-rebase identical tree).
- v38 temporary-table migration compatibility tests across
frontend/proxy.
- normal and focused race evidence for the TN queue, manager,
service/RPC correlation, cancellation, CN consumer apply, and
authentication barrier paths from merged matrixorigin#27842.
- two-CN authentication acceptance and dependency SCA validation from
merged matrixorigin#27842.

Fresh CI was triggered by the force-rebase and was not awaited.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…rigin#27814)

Fixes matrixorigin#27775

> [!IMPORTANT]
> **Draft status on exact head `f48843c9e2`, rebased on `main`
`07fe9a69c6`: deterministic implementation/code closure is complete. The
causal A/B, 100M/1B endpoint evidence, and exact-head SQL/compile plus
lockservice owner approvals are still required. Do not merge or call
matrixorigin#27775 fixed from local tests.**

Design: `docs/design/load_data_unique_index_locking.md`, revision v8.

## Problem and evidence boundary

The reported 100M/1B indexed `LOAD DATA` regression correlates with
hidden-UNIQUE per-batch lock encoding/submission, lock coarsening,
higher mutex delay, and lower CPU utilization. The no-index control is
comparatively stable.

This is still a hypothesis, not proven causality. The exact matrixorigin#26706
parent/merge A/B (`6742f958d466` vs `35db232dfc3b`) has not been run.
The earlier 5M experiment changed the normalized indexed/no-index ratio
by only about 2.5%, so it is mechanism evidence, not proof that matrixorigin#27775
is fixed. Implementation was explicitly requested before that external
gate; the PR therefore remains Draft.

## Current v8 design and implementation

Only a positively identified large modern `LOAD DATA` can qualify:

- fresh physical generation zero, retry enabled, non-internal and
non-prepared;
- statement-owned autocommit pessimistic RC (`Autocommit=true`,
`ByBegin=false`);
- finite effective input estimate `Cost*Rowsize >= 1 GiB`, uncompressed
CSV/JSONLINE remote source;
- one ordinary non-FK/non-partitioned/non-temporary user base table;
- synchronous default/BTREE indexes with at least one regular UNIQUE
hidden table;
- v39 protocol and a real underlying `engine.LogtailReadBarrier`
capability;
- authoritative base/hidden PK types whose lockop table range covers the
complete physical keyspace.

Missing, contradictory, duplicated, unsupported, reused, or ambiguous
state fails closed to exact `main` behavior. FLOAT/DOUBLE remain
ineligible because the current finite table-range endpoints do not cover
infinities and every NaN payload. Real production shapes such as a
`uint32` base PK and binary-`varchar` composite hidden PK are admitted.

The canonical logical plan is never mutated. Before source
initialization, generation zero:

1. acquires the existing metadata/general and base full-domain locks;
2. acquires an Exclusive full-domain lock for every promotable hidden
UNIQUE table, sorted by physical table ID;
3. invokes the existing v39 TN-ordered logtail read barrier;
4. advances the same pessimistic-RC transaction snapshot strictly beyond
the applied frontier; and
5. returns one ordinary physical retry.

The retry validates an exact coordinator-local proof: transaction ID,
logical plan identity, physical generation, installed snapshot,
frontier, and target value. It filters only covered hidden row targets
from a local `LockOp` copy. Logical rebuild, reused generation,
capability/protocol mismatch, or proof mismatch permanently disables the
optimization for that `Compile.Run`.

No protobuf/wire/catalog/durable-state change, planner cache policy,
generic lock ordering, goroutine, channel, or production log site is
introduced.

## Correctness and unhappy-path closure

- The promotion creates one bounded context: `min(lock_wait_timeout,
120s, caller deadline)`.
- That context's **absolute deadline** is copied into every lock RPC and
clamped by any shorter session timeout. Remote owners therefore see the
same authoritative deadline; target N cannot restart the budget consumed
by targets 1..N-1.
- Caller cancellation/deadline is preserved. Only expiry of the internal
aggregate budget maps to lock timeout.
- Hidden-lock, barrier, snapshot-update, capability, protocol, or proof
failure publishes no proof and never initializes the source.
- A successful lock wait may refresh the transaction snapshot. The
narrow helper suppresses only the incomplete ordinary retry; the
stronger common barrier still runs before proof publication. Definition
changes keep the existing retry behavior.
- Locks remain transaction/lockservice-owned. Compiler cancellation
stops the wait but does not unlock a partially acquired prefix behind
the transaction owner's back. Existing terminal autocommit rollback
releases the whole transaction exactly once.
- A real two-target test proves target 1 is owned while target 2 waits,
cancellation returns, no barrier runs, rollback releases target 1, and a
FastFail point contender then succeeds.
- A real binary-`varchar` full-range test proves an interior Exclusive
writer waits, the fenced retry is reentrant with no second barrier, and
transaction rollback lets the writer proceed.
- Admission tests cover the positive implicit-autocommit pessimistic-RC
case and reject `BEGIN`, `autocommit=0`, SI, optimistic, mirror,
aborted, and missing-ID transactions.

Lifecycle audit:

| Question | Closure |
| --- | --- |
| Q1: who owns cleanup? | The transaction/lockservice owns every
acquired lock; compiler owns only schema-bounded proof metadata and
disables/clears it on failure/rebuild. |
| Q2: what can wait? | Each target wait ends through holder release,
caller cancellation, aggregate deadline, lock timeout, deadlock, or
service error; barrier/update use the same bounded context. No new
goroutine or join edge exists. |
| Q3: what can grow? | Targets and proof state are bounded by schema
index count; there is one deadline, one barrier attempt, one retry, and
one fixed-cardinality metric sample per admitted run. |

## Performance and operational risk

The intended complexity change is:

```text
before: O(input batches * UNIQUE targets * encoded keys)
after:  O(UNIQUE targets log targets) + one applied-logtail barrier + one physical recompile
```

Safeguards:

- the ordinary non-LOAD top-level gate remains about 1.76 ns/op, 0 B/op,
0 allocs/op on Apple M4;
- the complete eligible-plan classifier remains about 1.69 us/op, 1120
B/op, 14 allocs/op, once per fresh candidate LOAD;
- retry proof lookup is binary over sorted physical IDs;
- ordinary `doLock` callers pass a zero scalar deadline; no
`LockOptions` growth, wrapper call around the existing non-inlined lock
function, allocation, goroutine, log, or retained state was added;
- `time.Now()` is not evaluated when neither the existing session
timeout nor the promotion deadline is present;
- the barrier metric has four pre-bound outcomes and fixed buckets;
there is no dynamic label or log-amplification path.

These checks bound implementation overhead only. Eligible LOAD still
holds base and hidden domains through barrier, retry, execution, and
commit, and pays one barrier plus recompile. Exact-main/final-head
endpoint runs must decide whether that tradeoff is worthwhile.

## Why review kept finding new blockers, and what changed

The repeated `Request changes` loop was a review-process failure, not
one endlessly recurring defect:

1. implementation started before causal evidence and owner-approved
design;
2. each pass repaired the latest counterexample and declared convergence
without freezing the complete decision surface;
3. the design promised a broader matrix than committed tests actually
proved;
4. code correctness, causal/performance evidence, and owner acceptance
were mixed together, so an external pending gate repeatedly appeared as
a new code defect.

V8 separates three gates: deterministic code closure, causal/endpoint
evidence, and owner acceptance. A missing code oracle requires code/test
change; pending scale evidence or approval does not. Conversely, local
green tests are not promoted into causal proof.

Concrete issues found and resolved or explicitly removed from scope:

- replaced the early planner/protobuf/FK-routing mechanism with a
compiler-local, no-wire-change design;
- rejected non-total FLOAT/DOUBLE key ranges;
- normalized target ordering and static-NULL UNIQUE handling;
- removed explicit transaction admission, redundant planner cache
mutation, and a lock-held metric/fence design;
- reused the existing close-aware v39 TN barrier instead of introducing
a future-HLC/client protocol;
- bound physical retry/source state to the installed snapshot and kept
the canonical plan immutable;
- aligned stated tests with reachable feature-owned contracts instead of
duplicating all generic lockservice fault matrices;
- fixed the final v7 gap where one context existed locally but each
remote lock RPC recomputed its deadline;
- fixed incomplete Apache headers that caused SCA failure.

## Exact-head local validation

On `f48843c9e2` / base `07fe9a69c6`:

- normal affected packages passed: `./pkg/sql/compile`,
`./pkg/sql/colexec/lockop`, `./pkg/util/metric/v2`;
- full owning-package race passed for compile and lockop;
- measured focused race stress used `B=30s`, `N=100` and passed for both
real-lockservice success/reentry and
cancellation/deadline/prefix-release tests;
- `go vet` passed for all three affected packages;
- `license-eye header check`: 5906 checked, 4840 valid, 0 invalid, 1066
ignored;
- `license-eye dep check` passed;
- `git diff --check` passed.

The isolated macOS worktree reused unchanged, platform-matched CGo and
third-party artifacts from the primary checkout for these tests; no CGo
source changes are in this PR. The reusable platform/provenance guard is
submitted separately as matrixorigin#27852.

## Remaining merge gates and residual risks

1. **Causality:** alternating matrixorigin#26706 parent/merge 100M A/B with same-run
no-index control and aligned lock/mutex evidence. If that boundary does
not reproduce, abandon this mechanism and bisect the original range.
2. **Endpoint performance:** alternate exact current `main` and exact
final head for at least three successful 100M runs per indexed shape
plus no-index control; require >=80% recovery of the normalized
regression gap and <=15% no-index median regression, then one 1B
confirmation.
3. **Availability/deadlock:** direct/internal writers to hidden physical
tables can wait behind a long full-domain LOAD lock and can add a
multi-table deadlock edge. The real conflict/release contract is tested,
but scale/cycle observations and lockservice-owner acceptance remain
required.
4. **Optimistic writers:** they do not honor the promoted pessimistic
lock. This PR preserves exact-main TN conflict/retry behavior and does
not claim stronger exclusion.
5. **Lock retention:** successful LOAD retains base and hidden locks
through retry, source initialization, execution, and commit; terminal
failure relies on existing whole-transaction rollback.
6. **Shared prerequisite:** the design depends on matrixorigin#27842's v39
TN-ordered barrier and fails closed for older protocol/capability
states.
7. **Mandatory exact-head review:** one SQL planner/compile owner and
one lockservice owner must approve the same final commit. The existing
`fengttt` approval is on the pre-v8 head and does not close this gate.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
## What changed

Replace the fixed HLC uncertainty wait used by authentication with a
generic,
TN-ordered logtail read barrier:

- place a barrier marker in the same TN FIFO as committed transactions
and
  return the exact published frontier;
- order logtail updates, forced filtered progress, and the barrier
response
  through the existing per-session stream;
- correlate concurrent barrier requests and wait for the normal CN apply
  pipeline before returning;
- use the generic engine capability from authentication without adding
  catalog-specific TN logic;
- fail closed on cancellation, reconnect, missing capabilities, queue
  pressure, and regressing apply timestamps;
- introduce the wire contract at MORPC v39; protocol <=38 retains the
legacy
  HLC fence during rolling upgrades.

The invariant is:

```text
commit completes before barrier begins
  => commit precedes TN marker
  => its logtail precedes the barrier response
  => CN apply reaches the exact frontier before the barrier returns
```

The full ordering, ownership, upgrade, and failure model is documented
in
`docs/design/authentication_catalog_freshness.md`.

## Systemic overload and hot-path fixes

The final design bounds barrier work across every shared stage instead
of only
making queue insertion cancellable:

- each CN retains at most 100 in-flight request correlations;
- the logtail server admits at most 100 barriers globally and keeps each
slot
  owned through TN processing, notifier ordering, and response hand-off;
- the manager independently caps markers at 100, one queue batch, so
barriers
  cannot fill the 10,000-entry commit FIFO;
- shutdown drains queued barrier ownership, while cancellation before
and
  after TN admission has distinct, exactly-once cleanup;
- adjacent markers at one FIFO frontier are completed together without
empty
  collection segments.

Normal commit traffic keeps the original direct `SafeQueue.Enqueue`
channel
send. Context checks/selects exist only in `EnqueueWithContext`;
transaction-
only manager batches perform one atomic pending-barrier load and do not
scan or
type-assert the batch twice.

## Root cause and performance

matrixorigin#27763 fenced every login beyond the HLC uncertainty upper bound. With
the
default 500ms max clock offset, each fresh connection paid about 500ms
even
when there was no real logtail lag. TPCH reconnects for each query, so
22
queries accumulated about 11 seconds, matching matrixorigin#27834's regression.

Initial candidate validation on `10.222.1.55` (exact commit
`14c0181070`):

| Check | Result |
|---|---:|
| main fresh login | about 513-527ms each |
| main, 22 sequential fresh connections | 11.415s |
| candidate, 30 sequential fresh connections | 649ms total, 21ms
average, p95 31ms |
| password mutation followed immediately by login | 20/20 new password
accepted; 0 stale old-password accepts |
| role revoke/grant followed immediately by authorization | 0 stale
revoke accepts; 20/20 regrants visible |

On the final code, the focused `SafeQueue` benchmark (Apple M4, 1s x 3,
0 alloc/op) changed from a median 76.95ns/op at the prior PR head to
58.59ns/op after restoring the background hot path, about 24% lower.

Actual TPCH-10G must still be rerun on the final head as a merge
acceptance
gate; synthetic connection timing is supporting evidence, not a
replacement.

## Validation

- rebased onto `main@f779dff`; historical main-merge commits were
removed, the three logical commits were preserved, and range-diff is
patch-equivalent except for the required v38-to-v39 capability
allocation;
- focused rebase validation passed for the v38 legacy authentication
fallback, v39 TN-ordered barrier, fail-closed/cancellation paths, and
the independent v38 temporary-table migration contract;
- CGo-aware normal tests passed for logstore/sm, TAE logtail
manager/service,
  disttae, engine/frontend, and status;
- race tests passed three times for logstore/sm, TAE logtail
manager/service;
- the new shared-cluster acceptance test ran three times: CN-0
repeatedly
changes credentials and revokes/grants an explicit role, while each
fresh
  login is immediately routed to CN-1 with no sleep or retry;
- deterministic tests cover CN/server/manager admission bounds, caller
cancel,
  post-admission cancel, queue/send failure, shutdown Drain, response
  correlation, ordered progress, and slot reuse;
- `git diff --check` passes; tests are additive and do not reduce
coverage or
  assertions.

Fixes matrixorigin#27834
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
Fixes matrixorigin#27833.
Related to matrixorigin#27718 and matrixorigin#26087.

Rebased onto `main@fcc8ff3`, which contains the merged TN-ordered
logtail barrier from matrixorigin#27842. The complete feature-only range is now
`fcc8ff3b03..66e95cf`; no dependency merge history remains in this
PR.

Design:
[`docs/design/feature_quota_admission.md`](https://github.com/matrixorigin/matrixone/blob/codex/issue27833-feature-limit-barrier/docs/design/feature_quota_admission.md)
(**Review required**).

## Why

Feature quota is admission-control state, but `CREATE SNAPSHOT` and
`DATA BRANCH CREATE` could read a stale CN catalog snapshot immediately
after an administrator committed `mo_feature_limit_upsert` on another
CN. A stale lower value falsely rejects an allowed operation; a stale
higher value can persist an object after the feature was disabled or
reduced. Concurrent creators could also count the same pre-publication
metadata and exceed a finite limit.

Required contract:

- a registry/quota commit completed before an operation starts
constrains it on every CN;
- finite admission and metadata publication are one serialized
transaction;
- the check does not advance or downgrade a caller's fixed SI
transaction;
- cancellation, missing dependencies, and freshness failures fail
closed.

## What changed

- Establish a TN-ordered logtail barrier before reading feature
registry/quota state, then advance the owning RC workspace to the
applied frontier.
- For finite branch quota, retain the account quota-row lock, establish
a second frontier after any lock wait, re-read the locked quota, count
usage, and publish metadata in the same transaction.
- Preserve explicit SI semantics with an independent short
pessimistic-RC control transaction. Disabled rejects, unlimited
proceeds, and finite quota asks the caller to retry outside the active
transaction.
- Preserve rolling-upgrade compatibility: protocol v38 and below use the
HLC uncertainty fallback; v39 uses the TN-ordered barrier.
- Fail closed for barrier, logtail, workspace, transaction, and
typed-nil executor failures.
- Add a bounded two-CN branch acceptance sequence on one pre-opened CN-B
connection: `1 -> 0 -> -1 -> 0 -> 1`, with no sleep or retry between
CN-A's committed quota mutation and admission.
- Reuse the existing shared two-CN cluster; no extra embedded-cluster
startup was added.
- Make catalog-readiness polling synchronous and context-bounded,
preserve the last SQL error, close partial executor results, and avoid
calling `testing.T` from a polling worker goroutine.
- Strengthen unlimited snapshot and SI snapshot-preservation assertions.

## Performance and risk

- Ordinary SQL and authentication add no new barrier, lock, scan,
allocation, or goroutine from this feature change.
- Snapshot create: one v39 barrier and the existing lineage-owner lock.
- Disabled/unlimited branch create: one v39 barrier and no quota lock.
- Finite branch create: two v39 barriers and serialization only on that
target account's quota row; different accounts remain concurrent.
- The v38 fallback is correct but can wait about one `MaxOffset` for
disabled/unlimited and two for finite branch admission.
- Every wait is request-context-bound; topology readiness has one
30-second total bound and preserves the causal probe error.

The merged matrixorigin#27842 queue/RPC hot path is byte-identical to `main`. On
this final tree, `BenchmarkSafeQueueEnqueue` (Apple M4, 1s x3) reports 0
alloc/op; the background path is 72.08/65.79/65.25 ns/op (median 65.79
ns/op), and the request-context path is 93.54/109.6/87.28 ns/op. TPCH
acceptance belongs to the already-merged barrier change; this
feature-only delta does not add work to TPCH query execution.

## Validation

Exact head `66e95cf25b` on `main@fcc8ff3`:

- 17 selected frontend quota/authentication/protocol-boundary test
functions, including all nested fail-closed cases: PASS (`pkg/frontend`,
1.067s).
- `BenchmarkSafeQueueEnqueue`, background and request-context paths, 1s
x3: PASS, 0 alloc/op.
- `git diff --check origin/main...HEAD`: PASS.
- `git range-diff` against the pre-rebase feature commit:
patch-equivalent.
- Production and test trees are byte-identical to the previously
validated matrixorigin#27844 head; the rebase changed ancestry and the two design
clarifications only.

Semantically reused because the relevant code, tests, build mode,
topology, and current-main dependency tree are unchanged:

- `TestIssue26087ConcurrentDataBranchQuota`,
`TestIssue27718ConcurrentSnapshotQuota`, and
`TestWaitForCatalogVisibilityPreservesProbeError`: PASS on the shared
two-CN cluster (15.310s on the pre-rebase identical tree).
- v38 temporary-table migration compatibility tests across
frontend/proxy.
- normal and focused race evidence for the TN queue, manager,
service/RPC correlation, cancellation, CN consumer apply, and
authentication barrier paths from merged matrixorigin#27842.
- two-CN authentication acceptance and dependency SCA validation from
merged matrixorigin#27842.

Fresh CI was triggered by the force-rebase and was not awaited.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…rigin#27814)

Fixes matrixorigin#27775

> [!IMPORTANT]
> **Draft status on exact head `f48843c9e2`, rebased on `main`
`07fe9a69c6`: deterministic implementation/code closure is complete. The
causal A/B, 100M/1B endpoint evidence, and exact-head SQL/compile plus
lockservice owner approvals are still required. Do not merge or call
matrixorigin#27775 fixed from local tests.**

Design: `docs/design/load_data_unique_index_locking.md`, revision v8.

## Problem and evidence boundary

The reported 100M/1B indexed `LOAD DATA` regression correlates with
hidden-UNIQUE per-batch lock encoding/submission, lock coarsening,
higher mutex delay, and lower CPU utilization. The no-index control is
comparatively stable.

This is still a hypothesis, not proven causality. The exact matrixorigin#26706
parent/merge A/B (`6742f958d466` vs `35db232dfc3b`) has not been run.
The earlier 5M experiment changed the normalized indexed/no-index ratio
by only about 2.5%, so it is mechanism evidence, not proof that matrixorigin#27775
is fixed. Implementation was explicitly requested before that external
gate; the PR therefore remains Draft.

## Current v8 design and implementation

Only a positively identified large modern `LOAD DATA` can qualify:

- fresh physical generation zero, retry enabled, non-internal and
non-prepared;
- statement-owned autocommit pessimistic RC (`Autocommit=true`,
`ByBegin=false`);
- finite effective input estimate `Cost*Rowsize >= 1 GiB`, uncompressed
CSV/JSONLINE remote source;
- one ordinary non-FK/non-partitioned/non-temporary user base table;
- synchronous default/BTREE indexes with at least one regular UNIQUE
hidden table;
- v39 protocol and a real underlying `engine.LogtailReadBarrier`
capability;
- authoritative base/hidden PK types whose lockop table range covers the
complete physical keyspace.

Missing, contradictory, duplicated, unsupported, reused, or ambiguous
state fails closed to exact `main` behavior. FLOAT/DOUBLE remain
ineligible because the current finite table-range endpoints do not cover
infinities and every NaN payload. Real production shapes such as a
`uint32` base PK and binary-`varchar` composite hidden PK are admitted.

The canonical logical plan is never mutated. Before source
initialization, generation zero:

1. acquires the existing metadata/general and base full-domain locks;
2. acquires an Exclusive full-domain lock for every promotable hidden
UNIQUE table, sorted by physical table ID;
3. invokes the existing v39 TN-ordered logtail read barrier;
4. advances the same pessimistic-RC transaction snapshot strictly beyond
the applied frontier; and
5. returns one ordinary physical retry.

The retry validates an exact coordinator-local proof: transaction ID,
logical plan identity, physical generation, installed snapshot,
frontier, and target value. It filters only covered hidden row targets
from a local `LockOp` copy. Logical rebuild, reused generation,
capability/protocol mismatch, or proof mismatch permanently disables the
optimization for that `Compile.Run`.

No protobuf/wire/catalog/durable-state change, planner cache policy,
generic lock ordering, goroutine, channel, or production log site is
introduced.

## Correctness and unhappy-path closure

- The promotion creates one bounded context: `min(lock_wait_timeout,
120s, caller deadline)`.
- That context's **absolute deadline** is copied into every lock RPC and
clamped by any shorter session timeout. Remote owners therefore see the
same authoritative deadline; target N cannot restart the budget consumed
by targets 1..N-1.
- Caller cancellation/deadline is preserved. Only expiry of the internal
aggregate budget maps to lock timeout.
- Hidden-lock, barrier, snapshot-update, capability, protocol, or proof
failure publishes no proof and never initializes the source.
- A successful lock wait may refresh the transaction snapshot. The
narrow helper suppresses only the incomplete ordinary retry; the
stronger common barrier still runs before proof publication. Definition
changes keep the existing retry behavior.
- Locks remain transaction/lockservice-owned. Compiler cancellation
stops the wait but does not unlock a partially acquired prefix behind
the transaction owner's back. Existing terminal autocommit rollback
releases the whole transaction exactly once.
- A real two-target test proves target 1 is owned while target 2 waits,
cancellation returns, no barrier runs, rollback releases target 1, and a
FastFail point contender then succeeds.
- A real binary-`varchar` full-range test proves an interior Exclusive
writer waits, the fenced retry is reentrant with no second barrier, and
transaction rollback lets the writer proceed.
- Admission tests cover the positive implicit-autocommit pessimistic-RC
case and reject `BEGIN`, `autocommit=0`, SI, optimistic, mirror,
aborted, and missing-ID transactions.

Lifecycle audit:

| Question | Closure |
| --- | --- |
| Q1: who owns cleanup? | The transaction/lockservice owns every
acquired lock; compiler owns only schema-bounded proof metadata and
disables/clears it on failure/rebuild. |
| Q2: what can wait? | Each target wait ends through holder release,
caller cancellation, aggregate deadline, lock timeout, deadlock, or
service error; barrier/update use the same bounded context. No new
goroutine or join edge exists. |
| Q3: what can grow? | Targets and proof state are bounded by schema
index count; there is one deadline, one barrier attempt, one retry, and
one fixed-cardinality metric sample per admitted run. |

## Performance and operational risk

The intended complexity change is:

```text
before: O(input batches * UNIQUE targets * encoded keys)
after:  O(UNIQUE targets log targets) + one applied-logtail barrier + one physical recompile
```

Safeguards:

- the ordinary non-LOAD top-level gate remains about 1.76 ns/op, 0 B/op,
0 allocs/op on Apple M4;
- the complete eligible-plan classifier remains about 1.69 us/op, 1120
B/op, 14 allocs/op, once per fresh candidate LOAD;
- retry proof lookup is binary over sorted physical IDs;
- ordinary `doLock` callers pass a zero scalar deadline; no
`LockOptions` growth, wrapper call around the existing non-inlined lock
function, allocation, goroutine, log, or retained state was added;
- `time.Now()` is not evaluated when neither the existing session
timeout nor the promotion deadline is present;
- the barrier metric has four pre-bound outcomes and fixed buckets;
there is no dynamic label or log-amplification path.

These checks bound implementation overhead only. Eligible LOAD still
holds base and hidden domains through barrier, retry, execution, and
commit, and pays one barrier plus recompile. Exact-main/final-head
endpoint runs must decide whether that tradeoff is worthwhile.

## Why review kept finding new blockers, and what changed

The repeated `Request changes` loop was a review-process failure, not
one endlessly recurring defect:

1. implementation started before causal evidence and owner-approved
design;
2. each pass repaired the latest counterexample and declared convergence
without freezing the complete decision surface;
3. the design promised a broader matrix than committed tests actually
proved;
4. code correctness, causal/performance evidence, and owner acceptance
were mixed together, so an external pending gate repeatedly appeared as
a new code defect.

V8 separates three gates: deterministic code closure, causal/endpoint
evidence, and owner acceptance. A missing code oracle requires code/test
change; pending scale evidence or approval does not. Conversely, local
green tests are not promoted into causal proof.

Concrete issues found and resolved or explicitly removed from scope:

- replaced the early planner/protobuf/FK-routing mechanism with a
compiler-local, no-wire-change design;
- rejected non-total FLOAT/DOUBLE key ranges;
- normalized target ordering and static-NULL UNIQUE handling;
- removed explicit transaction admission, redundant planner cache
mutation, and a lock-held metric/fence design;
- reused the existing close-aware v39 TN barrier instead of introducing
a future-HLC/client protocol;
- bound physical retry/source state to the installed snapshot and kept
the canonical plan immutable;
- aligned stated tests with reachable feature-owned contracts instead of
duplicating all generic lockservice fault matrices;
- fixed the final v7 gap where one context existed locally but each
remote lock RPC recomputed its deadline;
- fixed incomplete Apache headers that caused SCA failure.

## Exact-head local validation

On `f48843c9e2` / base `07fe9a69c6`:

- normal affected packages passed: `./pkg/sql/compile`,
`./pkg/sql/colexec/lockop`, `./pkg/util/metric/v2`;
- full owning-package race passed for compile and lockop;
- measured focused race stress used `B=30s`, `N=100` and passed for both
real-lockservice success/reentry and
cancellation/deadline/prefix-release tests;
- `go vet` passed for all three affected packages;
- `license-eye header check`: 5906 checked, 4840 valid, 0 invalid, 1066
ignored;
- `license-eye dep check` passed;
- `git diff --check` passed.

The isolated macOS worktree reused unchanged, platform-matched CGo and
third-party artifacts from the primary checkout for these tests; no CGo
source changes are in this PR. The reusable platform/provenance guard is
submitted separately as matrixorigin#27852.

## Remaining merge gates and residual risks

1. **Causality:** alternating matrixorigin#26706 parent/merge 100M A/B with same-run
no-index control and aligned lock/mutex evidence. If that boundary does
not reproduce, abandon this mechanism and bisect the original range.
2. **Endpoint performance:** alternate exact current `main` and exact
final head for at least three successful 100M runs per indexed shape
plus no-index control; require >=80% recovery of the normalized
regression gap and <=15% no-index median regression, then one 1B
confirmation.
3. **Availability/deadlock:** direct/internal writers to hidden physical
tables can wait behind a long full-domain LOAD lock and can add a
multi-table deadlock edge. The real conflict/release contract is tested,
but scale/cycle observations and lockservice-owner acceptance remain
required.
4. **Optimistic writers:** they do not honor the promoted pessimistic
lock. This PR preserves exact-main TN conflict/retry behavior and does
not claim stronger exclusion.
5. **Lock retention:** successful LOAD retains base and hidden locks
through retry, source initialization, execution, and commit; terminal
failure relies on existing whole-transaction rollback.
6. **Shared prerequisite:** the design depends on matrixorigin#27842's v39
TN-ordered barrier and fails closed for older protocol/capability
states.
7. **Mandatory exact-head review:** one SQL planner/compile owner and
one lockservice owner must approve the same final commit. The existing
`fengttt` approval is on the pre-v8 head and does not close this gate.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
## What changed

Replace the fixed HLC uncertainty wait used by authentication with a
generic,
TN-ordered logtail read barrier:

- place a barrier marker in the same TN FIFO as committed transactions
and
  return the exact published frontier;
- order logtail updates, forced filtered progress, and the barrier
response
  through the existing per-session stream;
- correlate concurrent barrier requests and wait for the normal CN apply
  pipeline before returning;
- use the generic engine capability from authentication without adding
  catalog-specific TN logic;
- fail closed on cancellation, reconnect, missing capabilities, queue
  pressure, and regressing apply timestamps;
- introduce the wire contract at MORPC v39; protocol <=38 retains the
legacy
  HLC fence during rolling upgrades.

The invariant is:

```text
commit completes before barrier begins
  => commit precedes TN marker
  => its logtail precedes the barrier response
  => CN apply reaches the exact frontier before the barrier returns
```

The full ordering, ownership, upgrade, and failure model is documented
in
`docs/design/authentication_catalog_freshness.md`.

## Systemic overload and hot-path fixes

The final design bounds barrier work across every shared stage instead
of only
making queue insertion cancellable:

- each CN retains at most 100 in-flight request correlations;
- the logtail server admits at most 100 barriers globally and keeps each
slot
  owned through TN processing, notifier ordering, and response hand-off;
- the manager independently caps markers at 100, one queue batch, so
barriers
  cannot fill the 10,000-entry commit FIFO;
- shutdown drains queued barrier ownership, while cancellation before
and
  after TN admission has distinct, exactly-once cleanup;
- adjacent markers at one FIFO frontier are completed together without
empty
  collection segments.

Normal commit traffic keeps the original direct `SafeQueue.Enqueue`
channel
send. Context checks/selects exist only in `EnqueueWithContext`;
transaction-
only manager batches perform one atomic pending-barrier load and do not
scan or
type-assert the batch twice.

## Root cause and performance

matrixorigin#27763 fenced every login beyond the HLC uncertainty upper bound. With
the
default 500ms max clock offset, each fresh connection paid about 500ms
even
when there was no real logtail lag. TPCH reconnects for each query, so
22
queries accumulated about 11 seconds, matching matrixorigin#27834's regression.

Initial candidate validation on `10.222.1.55` (exact commit
`14c0181070`):

| Check | Result |
|---|---:|
| main fresh login | about 513-527ms each |
| main, 22 sequential fresh connections | 11.415s |
| candidate, 30 sequential fresh connections | 649ms total, 21ms
average, p95 31ms |
| password mutation followed immediately by login | 20/20 new password
accepted; 0 stale old-password accepts |
| role revoke/grant followed immediately by authorization | 0 stale
revoke accepts; 20/20 regrants visible |

On the final code, the focused `SafeQueue` benchmark (Apple M4, 1s x 3,
0 alloc/op) changed from a median 76.95ns/op at the prior PR head to
58.59ns/op after restoring the background hot path, about 24% lower.

Actual TPCH-10G must still be rerun on the final head as a merge
acceptance
gate; synthetic connection timing is supporting evidence, not a
replacement.

## Validation

- rebased onto `main@f779dff`; historical main-merge commits were
removed, the three logical commits were preserved, and range-diff is
patch-equivalent except for the required v38-to-v39 capability
allocation;
- focused rebase validation passed for the v38 legacy authentication
fallback, v39 TN-ordered barrier, fail-closed/cancellation paths, and
the independent v38 temporary-table migration contract;
- CGo-aware normal tests passed for logstore/sm, TAE logtail
manager/service,
  disttae, engine/frontend, and status;
- race tests passed three times for logstore/sm, TAE logtail
manager/service;
- the new shared-cluster acceptance test ran three times: CN-0
repeatedly
changes credentials and revokes/grants an explicit role, while each
fresh
  login is immediately routed to CN-1 with no sleep or retry;
- deterministic tests cover CN/server/manager admission bounds, caller
cancel,
  post-admission cancel, queue/send failure, shutdown Drain, response
  correlation, ordered progress, and slot reuse;
- `git diff --check` passes; tests are additive and do not reduce
coverage or
  assertions.

Fixes matrixorigin#27834
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
Fixes matrixorigin#27833.
Related to matrixorigin#27718 and matrixorigin#26087.

Rebased onto `main@fcc8ff3`, which contains the merged TN-ordered
logtail barrier from matrixorigin#27842. The complete feature-only range is now
`fcc8ff3b03..66e95cf`; no dependency merge history remains in this
PR.

Design:
[`docs/design/feature_quota_admission.md`](https://github.com/matrixorigin/matrixone/blob/codex/issue27833-feature-limit-barrier/docs/design/feature_quota_admission.md)
(**Review required**).

## Why

Feature quota is admission-control state, but `CREATE SNAPSHOT` and
`DATA BRANCH CREATE` could read a stale CN catalog snapshot immediately
after an administrator committed `mo_feature_limit_upsert` on another
CN. A stale lower value falsely rejects an allowed operation; a stale
higher value can persist an object after the feature was disabled or
reduced. Concurrent creators could also count the same pre-publication
metadata and exceed a finite limit.

Required contract:

- a registry/quota commit completed before an operation starts
constrains it on every CN;
- finite admission and metadata publication are one serialized
transaction;
- the check does not advance or downgrade a caller's fixed SI
transaction;
- cancellation, missing dependencies, and freshness failures fail
closed.

## What changed

- Establish a TN-ordered logtail barrier before reading feature
registry/quota state, then advance the owning RC workspace to the
applied frontier.
- For finite branch quota, retain the account quota-row lock, establish
a second frontier after any lock wait, re-read the locked quota, count
usage, and publish metadata in the same transaction.
- Preserve explicit SI semantics with an independent short
pessimistic-RC control transaction. Disabled rejects, unlimited
proceeds, and finite quota asks the caller to retry outside the active
transaction.
- Preserve rolling-upgrade compatibility: protocol v38 and below use the
HLC uncertainty fallback; v39 uses the TN-ordered barrier.
- Fail closed for barrier, logtail, workspace, transaction, and
typed-nil executor failures.
- Add a bounded two-CN branch acceptance sequence on one pre-opened CN-B
connection: `1 -> 0 -> -1 -> 0 -> 1`, with no sleep or retry between
CN-A's committed quota mutation and admission.
- Reuse the existing shared two-CN cluster; no extra embedded-cluster
startup was added.
- Make catalog-readiness polling synchronous and context-bounded,
preserve the last SQL error, close partial executor results, and avoid
calling `testing.T` from a polling worker goroutine.
- Strengthen unlimited snapshot and SI snapshot-preservation assertions.

## Performance and risk

- Ordinary SQL and authentication add no new barrier, lock, scan,
allocation, or goroutine from this feature change.
- Snapshot create: one v39 barrier and the existing lineage-owner lock.
- Disabled/unlimited branch create: one v39 barrier and no quota lock.
- Finite branch create: two v39 barriers and serialization only on that
target account's quota row; different accounts remain concurrent.
- The v38 fallback is correct but can wait about one `MaxOffset` for
disabled/unlimited and two for finite branch admission.
- Every wait is request-context-bound; topology readiness has one
30-second total bound and preserves the causal probe error.

The merged matrixorigin#27842 queue/RPC hot path is byte-identical to `main`. On
this final tree, `BenchmarkSafeQueueEnqueue` (Apple M4, 1s x3) reports 0
alloc/op; the background path is 72.08/65.79/65.25 ns/op (median 65.79
ns/op), and the request-context path is 93.54/109.6/87.28 ns/op. TPCH
acceptance belongs to the already-merged barrier change; this
feature-only delta does not add work to TPCH query execution.

## Validation

Exact head `66e95cf25b` on `main@fcc8ff3`:

- 17 selected frontend quota/authentication/protocol-boundary test
functions, including all nested fail-closed cases: PASS (`pkg/frontend`,
1.067s).
- `BenchmarkSafeQueueEnqueue`, background and request-context paths, 1s
x3: PASS, 0 alloc/op.
- `git diff --check origin/main...HEAD`: PASS.
- `git range-diff` against the pre-rebase feature commit:
patch-equivalent.
- Production and test trees are byte-identical to the previously
validated matrixorigin#27844 head; the rebase changed ancestry and the two design
clarifications only.

Semantically reused because the relevant code, tests, build mode,
topology, and current-main dependency tree are unchanged:

- `TestIssue26087ConcurrentDataBranchQuota`,
`TestIssue27718ConcurrentSnapshotQuota`, and
`TestWaitForCatalogVisibilityPreservesProbeError`: PASS on the shared
two-CN cluster (15.310s on the pre-rebase identical tree).
- v38 temporary-table migration compatibility tests across
frontend/proxy.
- normal and focused race evidence for the TN queue, manager,
service/RPC correlation, cancellation, CN consumer apply, and
authentication barrier paths from merged matrixorigin#27842.
- two-CN authentication acceptance and dependency SCA validation from
merged matrixorigin#27842.

Fresh CI was triggered by the force-rebase and was not awaited.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…rigin#27814)

Fixes matrixorigin#27775

> [!IMPORTANT]
> **Draft status on exact head `f48843c9e2`, rebased on `main`
`07fe9a69c6`: deterministic implementation/code closure is complete. The
causal A/B, 100M/1B endpoint evidence, and exact-head SQL/compile plus
lockservice owner approvals are still required. Do not merge or call
matrixorigin#27775 fixed from local tests.**

Design: `docs/design/load_data_unique_index_locking.md`, revision v8.

## Problem and evidence boundary

The reported 100M/1B indexed `LOAD DATA` regression correlates with
hidden-UNIQUE per-batch lock encoding/submission, lock coarsening,
higher mutex delay, and lower CPU utilization. The no-index control is
comparatively stable.

This is still a hypothesis, not proven causality. The exact matrixorigin#26706
parent/merge A/B (`6742f958d466` vs `35db232dfc3b`) has not been run.
The earlier 5M experiment changed the normalized indexed/no-index ratio
by only about 2.5%, so it is mechanism evidence, not proof that matrixorigin#27775
is fixed. Implementation was explicitly requested before that external
gate; the PR therefore remains Draft.

## Current v8 design and implementation

Only a positively identified large modern `LOAD DATA` can qualify:

- fresh physical generation zero, retry enabled, non-internal and
non-prepared;
- statement-owned autocommit pessimistic RC (`Autocommit=true`,
`ByBegin=false`);
- finite effective input estimate `Cost*Rowsize >= 1 GiB`, uncompressed
CSV/JSONLINE remote source;
- one ordinary non-FK/non-partitioned/non-temporary user base table;
- synchronous default/BTREE indexes with at least one regular UNIQUE
hidden table;
- v39 protocol and a real underlying `engine.LogtailReadBarrier`
capability;
- authoritative base/hidden PK types whose lockop table range covers the
complete physical keyspace.

Missing, contradictory, duplicated, unsupported, reused, or ambiguous
state fails closed to exact `main` behavior. FLOAT/DOUBLE remain
ineligible because the current finite table-range endpoints do not cover
infinities and every NaN payload. Real production shapes such as a
`uint32` base PK and binary-`varchar` composite hidden PK are admitted.

The canonical logical plan is never mutated. Before source
initialization, generation zero:

1. acquires the existing metadata/general and base full-domain locks;
2. acquires an Exclusive full-domain lock for every promotable hidden
UNIQUE table, sorted by physical table ID;
3. invokes the existing v39 TN-ordered logtail read barrier;
4. advances the same pessimistic-RC transaction snapshot strictly beyond
the applied frontier; and
5. returns one ordinary physical retry.

The retry validates an exact coordinator-local proof: transaction ID,
logical plan identity, physical generation, installed snapshot,
frontier, and target value. It filters only covered hidden row targets
from a local `LockOp` copy. Logical rebuild, reused generation,
capability/protocol mismatch, or proof mismatch permanently disables the
optimization for that `Compile.Run`.

No protobuf/wire/catalog/durable-state change, planner cache policy,
generic lock ordering, goroutine, channel, or production log site is
introduced.

## Correctness and unhappy-path closure

- The promotion creates one bounded context: `min(lock_wait_timeout,
120s, caller deadline)`.
- That context's **absolute deadline** is copied into every lock RPC and
clamped by any shorter session timeout. Remote owners therefore see the
same authoritative deadline; target N cannot restart the budget consumed
by targets 1..N-1.
- Caller cancellation/deadline is preserved. Only expiry of the internal
aggregate budget maps to lock timeout.
- Hidden-lock, barrier, snapshot-update, capability, protocol, or proof
failure publishes no proof and never initializes the source.
- A successful lock wait may refresh the transaction snapshot. The
narrow helper suppresses only the incomplete ordinary retry; the
stronger common barrier still runs before proof publication. Definition
changes keep the existing retry behavior.
- Locks remain transaction/lockservice-owned. Compiler cancellation
stops the wait but does not unlock a partially acquired prefix behind
the transaction owner's back. Existing terminal autocommit rollback
releases the whole transaction exactly once.
- A real two-target test proves target 1 is owned while target 2 waits,
cancellation returns, no barrier runs, rollback releases target 1, and a
FastFail point contender then succeeds.
- A real binary-`varchar` full-range test proves an interior Exclusive
writer waits, the fenced retry is reentrant with no second barrier, and
transaction rollback lets the writer proceed.
- Admission tests cover the positive implicit-autocommit pessimistic-RC
case and reject `BEGIN`, `autocommit=0`, SI, optimistic, mirror,
aborted, and missing-ID transactions.

Lifecycle audit:

| Question | Closure |
| --- | --- |
| Q1: who owns cleanup? | The transaction/lockservice owns every
acquired lock; compiler owns only schema-bounded proof metadata and
disables/clears it on failure/rebuild. |
| Q2: what can wait? | Each target wait ends through holder release,
caller cancellation, aggregate deadline, lock timeout, deadlock, or
service error; barrier/update use the same bounded context. No new
goroutine or join edge exists. |
| Q3: what can grow? | Targets and proof state are bounded by schema
index count; there is one deadline, one barrier attempt, one retry, and
one fixed-cardinality metric sample per admitted run. |

## Performance and operational risk

The intended complexity change is:

```text
before: O(input batches * UNIQUE targets * encoded keys)
after:  O(UNIQUE targets log targets) + one applied-logtail barrier + one physical recompile
```

Safeguards:

- the ordinary non-LOAD top-level gate remains about 1.76 ns/op, 0 B/op,
0 allocs/op on Apple M4;
- the complete eligible-plan classifier remains about 1.69 us/op, 1120
B/op, 14 allocs/op, once per fresh candidate LOAD;
- retry proof lookup is binary over sorted physical IDs;
- ordinary `doLock` callers pass a zero scalar deadline; no
`LockOptions` growth, wrapper call around the existing non-inlined lock
function, allocation, goroutine, log, or retained state was added;
- `time.Now()` is not evaluated when neither the existing session
timeout nor the promotion deadline is present;
- the barrier metric has four pre-bound outcomes and fixed buckets;
there is no dynamic label or log-amplification path.

These checks bound implementation overhead only. Eligible LOAD still
holds base and hidden domains through barrier, retry, execution, and
commit, and pays one barrier plus recompile. Exact-main/final-head
endpoint runs must decide whether that tradeoff is worthwhile.

## Why review kept finding new blockers, and what changed

The repeated `Request changes` loop was a review-process failure, not
one endlessly recurring defect:

1. implementation started before causal evidence and owner-approved
design;
2. each pass repaired the latest counterexample and declared convergence
without freezing the complete decision surface;
3. the design promised a broader matrix than committed tests actually
proved;
4. code correctness, causal/performance evidence, and owner acceptance
were mixed together, so an external pending gate repeatedly appeared as
a new code defect.

V8 separates three gates: deterministic code closure, causal/endpoint
evidence, and owner acceptance. A missing code oracle requires code/test
change; pending scale evidence or approval does not. Conversely, local
green tests are not promoted into causal proof.

Concrete issues found and resolved or explicitly removed from scope:

- replaced the early planner/protobuf/FK-routing mechanism with a
compiler-local, no-wire-change design;
- rejected non-total FLOAT/DOUBLE key ranges;
- normalized target ordering and static-NULL UNIQUE handling;
- removed explicit transaction admission, redundant planner cache
mutation, and a lock-held metric/fence design;
- reused the existing close-aware v39 TN barrier instead of introducing
a future-HLC/client protocol;
- bound physical retry/source state to the installed snapshot and kept
the canonical plan immutable;
- aligned stated tests with reachable feature-owned contracts instead of
duplicating all generic lockservice fault matrices;
- fixed the final v7 gap where one context existed locally but each
remote lock RPC recomputed its deadline;
- fixed incomplete Apache headers that caused SCA failure.

## Exact-head local validation

On `f48843c9e2` / base `07fe9a69c6`:

- normal affected packages passed: `./pkg/sql/compile`,
`./pkg/sql/colexec/lockop`, `./pkg/util/metric/v2`;
- full owning-package race passed for compile and lockop;
- measured focused race stress used `B=30s`, `N=100` and passed for both
real-lockservice success/reentry and
cancellation/deadline/prefix-release tests;
- `go vet` passed for all three affected packages;
- `license-eye header check`: 5906 checked, 4840 valid, 0 invalid, 1066
ignored;
- `license-eye dep check` passed;
- `git diff --check` passed.

The isolated macOS worktree reused unchanged, platform-matched CGo and
third-party artifacts from the primary checkout for these tests; no CGo
source changes are in this PR. The reusable platform/provenance guard is
submitted separately as matrixorigin#27852.

## Remaining merge gates and residual risks

1. **Causality:** alternating matrixorigin#26706 parent/merge 100M A/B with same-run
no-index control and aligned lock/mutex evidence. If that boundary does
not reproduce, abandon this mechanism and bisect the original range.
2. **Endpoint performance:** alternate exact current `main` and exact
final head for at least three successful 100M runs per indexed shape
plus no-index control; require >=80% recovery of the normalized
regression gap and <=15% no-index median regression, then one 1B
confirmation.
3. **Availability/deadlock:** direct/internal writers to hidden physical
tables can wait behind a long full-domain LOAD lock and can add a
multi-table deadlock edge. The real conflict/release contract is tested,
but scale/cycle observations and lockservice-owner acceptance remain
required.
4. **Optimistic writers:** they do not honor the promoted pessimistic
lock. This PR preserves exact-main TN conflict/retry behavior and does
not claim stronger exclusion.
5. **Lock retention:** successful LOAD retains base and hidden locks
through retry, source initialization, execution, and commit; terminal
failure relies on existing whole-transaction rollback.
6. **Shared prerequisite:** the design depends on matrixorigin#27842's v39
TN-ordered barrier and fails closed for older protocol/capability
states.
7. **Mandatory exact-head review:** one SQL planner/compile owner and
one lockservice owner must approve the same final commit. The existing
`fengttt` approval is on the pre-v8 head and does not close this gate.

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

size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf: TPCH 10G 查询耗时翻倍 (+138%),二分定位到 #27763 (fix(frontend): enforce fresh authentication snapshots across CNs)

2 participants