Skip to content

perf(load): avoid per-batch locks for covered unique indexes - #27814

Merged
XuPeng-SH merged 9 commits into
matrixorigin:mainfrom
XuPeng-SH:xp/fix-load-index-lock-contention
Aug 30, 2026
Merged

XuPeng-SH merged 9 commits into
matrixorigin:mainfrom
XuPeng-SH:xp/fix-load-index-lock-contention

Conversation

@XuPeng-SH

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

Copy link
Copy Markdown
Contributor

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:

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 fix(lock): preserve bounded ranges for large DML batches #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 fix(logtail): add linearizable read barrier #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.

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

@matrix-meow matrix-meow added the size/M Denotes a PR that changes [100,499] lines label Aug 28, 2026
@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Deep review result: blocking correctness finding.

The new “full-domain” intent is not full-domain for FLOAT/DOUBLE unique keys

The new path in pkg/sql/plan/bind_insert.go changes every covered single-column unique-index target to LockTable=true, Mode=Shared, and pkg/sql/compile/compile.go then calls LockTableWithMode using that target's key type. For FLOAT/DOUBLE, however, the existing table-range fetcher builds only:

  • FLOAT: [-math.MaxFloat32, +math.MaxFloat32]
  • DOUBLE: [-math.MaxFloat64, +math.MaxFloat64]

MatrixOne supports non-finite FLOAT/DOUBLE values, and LOAD DATA parses them through strconv.ParseFloat. With the actual ordered Packer encoding:

-Inf        21000fffffffffffff
-MaxFloat64 210010000000000000
 MaxFloat64 21ffefffffffffffff
+Inf        21fff0000000000000
 NaN        21fff8000000000000

Therefore -Inf is below the range start, while +Inf and positive NaN encodings are above the range end. localLockTable.getLockByKeyLocked locates a covering range by seeking a range-end at or after the requested key; for these values it finds no covering intent.

Concrete reachable case:

create table t(id bigint primary key, u double unique);
-- LOAD DATA contains Inf/NaN for u

After this PR the exact per-batch Exclusive hidden-index key lock is removed. An independent Exclusive row write to the hidden unique-index table for Inf/NaN does not wait behind the new Shared intent, even though the PR's safety invariant and tests say every independent physical-index writer is fenced for the statement. A later physical writer can therefore enter after LOAD acquired its advertised fence and race the same hidden key; the LOAD may lose to the later write/commit conflict instead of owning the index mutation interval.

This is not hypothetical type reachability: FLOAT/DOUBLE unique indexes are accepted by DDL, non-finite values are explicitly supported, and there is no DML guard that makes an existing hidden table unaddressable by name.

Please either:

  1. make table locking use true encoded-keyspace sentinels that cover every valid value, including infinities and every NaN payload; or
  2. keep exact row locks for unique-key encoding families whose table range is not total, until the general table-lock boundary is fixed.

Add deterministic coverage for FLOAT and DOUBLE -Inf, +Inf, and NaN: planner classification plus a real lockservice assertion that an Exclusive physical row writer waits behind the intent. The current finite int32 lockservice test cannot catch this boundary.

What passed

  • Full diff and latest base/head inspected: base 52336df805, head 32570a2d27; no relevant source changes in current origin/main since the PR base.
  • Focused planner/compiler tests pass.
  • Focused race stress: measured 0.08s, B=30s, N=100; pass.
  • Full affected-package race run passes for pkg/sql/plan, pkg/sql/compile, and pkg/sql/colexec/lockop.
  • Ownership/Q1: locks remain transaction-owned; compiler only retains bounded plan pointers and clears them before pooling.
  • Liveness/Q2: ordinary locks and intents are deterministic; cancellation detaches the tested waiter; re-entry succeeds.
  • Boundedness/Q3: the new slice is bounded by synchronous unique-index count and recycled.

The finite-key design and lifecycle handling look sound; the non-finite keyspace hole is the blocker.

GitHub does not allow the PR author account to submit a formal Request changes review, so this is posted as a blocking review comment.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Follow-up deep review decision: REQUEST_CHANGES-equivalent.

GitHub does not allow the PR author account to submit a formal Request changes review, so this is posted as a blocking review comment.

1. Mandatory design-first gate is missing

This is no longer a focused implementation-only bug fix. Excluding tests, generated protobuf, deepcopy, and the proto declaration, it changes about 597 non-generated production lines and crosses planner → plan protobuf → compiler → lockservice. It also changes a distributed locking/concurrency protocol and a material LOAD hot path. Both the size trigger and multiple complexity triggers require a stable, versioned, approved design.

The PR body is useful implementation documentation, but it is not a separately reviewed design revision and has no traceable design approval. The design must close at least:

  • the ownership and linearization invariant for base, hidden UNIQUE, and referenced FK keyspaces;
  • alternatives and why full-domain parent fencing wins;
  • the availability tradeoff that a long child LOAD now holds Shared full-domain fences and blocks all conflicting parent writes, including disjoint keys, for the LOAD duration;
  • mixed-version rollout, downgrade/rollback behavior, and when the stronger invariant becomes cluster-wide;
  • resource/failure blast radius, observability, and measurable acceptance criteria.

Implementation approval remains blocked until that design is reviewed and approved.

2. The performance evidence does not demonstrate that #27775 is fixed

The reported indexed result improves from 16.107 s to 10.84 s, or 32.7%. However, the no-index control also improves from 7.732 s to 5.34 s, or 30.9%. Normalizing by that control, the indexed/no-index ratio changes only:

  • main: 16.107 / 7.732 = 2.083
  • PR: 10.84 / 5.34 = 2.030

That is only about a 2.5% controlled improvement. It cannot substantiate recovery from the reported 2.2–2.4x indexed regression. The values are also single observations with no median/variance and use a different scale/topology from the 100M/1B reproducer.

Eliminating three coarsening events is good mechanism evidence, but it is not endpoint evidence. Please provide repeated, alternating exact-main/exact-PR runs on the same host and state, report median and spread plus the indexed/no-index ratio, and validate at a size that crosses the regression threshold, preferably the existing 100M case before the 1B case.

3. The changed public LOAD + FK contract has no committed BVT regression

This PR reroutes FK-related LOAD from the legacy planner to the modern path and changes SQL-visible transaction waiting, commit/rollback visibility, and FK failure behavior. Planner UTs, real-lockservice UTs, and the manual 55-transaction matrix are valuable, but none is a persistent frontend/public-SQL regression.

The current BVT corpus has LOAD and FK cases, but no case exercises LOAD DATA with FK concurrency as one scenario. Add a minimal deterministic multi-session BVT covering parent commit and rollback while a child LOAD waits, with durable row/error oracles and no sleep-based synchronization. Keep scale/performance in the big-data suite.

Verified in this pass

  • Exact range: base 4661c00ce016cf0d075d5395c73fc02c75307f08, head 502ebc9b4415d7cca423426ba1ea41b07483fbb0.
  • Every changed hunk and generated-field consumer was inspected.
  • The FLOAT/DOUBLE full-physical-domain correction, strongest-mode coalescing, total ordering inside the new pre-pipeline protocol, cancellation/rollback ownership, re-entry, and compiler-pool cleanup are internally consistent.
  • Focused CGo tests passed for plan, compile, and lockop.
  • Focused real-lockservice race tests passed 3 repetitions.
  • Exact-head Ubuntu UT, SCA, build, coverage, proxy BVT, and pessimistic multi-CN BVT are green. Upgrade compatibility jobs are skipped.
  • Current main is one unrelated fulltext commit ahead with no changed-file overlap.

The implementation direction is plausible, and I found no new concrete FLOAT boundary, leak, or internal all-new lock-order defect. The three evidence/design gates above still block approval.

@XuPeng-SH

XuPeng-SH commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor Author

Design-first revision v1 is now available at docs/design/load_data_unique_index_locking.md.

The design intentionally narrows this PR back to #27775:

  • keep one Exclusive full-domain base lock plus one Exclusive full-domain lock for each writable regular UNIQUE hidden table;
  • consume those covered targets once before data-source initialization, eliminating per-batch UNIQUE lock encoding/submission;
  • preserve the FK LOAD planner and validation path from main;
  • remove the proposed referenced-parent Shared full-domain fences;
  • remove the proposed LockTarget protobuf grouping field and keep grouping statement-local in compile;
  • retain complete FLOAT/DOUBLE physical-domain coverage, deterministic ordering, partial-acquisition/rollback, and compiler-reuse closure.

This removes the availability regression where a long child LOAD would block all parent writes, including disjoint keys, and avoids an unnecessary mixed-version plan contract.

Implementation remains blocked pending traceable approval of design revision v1. Requesting one planner/compile owner and one lockservice owner to review the invariants, alternatives, rollout/rollback, and 100M/1B acceptance gate.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Design revision v3 is pushed at 44d0d92 and supersedes v1 plus the current production implementation. The PR body now reflects the actual pending state and all known correctness, cache, retry-amplification, HLC-wait, availability, type-domain, and performance risks.\n\n@aunjgr @aptend @fengttt @iamlinjunhong: please review the exact design commit. Implementation remains blocked until one SQL planner/compile owner and one lockservice owner explicitly approve that revision. In particular, please challenge (1) the post-acquisition HLC/logtail freshness proof, (2) the one-fence-per-Run sticky rebuild fallback, (3) large-LOAD cache exclusion, and (4) direct hidden-writer availability/deadlock impact.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Deep review result on exact head 44d0d92292: REQUEST_CHANGES-equivalent.

GitHub does not allow the PR author account to submit a formal Request changes review, so this is posted as a blocking review comment.

1. The delivered production code is the superseded implementation, not design v3

This is a concrete correctness blocker, not only a process marker. The current head still:

  • rewrites every real-PK LOAD to pre-pipeline base/hidden full-table targets in bind_insert.go;
  • changes FK planner routing in bind_load.go;
  • adds and consumes LockTarget.lock_table_group on the plan wire contract;
  • mutates canonical LockTargets during compile; and
  • acquires those table locks through ordinary LockTableWithMode, with no post-acquisition coordinator fence, no logtail/snapshot advance, no exact retry proof, no 1 GiB admission gate, and no sticky logical-rebuild fallback.

That is precisely the v1/v2 behavior which the v3 document rejects. The already-reproduced counterexample remains reachable in the actual code:

LOAD snapshot T0
-> direct hidden-table writer commits K at T1
-> LOAD later obtains the hidden full lock with bat=nil
-> generic table-lock freshness does not scan K
-> LOAD can start duplicate detection from T0 and miss K

The design text identifies this as unsafe, but documentation at the last commit does not repair the production path in the preceding commits. The PR must not merge until the superseded implementation is removed and replaced by the exact approved design.

2. The mandatory design gate is still open

Design revision v3 is substantially better scoped than the prior revisions. I traced the main proof chain against current code:

  • Clock.Now returns local HLC plus the pairwise MaxOffset; advancing to the next physical tick dominates logical timestamps at the bound.
  • The CN logtail frontier is the minimum across consumer routines, and the built-in timestamp waiter returns applied.Next(), so a successful wait can establish snapshot > fence.
  • RollbackLastStatement rolls back workspace state but not transaction-owned locks, so a physical data retry can re-enter the acquired ranges.
  • The one-fence proof plus sticky fallback is schema-bounded and introduces no new goroutine or input-sized retained structure.

I found no additional contradiction in that abstract v3 proof. However, the two required owner decisions have not been recorded: SQL planner/compile must approve the physical-generation/retry/cache contract, and lockservice must approve the HLC/unlock/owner-rebind proof plus the broader direct-hidden-writer wait/deadlock surface. Those are material ownership and availability decisions and cannot be inferred from green CI.

3. Required implementation and endpoint evidence is absent

The latest CI is green only for the obsolete implementation. It does not exercise the v3 classifier, deferred freshness helper, coordinator fence, exact retry proof, cache isolation, owner restart/rebind, idle heartbeat progress, sticky rebuild fallback, or the complete negative eligibility matrix.

The performance claim is also still open. The existing 5M numbers improve the normalized indexed/no-index ratio by only about 2.5%; they prove mechanism movement, not recovery of #27775. The design correctly requires alternating exact-main/exact-PR 100M runs and a normalized >=30% improvement before merge. That evidence must be produced from the final implementation, not reused from this head.

Unhappy-path verdict

Dimension Design v3 Current PR head
Q1 ownership coherent transaction-owned lock model old compiler/protocol model, superseded
Q2 waits bounded by context/client close/deadlock/timeout in the proposed design no global freshness wait/proof exists
Q3 growth schema-bounded target/proof state current code is bounded, but implements the wrong contract
Correctness plausible pending dual-owner approval and implementation fails the reproduced no-active-conflict freshness case
Performance explicit 100M/1B acceptance gate final endpoint evidence absent

Reviewed range: merge-base 7bb89155a2, head 44d0d92292; latest origin/main is f779dff860 with no changed-file overlap. git diff --check passes. I intentionally did not treat the old implementation test suite as v3 validation.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Additional deep-review finding on unchanged head 44d0d92292: design v3 has a blocking Q2/liveness gap in its stated client-close path.

The previous production-code blocker remains open. This comment does not repeat it; it challenges a new assumption inside the proposed v3 contract.

TxnOperator.UpdateSnapshot cannot observe TxnClient.Close

The design says both:

  • the compiler calls txnOp.UpdateSnapshot(ctx, fence); and
  • if heartbeat/logtail progress is unavailable, the wait terminates through statement-context or txn-client close.

Those two statements are not compatible with the current API closure:

  1. txnOperator.UpdateSnapshot calls updateSnapshot(ctx, ts, nil).
  2. The built-in close-aware waiter therefore receives a nil closeC.
  3. A waiter entry blocks on ctx.Done, that nil channel, or timestamp notification.
  4. txnClient.Close closes its private lifecycle.closedC, but it does not close the shared timestampWaiter and the operator was never given closedC.

Concrete deterministic state:

logtail frontier < future fence
-> txnOp.UpdateSnapshot(background/live statement ctx, fence) registers a waiter
-> txnClient.Close closes lifecycle.closedC
-> no logtail notification and timestampWaiter itself remains open
-> UpdateSnapshot stays blocked while holding txnOperator.mu

A full CN shutdown later closes the timestamp waiter separately, and frontend shutdown normally cancels statement contexts first, but neither fact makes standalone transaction-client closure an independent termination edge. The exact client-close test required by the design would fail if it closes only the client while keeping the statement context and timestamp waiter open.

This matters because the proposed fence deliberately waits into the future. During a logtail outage, a LOAD with a live/unbounded statement context cannot rely on client lifecycle shutdown as the second local escape route described by the design.

Required design correction

Before owner approval, revise the design to choose and test one real ownership boundary:

  • add/use a close-aware snapshot-update entry point that is owned by TxnClient and always supplies lifecycle.closedC; or
  • explicitly make the compiler perform a close-aware TxnClient.WaitLogTailAppliedAt step before installing the snapshot, with the race between wait completion, client close, and snapshot installation closed; or
  • drop the client-close guarantee and prove that every admitted compiler context is independently canceled on every relevant client/service shutdown path.

The regression must hold logtail below the fence, keep the caller context live, close only the txn client, and require the fence call to return ErrClientClosed without separately closing/notifying the timestamp waiter. Also cover close-vs-notify selection and verify the waiter entry is removed.

Q1 remains single-owner through finishWaiter; Q3 remains bounded by in-flight statements. Q2 is the failing proposition. The HLC domination and physical-generation proof reviewed previously are unaffected by this finding.

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

Multi-angle deep review on exact head 44d0d92292: REQUEST_CHANGES-equivalent.

GitHub does not allow the PR author account to submit a formal Request changes review. This review therefore records the same blocking decision as a COMMENTED review. It consolidates the current disposition; the two concrete blockers are documented in detail at the implementation review and the Q2/client-close review.

Correctness and delivered artifact

The code at this head is still the superseded v1/v2 implementation, while the PR body explicitly says it must not be reviewed or merged as the intended implementation. It still changes planner/FK routing and the plan wire shape, mutates canonical lock targets, and uses ordinary LockTableWithMode without the v3 post-acquisition HLC/logtail fence, strict snapshot proof, exact retry generation, 1 GiB admission gate, or sticky fallback.

Consequently, the already-proven no-active-conflict stale-snapshot execution remains reachable in the delivered code: a direct hidden-table writer can commit after LOAD's snapshot and before its full lock; the table-lock path has bat=nil, performs no key-version scan, and the LOAD can start duplicate discovery from the stale snapshot. This alone blocks merge.

Design v3: safety, retry, and cache

I re-traced the complete v3 proof across planner output, compiler retry lifecycle, transaction snapshot semantics, remote mirror admission, lockservice ownership, CN logtail frontier, and TN heartbeat publication.

Under its stated assumptions, the core safety sequence is coherent: acquire base and all promoted hidden ownership first; construct a coordinator HLC strict upper bound; wait until the applied frontier reaches it; install a strictly later RC snapshot; physically rebuild; and admit source initialization only with an exact transaction/target/fence/generation proof. Transaction-owned locks survive RollbackLastStatement, and remote NewWithSnapshot waits for its local logtail through SnapshotTS.Prev(). I found no third independent safety counterexample in that abstract sequence.

However, v3 is not yet approvable because one of its required liveness assumptions is false in the current API: TxnOperator.UpdateSnapshot(ctx, fence) calls updateSnapshot(..., nil), so TxnClient.Close cannot reach the waiter's close channel. With a live caller context and stalled logtail, the fence wait can remain blocked while holding txnOperator.mu. The exact close-only deterministic regression required by v3 would fail. The design must select a real close-aware ownership boundary before implementation.

The cache/retry policy is appropriately fail-closed in principle, but none of it exists in this head. Final validation must prove canonical-plan immutability, no proof inheritance across prepared/session-cache or logical rebuilds, exactly one optimization fence per Compile.Run, and fresh physical/remote source state after retry.

Concurrency, deadlock, and unhappy paths

The proposed full-domain hidden ownership intentionally broadens conflicts for direct physical-index writers and can introduce new wait/deadlock edges. For ordinary eligible DML, base-before-hidden ordering can prevent the common inversion, but earlier-statement retained locks and direct multi-table physical clients remain real residual cycles. This is an availability tradeoff requiring traceable lockservice-owner approval plus deterministic commit/rollback/cancel/timeout/deadlock tests; green CI on the obsolete implementation is not that evidence.

Q1/Q3 are plausibly bounded in v3: compiler proof state is schema-sized, no input-sized retained collection or new goroutine is required, and partial lock prefixes stay transaction-owned. Q2 is not closed because of the client-close disconnect above. Failure after source initialization also retains the new hidden full locks in explicit transactions until terminal commit/rollback; that documented behavior needs regression coverage because it broadens writer impact.

Performance and operational evidence

The mechanism hypothesis is credible—removing per-batch UNIQUE lock encoding/submission should eliminate lock-budget coarsening—but issue #27775 is an endpoint regression, and the endpoint is still unproven. The existing 5M result improves the normalized indexed/no-index ratio by only about 2.5%, far below v3's >=30% acceptance gate. There is still no alternating exact-main/exact-final-head 100M evidence, no 1B confirmation, and no final-head accounting for fence wait, two compile generations, retry count, lock waits/deadlocks, coarsening, profiles, or log volume.

The final evidence must also come from the implementation that will merge. The current all-green CI validates only the old unsafe code and cannot be carried forward as v3 evidence.

Compatibility and merge state

V3's intended no-protobuf/no-FK-routing scope is the right compatibility direction, but the delivered branch still contains the opposite changes and must remove them. The PR is also BEHIND latest main (fcc8ff3b03). There is currently no changed-file overlap with the intervening main commits, but the final implementation must rebase before exact-head correctness and scale validation so evidence is not attached to a stale base.

Decision

Do not merge or approve this head. Required closure:

  1. obtain traceable SQL planner/compile-owner and lockservice-owner approval for one exact design revision;
  2. repair the close-aware fence-wait contract and add its deterministic race/cancellation tests;
  3. replace, rather than layer on, the superseded production implementation;
  4. rebase latest main and run the full v3 negative/unhappy/concurrency matrix; and
  5. pass the exact-final-head 100M normalized performance gate and 1B confirmation.

Reviewed range: base 7bb89155a2, head 44d0d92292; git diff --check passes. CI was inspected but intentionally not treated as evidence for code that has not been implemented.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Design revision v4 is ready for owner review on exact head 47c3f1e748, rebased onto current main fb56746be1.

The superseded production implementation has been removed; the PR diff is now design-only. V4 closes the Q2 blocker found in v3: the compiler no longer relies on TxnOperator.UpdateSnapshot for the future fence. The transaction client owns a close-aware wait-and-install transition, holds no lifecycle/operator lock while logtail is stalled, then linearizes client close before exact-generation/open-status validation and monotonic snapshot installation. The design includes close-vs-notify, commit/rollback-vs-notify, and restart-generation tests.

@aunjgr @aptend @fengttt @iamlinjunhong: please record explicit approval or concrete blockers on this exact revision. Production implementation remains blocked until one SQL planner/compile owner and one lockservice owner approve it.

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

Multi-angle deep review on exact head 47c3f1e748b9dffbf12ef4864905741660f309bf against base fb56746be170fa7e51191853f9e9f5a518ef69e0: REQUEST_CHANGES-equivalent.

GitHub does not allow the PR author account to submit a formal Request changes review, so this is submitted as a blocking COMMENTED review.

V4 closes the concrete v3 client-close defect. I traced the proposed HLC upper-bound fence, TN heartbeat -> ordered empty progress -> CN minimum apply frontier, exact transaction-generation revalidation, metadata-lock collection through MULTI_UPDATE.UpdateCtxList, current LOAD byte estimate, and admitted integer/composite range endpoints against current main. I did not find a new counterexample in that core abstract freshness proof. Three design issues still need to be resolved before owner approval and implementation.

1. [P1 availability/scope] Do not optimize explicit multi-statement transactions without a demonstrated need

The eligibility contract admits every pessimistic RC transaction, including BEGIN ... LOAD DATA ... and autocommit=0. The document then has to accept all of the following new surface:

  • a stalled future-logtail fence while the transaction already owns base plus promoted hidden full-domain Exclusive locks;
  • cancellation/fence/source/rebuild failure retaining those hidden locks until a later explicit COMMIT or ROLLBACK;
  • prior-statement physical locks forming a new cross-statement cycle; and
  • snapshot/retry/workspace correctness for earlier statements.

These are reachable SQL states, not theoretical impossibilities, but they are not required by #27775's single-statement large-LOAD workload. Current code already exposes an exact, stable discriminator through txnOp.TxnOptions().Autocommit and .ByBegin (the ALTER path uses byBegin || !autocommit to identify an explicit transaction).

Please make statement-owned autocommit a positive eligibility invariant: Autocommit == true && ByBegin == false. Add negative classifier tests for both BEGIN and autocommit=0. If explicit transactions are intentionally required, the design instead needs concrete workload evidence that justifies the added surface and an approved terminal policy for a stalled/failed fence after full ownership; documenting indefinite retained ownership is not enough for this issue's narrow fix.

2. [P2 design] The proposed large-LOAD planner cache mutation duplicates current behavior

The cache argument in sections 6.1/10.15 does not match exact current code for the only admitted modern shape:

  1. an eligible modern LOAD contains MULTI_UPDATE;
  2. physical compilation already executes node.NotCacheable = true for every MULTI_UPDATE (pkg/sql/compile/compile.go:2045-2060); and
  3. frontend session-cache insertion calls checkNodeCanCache only after execution/compile (pkg/frontend/mysql_cmd_executor.go:5922-5929).

Therefore a direct modern LOAD plan is already excluded from the session cache, independent of input size. planGenerationReused remains the correct fail-closed guard for legacy/reused session or prepared generations. The proposed planner-time 1 GiB NotCacheable helper/constant synchronization adds code and tests without closing a reachable cache path.

Please remove this planner change from the design, or identify and test one concrete admitted path that can currently insert the modern MULTI_UPDATE LOAD plan into the session cache before compilation marks it. Keep the 1 GiB estimate solely as the compiler's fixed-cost admission gate unless evidence shows otherwise.

3. [P2 validation/observability] The mandatory fence-cost gate has no safe measurement contract

Section 11 requires the HLC-fence wait duration to be reported separately, while section 12 promises no new metric label. The v4 client-owned path cannot simply reuse txnOperator.doCostAction(UpdateSnapshotEvent, locked=false): that helper takes txnOperator.mu.RLock across the supplied action, recreating the exact lock-held-during-logtail-wait defect that v4 removes. TxnClient.WaitLogTailAppliedAt itself currently exposes no duration metric.

Specify the implementation-level observation point now: capture immutable transaction/event identity under the short pre-wait lock, time only WaitLogTailAppliedAt with no lifecycle/operator lock held, then publish one bounded-cardinality existing event or metric after the wait. It must distinguish fence wait from physical recompile, record success/cancel/client-close, and add no per-heartbeat/per-target/per-batch log. Add a deterministic assertion that the event is emitted exactly once per attempted fence and that close/cancel does not leak a waiter or duplicate the event.

Q1-Q3 and other angles

Dimension Exact-head verdict
Correctness/linearization Core v4 proof is coherent against current one-primary-TN/logtail behavior; no new stale-snapshot counterexample found.
Q1 ownership Compiler target/proof state is schema-bounded; lock ownership remains transaction/lockservice-owned; v4 generation token prevents stale waiter mutation.
Q2 waits/lifecycle Client close/notify/restart ordering is now coherent, but explicit-transaction admission unnecessarily preserves the largest retained-lock and cross-statement wait graph.
Q3 boundedness At most one fence/retry and schema-bounded slices are sound; no input-sized retained state or new goroutine is proposed.
Performance Cost model is plausible, but the 100M normalized >=30% endpoint gate is still open and the fence duration is not yet safely observable.
Compatibility No wire/on-disk change; optional client capability fails closed. The shared clock-helper refactor still needs exact equivalence tests.
Logging No direct log-storm site is proposed; existing wait/deadlock diagnostics still require the scale gate.

The PR is intentionally docs-only and still has no SQL planner/compile-owner or lockservice-owner approval, final implementation, exact-main/final-head 100M evidence, or 1B confirmation. Green CI on this head cannot close those gates. git diff --check is clean; code tests are not counted because the exact diff is one design document.

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

Multi-angle self-review on exact design head 93e53055633ff0eb13d8917a6abca330c7260ce2 against latest base fb56746be170fa7e51191853f9e9f5a518ef69e0: the three v4 blockers are resolved; no additional self-found design blocker remains in v5.

This is not an approval or merge recommendation. The mandatory design gate still requires explicit approval from one SQL planner/compile owner and one lockservice owner, and production implementation plus 100M/1B endpoint evidence are intentionally absent.

Resolved findings

  1. Scope/availability: first-attempt eligibility now positively requires TxnOptions.Autocommit == true && ByBegin == false. BEGIN (which may retain Autocommit=true) and autocommit=0 are explicit negative controls. Terminal acquisition/fence/retry/source/commit failures go through the existing single-statement whole-txn rollback, so promoted hidden full locks cannot survive into a later user statement. Cross-statement workspace and retained-lock cycles are removed from the admitted graph.
  2. Cache design: the proposed planner-time >=1 GiB NotCacheable mutation and shared planner/compiler helper are deleted. Exact current compile already sets NotCacheable on every reachable MULTI_UPDATE, and frontend checks cacheability after compile. The 1 GiB estimate is compiler-only; planGenerationReused fails closed for reused legacy/session/prepared generations.
  3. Observability/liveness: the fence path explicitly forbids txnOperator.doCostAction, because it would hold op.mu.RLock across WaitLogTailAppliedAt. The client times only that wait with no lifecycle/active-shard/operator lock or event callback held and emits through one post-unlock epilogue. One dedicated histogram has four pre-bound outcomes and 21 fixed 0.1 ms-to-~105 s buckets plus +Inf; each attempted wait emits exactly once, pre-wait rejection emits none, and no dynamic identity or log is added.

Q1-Q3 / design verdict

Dimension V5 result
Safety Core order remains metadata -> base -> all promoted hidden ownership -> strict coordinator HLC upper-bound -> close-aware applied-frontier wait/install -> exact physical retry proof -> source initialization. No new counterexample found.
Q1 ownership Compiler slices/proof are schema-bounded and cleared by their root owner; locks remain transaction/lockservice-owned and release exactly once through autocommit commit/rollback; metric timing retains no txn/event identity.
Q2 liveness Physical waits terminate through holder release/context/timeout/deadlock. Fence wait observes frontier progress, context/deadline, and client close with no lifecycle/operator lock held. Commit/rollback/restart are not wake sources but are not blocked by the waiter; defensive generation validation rejects stale installation.
Q3 boundedness At most one optimization fence/retry and one metric observation per Compile.Run; no new goroutine/log/input-sized state; metric cardinality and buckets are fixed.
Compatibility No planner policy, protobuf/wire, catalog, durable, lock-mode, FK-routing, or generic table-range change. Mixed CN versions contend in the same existing physical lock namespace.
Performance Per-batch promoted UNIQUE lock work becomes schema-fixed, but every eligible LOAD pays one future-fence wait and physical recompile. The compiler-only >=1 GiB gate and mandatory normalized 100M/1B gate remain necessary.
Test architecture V5 maps BEGIN/autocommit-off negatives, whole-autocommit rollback, exact-one metric outcomes, close/cancel races, owner rebind/restart, range endpoints, retry proof, and scale evidence to deterministic UT/integration/performance layers. No sleeps or large data are assigned to UT/BVT.

Evidence and limits

  • Complete v4->v5 diff and every affected contract/table entry reviewed.
  • Source facts rechecked at exact base: transaction options and frontend terminal branches; MULTI_UPDATE NotCacheable mutation before frontend cache publication; doCostAction read-lock lifetime; close-aware timestamp waiter cleanup.
  • git diff --check and Markdown fence balance pass; worktree is clean after commit.
  • Branch is 0 commits behind latest main; only docs/design/load_data_unique_index_locking.md differs.
  • No Go/BVT run is claimed for this docs-only revision. Current CI can validate delivery hygiene but cannot validate the absent implementation.

@aunjgr @aptend @fengttt @iamlinjunhong: please review exact v5 commit 93e5305563, especially the HLC/unlock proof, physical retry generation contract, direct-hidden-writer availability tradeoff, statement-owned eligibility, and bounded fence metric.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

V6 convergence revision is pushed at exact commit c36ff10bbe, rebased on main@a3f1328612.

The repeated review loop was process and mechanism debt, not one last missing conditional: earlier revisions skipped the unproven #26706 causal boundary, repaired serial counterexamples while retaining future-HLC fencing, and let the PR body/issue/design describe different states.

V6 now:

  • requires the exact fix(lock): preserve bounded ranges for large DML batches #26706 parent/merge 100M causal A/B before implementation;
  • reuses fix(logtail): add linearizable read barrier #27842's v39 TN-ordered applied logtail barrier instead of future HLC/client-owned wait-install;
  • admits only generation-zero, statement-owned autocommit pessimistic-RC modern LOAD >=1 GiB, with FK/unsupported/reused/mixed-version paths failing to exact main;
  • keeps canonical and generation-zero row targets intact until ownership + barrier + snapshot proof completes;
  • gives all promoted hidden locks, barrier, and snapshot install one aggregate min(lock_wait_timeout, 120s, caller deadline) budget, preserving caller-cancel semantics;
  • disables promotion on any unrelated pre-proof retry or logical rebuild;
  • explicitly scopes optimistic writers to existing TN conflict semantics and records direct-hidden-writer availability/deadlock impact; and
  • requires >=80% recovery of the normalized 100M regression gap plus a no-index guard and 1B confirmation.

The stale #27775 comment that called this the root cause/final fix has been corrected. This head remains docs-only and must not merge as the fix. Production code is blocked on the causal gate and explicit approval of this exact revision by one SQL planner/compile owner and one lockservice owner.

@aunjgr @aptend @fengttt @iamlinjunhong please return the complete blocker set against this exact revision, especially the commit->unlock->barrier ordering, physical retry/source rebuild proof, one-budget timeout semantics, and direct hidden-writer availability tradeoff.

@XuPeng-SH

XuPeng-SH commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor Author

Implementation and multi-angle self-review were completed on 61165852da; after a conflict-free rebase onto latest main a15139da62, the exact PR head is 28357e2cbf. The affected tests, focused race checks, and vet were rerun successfully after rebase.

Key review findings fixed before push:

  • The first test/classifier forced int64, while the production target is commonly uint32 base PK plus binary varchar composite-UNIQUE hidden PK. That version could pass while never activating. The planner-shape and real lockservice paths now exercise the real types.
  • A broad type fix briefly reintroduced the known FLOAT/DOUBLE ±Inf/NaN range hole. Admission now uses lockop's authoritative total-range capability and rejects FLOAT/DOUBLE.
  • Ordinary SQL initially paid transaction/protocol/capability checks, and a local-node change affected every table-lock DML. Both are now scoped behind an O(1) candidate-LOAD gate; the ordinary gate benchmarks at ~1.76 ns/op with zero allocations, and non-candidate exact-main mutation/allocation behavior has a regression test.
  • Candidate classification is ~1.69 us/op, 1120 B/op, 14 allocs/op once per fresh LOAD; proof lookup is binary rather than quadratic. No input/batch-sized metric, log, goroutine, or retained state was added.
  • Lock-wait refresh, common logtail barrier, retry snapshot rebinding, exact proof validation, aggregate timeout, canonical-plan isolation, and root/borrower cleanup are covered explicitly.

Validation passed: full pkg/sql/compile, pkg/sql/colexec/lockop, and pkg/util/metric/v2 tests; focused race tests; go vet; and a real lockservice consumer integration proving base lock -> hidden full lock -> barrier -> snapshot -> retry.

This is still not an approval/merge claim. The exact #26706 causal A/B, final 100M/1B normalized endpoint evidence, SQL/compile-owner review, and lockservice-owner review remain mandatory. The PR intentionally remains Draft.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

SCA failure on exact head 28357e2cbf is fixed by 7a0a477b01.

Root cause: the two newly added test files contained only the first half of the Apache-2.0 header and omitted the warranty/limitations paragraph:

  • pkg/sql/compile/load_unique_index_promotion_test.go
  • pkg/util/metric/v2/txn_load_barrier_test.go

The patch changes comments only. Local execution of the same CI command passed terminally:

license-eye -c .licenserc.yml header check
Totally checked 4978 files, valid: 4840, invalid: 0, ignored: 138, fixed: 0

No production/test behavior changed, so the exact-head UT/race/vet evidence remains semantically valid. New CI has been triggered; not waiting for it here.

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

V8 convergence review completed on exact head f48843c9e2 against base 07fe9a69c6.

The final code blocker found in v7 is fixed: one aggregate promotion context previously existed, but each doLock still derived a fresh remote LockWaitDeadline, so a later hidden target could restart the owner-side budget. V8 propagates the context's single absolute deadline to every lock RPC and clamps it with a shorter session timeout.

Deterministic closure added on the same head:

  • real two-target waiter observation proves both targets carry the identical absolute deadline;
  • cancel on target 2 after target 1 is acquired returns without running the barrier, and whole-transaction rollback releases the acquired prefix;
  • real binary-varchar range conflict, retry reentry, and rollback/writer-release coverage;
  • positive and negative transaction-admission coverage (BEGIN, autocommit-off, SI, optimistic, mirror, aborted, missing ID);
  • ordinary deadline clamping and already-expired deadline coverage.

Validation passed: affected normal packages, full owning-package race, both focused real-lockservice tests under measured -race -count=100, affected-package go vet, license-eye header/dependency checks, and git diff --check.

Q1-Q3: locks remain transaction/lockservice-owned; cancellation does not double-unlock; every new wait is context/deadline bounded; retained state is schema-bounded; no production log/goroutine/channel or dynamic-cardinality metric was added. The ordinary lock path gained no options-struct growth or wrapper around doLock.

The PR body now records the complete review-loop root cause, every resolved design/correctness issue, exact validation, and all residual risks. I found no additional deterministic code blocker in this pass.

This is not a merge/issue-closure claim. Exact #26706 causal A/B, final-head 100M/1B normalized endpoint evidence, and fresh approval from one SQL/compile owner plus one lockservice owner remain mandatory independent gates. @aunjgr @aptend @iamlinjunhong please review exact v8 head f48843c9e2, especially the snapshot/barrier proof, absolute deadline propagation, and direct-hidden-writer availability tradeoff.

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

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.

[Bug]: LOAD DATA into PK/index tables regresses by 2.2–2.4x on main

3 participants