Skip to content

fix(disttae): inspect catalog tombstones before retrying DDL - #28359

Merged
XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/fix-28357-catalog-tombstones
Sep 7, 2026
Merged

XuPeng-SH merged 3 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/fix-28357-catalog-tombstones

Conversation

@XuPeng-SH

Copy link
Copy Markdown
Contributor

What type of PR is this?

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

Which issue(s) this PR fixes:

issue #28357

This fixes the reproduced catalog tombstone-row bailout mechanism; keep the issue's original large-scale nightly acceptance separate from the focused evidence below.

What this PR does / why we need it:

Design intent and root cause

#23868 (728817e98f) introduced PK-aware tombstone checks specifically to prevent unrelated catalog changes from restarting long IVF builds. However, tombstonePKExistsInRange still returned changed=true once selected objects contained more than 50,000 rows, before checking the requested PK or row commit timestamp.

The selection includes physically created/deleted tombstone objects. Compaction can therefore select historical deletes unrelated to the requested catalog key; object row counts do not establish a logical metadata change. The consumer chain is LockMeta -> LockRows -> PrimaryKeysMayBeModified -> PKPersistedBetween. A conservative positive becomes an RC/definition retry, and Compile.Run rolls back/rebuilds the complete statement. A late index-update registration can consequently redo clustering and the entire mapping phase.

The issue records three tombstone_rows_bailout retries during one client CREATE INDEX. That incident evidence and the deterministic source-level mechanism are consistent, but this PR does not independently identify every concurrent tombstone producer or prove that each historical target key was unchanged.

Changes and preserved behavior

  • Thread the physical table ID into tombstone checking. The four canonical IDs recognized by catalog.IsSystemTable inspect copied PKs instead of using the row-count shortcut. No index-algorithm, table-name, account, or issue-specific special case.
  • Preserve the strict >50,000 cost guard for user tables; count with uint64.
  • Use the existing 16-permit PK I/O semaphore for tombstone scans. The data phase releases its permit first; acquisition is never nested. Readers release each block before advancing, and the scan releases its permit with defer on every return.
  • Check the process context before scanning and between blocks. Propagate caller/process cancellation during reads instead of converting it into another apparent metadata-change retry. Ordinary read errors still conservatively return changed.
  • Preserve real PK hits, TN (from, to] and abort checks, conservative CN hits, unknown visibility handling, lock/version fences, and statement rollback semantics. Tombstones remain searched linearly by copied PK, not by their rowid sort order.

Risks, performance, and deliberate limits

This trades additional catalog validation I/O for avoiding a complete expensive statement restart. It is not a zero-cost change: a missing key scans selected tombstone blocks, with work proportional to that history and key search cost. The semaphore bounds concurrent block readers, not total elapsed time, object metadata, or the existing shared cache. Slow storage can still prolong a check; process cancellation remains the termination mechanism, and no new fixed timeout, worker, retry loop, cache, configuration, or logging stream is introduced.

The existing changed_objects_bailout and candidate_blocks_bailout remain unchanged. Real conflicts and unavailable evidence may still require retries. This is not a blanket promise of zero catalog/DDL retries, nor a redesign of multi-phase index building. Prelocking alone would not close reentrant validation; suppressing the retry or retrying only the final REPLACE would weaken transaction/snapshot correctness.

Local Darwin/arm64 Apple M4, Go 1.26.4, LocalFS (disabled MO caches, OS cache possible), three one-second microbenchmark samples:

Selected tombstone rows Scan time/op Allocated bytes/op
1 19–21 us ~5.3 KB
50,000 0.78–0.83 ms ~30 KB
50,001 0.76–0.86 ms ~30 KB
100,000 1.59–2.24 ms ~54 KB

These measure successful negative checks, not a comparison to the old incorrect constant-time bailout, not peak RSS, and not remote-S3/nightly latency. The 10M-row/768-dimensional/109-minute nightly was not rerun locally; no numeric end-to-end speedup is claimed.

Validation and counterexamples

Base: latest main 62770aedaa0cf3b5613bb7a42371bb08ef14ed5c. Three changed files, production behavior localized to disttae.

  • Red before green: the same PKPersistedBetween regression using a real encoded 50,001-row TN tombstone object failed on 0b195e4f5a with tombstone_rows_bailout: absent catalog keys and out-of-range deletes returned true; an already-cancelled context returned no error. It passes with the fix.
  • Reused lightweight file-service/process fixtures, no new cluster UT. Tests cover all canonical catalog policies, retained user-table guard, CN and TN objects, a real hit in the last block, compaction of historical deletes, open lower/closed upper timestamp boundaries, mpool accounting, read errors, cancellation before work/while awaiting a saturated permit/during I/O, permit release, and a successful subsequent check. Phase barriers, not sleeps, trigger cancellation; cleanup joins the worker and closes owned file services.
  • Full disttae normal suite passed (final run 8.238 s); full disttae race suite passed (final run 11.118 s). Focused cancellation race test measured 0.02 s, then ran 100 times in one process (final run 3.637 s). Existing tombstone and timestamp/abort tests remain enabled.
  • Full lockop consumer suite passed. go vet for disttae and make -j8 build passed. Native artifacts were built through the platform-aware make cgo owner, with verified source provenance.
  • Existing vector_index_plugin_smoke.sql ran in normal mo-tester comparison mode on a fresh, test-owned standalone service after SQL and ISCP readiness: 22/22 twice, 0.262 s and 0.192 s. It validates HNSW/IVF creation, catalog metadata, SHOW CREATE, search, and rejection with the feature disabled. Database and table catalog residue were both zero after each run. No SQL/result files or mo-tester changes. An initial absolute dotted temporary-path invocation failed result-file discovery and executed no SQL; it is not counted as BVT evidence.
  • Rebased from 0b195e4f5a to 62770aedaa (only frontend clone/lineage locking and its tests changed upstream). Disttae and lockop suites were rerun after rebase; race/benchmark/IVF evidence is reused because those exercised paths and native inputs are unchanged.

Review

Self-review plus an independent read-only counterexample/ownership audit found no production blocker. Verified permit ownership across data/tombstone phases, no nested semaphore acquisition, and no reverse lock edge through tombstone I/O. No wire, persisted catalog format, configuration, or index implementation changes. The existing PKPersistedBetween process-context contract is unchanged; arbitrary contexts differing from tbl.proc.Ctx are not newly promised.

Audit Ownership / termination
Q1: cleanup Per-block readers release buffers; deferred scan permit release; test-owned FS/process cleanup and zero mpool residue
Q2: waits Non-nested semaphore admission observes context; readers receive that context; cancellation needs no metadata lock or semaphore permit
Q3: growth Existing 16-permit block-I/O admission; sequential block lifetime; no new queue, worker, retry state, or diagnostic cardinality; selected-object metadata remains snapshot-proportional

@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 of 84fca1d.
Base: main at 040356c; merge-base is the same commit.

Assessment: no blocking correctness, ownership, or liveness defect found in the three-file PR diff. The design is a proportionate correction at the conflict-detection boundary, not an IVF-specific workaround.

Correctness / counterexamples:

  • An aggregate tombstone row count is not evidence that the requested catalog PK changed. The change removes only this shortcut for the four canonical physical system-table IDs; user tables retain the strict >50,000 guard.
  • The production caller passes the physical table ID. Matching remains based on copied PKs, not tombstone rowid order. TN timestamp checks retain (from,to] and abort handling; actual CN hits and unavailable evidence remain conservative.
  • The encoded 50,001-row fixtures exercise PKPersistedBetween, absent keys, a real hit in the last block, historical deletes compacted after the snapshot, timestamp boundaries, all four catalog policies, and the user-table control. The retained pre-fix log shows the intended tombstone_rows_bailout failures, rather than a build/setup failure.
  • I traced the consumer path through primaryKeysMayBeChanged, LockRows/LockMeta, and Compile.Run retry/rollback. Real conflicts are not suppressed, and this does not partially retry only the final index-registration write.

Unhappy-path audit:

Audit Result
Q1 ownership The data phase releases its permit before tombstone admission; the tombstone phase defers permit release. Cached readers release pinned IOVectors, and the generic reader releases vectors on hit, miss, and error paths.
Q2 waits Admission and I/O observe the process context; cancellation needs neither a permit nor a metadata lock. No nested semaphore acquisition or newly introduced reverse lock dependency found.
Q3 growth Existing 16-permit admission bounds concurrent block-reading operations; blocks are processed sequentially. Selected-object metadata and shared-cache residency are not bounded by that semaphore, as the body correctly states.

Performance / acceptance decision:
Scanning catalog history is intentionally more expensive than the old constant-time positive. Long scans share admission with other PK checks and may increase their queueing latency; the semaphore is not a wall-time bound. No new per-row logging, worker, retry loop, configuration, or cache is introduced. The existing local microbenchmarks support the bounded examples, not remote-S3 or concurrent-load throughput guarantees. I do not recommend adding speculative caching/scheduling machinery without evidence.

Keep the original incident acceptance separate: this closes the reproduced tombstone-row bailout mechanism, but changed-object/candidate-block bailouts, real conflicts, and unavailable evidence can still cause retries. The 10M-row/768-dimensional nightly with concurrent catalog churn has not been rerun. The prior 22/22 index smoke runs are compatibility evidence, not reproduction of the 109-minute incident.

Fresh validation on the reviewed merge head, all with real exit 0:

  • disttae full normal suite: 9.979s.
  • disttae full race suite: 23.483s.
  • lockop full normal consumer suite: 4.596s.
  • TestCatalogTombstoneCancellationAndFailure: race measurement T=0.03s; B=30s, capped N=100; all 100 repetitions passed in one process (3.958s package duration).
  • git diff --check passed; worktree clean. Native/build inputs are unchanged by the main merge.

Cloud SCA/UT/BVT were still running when checked; no cloud-green claim. No code or PR-body changes made during this review. Submitting COMMENT because the authenticated account is the PR author, so this is not a GitHub APPROVE.

@XuPeng-SH
XuPeng-SH merged commit eb9b745 into matrixorigin:main Sep 7, 2026
19 checks passed
@XuPeng-SH
XuPeng-SH deleted the codex/fix-28357-catalog-tombstones branch September 7, 2026 23:25
XuPeng-SH added a commit that referenced this pull request Sep 8, 2026
…#28361)

## What type of PR is this?

- [x] BUG
- [x] Improvement

## Related changes

Follow-up to #28359; related to #28357. The lost caller-context defect
reproduces both on #28359 and its pre-PR base; it was not introduced by
that PR's catalog-tombstone policy change.

Final head: `725319c627ce358827ce54b31025c5d10df89e25`, base `main` at
`074bc173a5b64ed0ff0b6ad6ab091f478bf76c27`. Preserves the earlier
cancellation fix, length-rejection fix and concurrent SCA cleanup.

## Root cause and implementation

### Persisted PK checks must use the operation's context

`PrimaryKeysMayBeModified` / `PrimaryKeysMayBeUpserted` accept a caller
context, but `PKPersistedBetween` replaced it with the relation's
transaction-process context. Internal SQL using an existing transaction
can have a shorter statement deadline, so cancellation did not reach
metadata/block reads or PK I/O admission.

Pass caller context through the persisted boundary, metadata/BF reads,
predicate construction, data/tombstone reads and permit admission.
Observe cancellation between objects/blocks and at return: a synchronous
or cache-backed read completing after cancellation cannot turn
cancellation into successful validation or a metadata-conflict retry.
The shared transaction process is not mutated.

Actual PK conflicts, `(from, to]` commit-TS/abort filtering,
conservative unknown/I/O outcomes, user-table cost guards, and the
existing 16-permit admission policy remain unchanged.

### Exact unsorted membership should not repeatedly compare long common
prefixes

Tombstones are ordered by rowid, not their copied original PK;
binary-searching the source would be incorrect. The previous unsorted
varlen algorithm is O(rows × keys). Searching owned needles improves
large misses, but full-tail byte binary search has two counterexamples:

1. Unequal lengths with long common prefixes lose equality's cheap
length rejection.
2. Equal-length duplicate-heavy input concentrated just beyond the first
eight keys regresses: with 4096 needles and a 2KB prefix, hot rank nine
previously measured about 998 us versus linear's 289 us per 1024 rows.

The final immutable descriptor keeps original byte ordering for
sorted-source lookup and the first eight comparisons. Its tail is
length-ordered, copying only slice headers when the original order is
not length-monotone. Search rejects absent lengths before touching
payloads, then:

- compares a same-length group of at most eight keys directly;
- keeps binary search for larger inline-key groups;
- uses a once-built standard Go string map for larger out-of-line-key
groups.

Only eligible long groups pay for hashing. The threshold uses the
existing `types.VarlenaInlineSize` representation boundary, not an
issue-specific key size or table/index type. Pure exponential bracketing
was measured and rejected because moving from rank nine to rank
seventeen still regressed.

Map keys share only the descriptor's already-cloned, immutable Go-heap
payloads via the existing byte-to-string helper; no second payload copy
or caller/cache-buffer retention. Maps are completely constructed before
publication, never mutated by search, and may safely be shared by
combined predicates. Transient source-byte string lookups do not
allocate or retain source values. There is no per-block lookup
construction, global cache, lazy initialization, new worker, lock, retry
or timeout.

Small-key, sorted-source, constant, prefix/range,
NULL/unavailable-column and OID-mismatch semantics remain intact. No
wire/storage/catalog formats, authorization rules, config, native code
or generated files change.

## Performance and costs

Darwin arm64 / Apple M4, Go 1.26.4. Same-process paired
current/previous-linear benchmarks, median of three 100ms samples. These
are component measurements, not SQL/TPCC/nightly throughput claims.

1024 flat source rows, 2048-byte common prefix, 4096 needles:

| Hot byte-order rank | Previous linear | Final implementation |
| --- | ---: | ---: |
| 9 | 291 us | 288 us |
| 10 | 324 us | 282 us |
| 17 | 538 us | 313 us |
| Cycle over 32 tail keys | 770 us | 302 us |

The prior 998us regression is removed. The cycling case does not depend
on consecutive-value memoization. Repeated original PKs across different
rowids/versions are valid tombstone input; this is not the shape of an
ordinary unique-PK data block.

8192 rows, short-key **in-range misses**:

| Needles | Previous linear | Final implementation |
| ---: | ---: | ---: |
| 9 | 516 us | 168 us |
| 64 | 3.23 ms | 0.331 ms |
| 1024 | 48.3 ms | 0.645 ms |
| 4096 | 181 ms | 0.766 ms |

Miss scans allocate zero bytes. The 4096-key all-first-key control is
37.6us versus linear64.5us. Every measured length-shape variant (9/16/64
keys, 16/256/2048-byte prefixes, shorter/gap/present-length nonmembers
plus actual hits) remains faster than its paired linear control.

Construction is not free and can be paid even if subsequent blocks are
sorted or constant:

- Short single-key descriptors remain 168B/4 allocations; 4096
equal-length short keys remain 163968B/4099 allocations. Mixed short
keys needing a secondary order use 262304B/4101 allocations; the
existing auxiliary holder grows by eight bytes.
- A 4096-key, 2KB-prefix constructor totals about 1.47ms/9.75MB for
equal lengths or 5.18ms/9.85MB for mixed lengths, including original
payload cloning and sorting. Its once-built hash metadata is roughly
0.21MiB for 4096 entries, not another 8MiB payload copy.
- No claim of universal improvement on every input or platform.
Machine-load variation is visible in controls; the original nightly
workload has not been rerun.

Selected history still determines total scan work. The permit limit
bounds concurrent block readers, not total metadata/history.
Cancellation remains cooperative for synchronous CPU work and
third-party readers that ignore context.

## Validation

Final source, before committing without further code edits:

- Focused `TestReadFilterExact*`: PASS, 0.547s. Complete offset oracles
cover VARCHAR/VARBINARY, empty/duplicate/arbitrary bytes, all key
positions, unequal-length gaps, sparse mixed small/large groups,
original-buffer mutation, sorted/unsorted and combined predicates, and
real sealed cache-backed vectors without full-column cloning.
- Explicit group-size and inline/out-of-line boundary tests cover 16/17
total keys and `VarlenaInlineSize` / `VarlenaInlineSize+1`.
- New concurrent reuse test: four private source vectors share one
immutable combined hash-backed descriptor after caller buffers are
overwritten; exact offsets and misses verified. `-race -count=100` PASS,
1.568s.
- Final normal owning/consumer packages: objectio2.781s,
objectio/ioutil1.032s, readutil2.126s, disttae9.010s. All four pass `go
vet`.
- Final owning race suites: objectio6.644s, disttae12.056s.
- Final complete Search/KeyLengths/Construction/HotRanks benchmark
matrix: PASS, 74.354s. Functional offsets are checked independently
before timing the added hotspots.
- Native-aware tests verify matching native-source/platform provenance
and use the supported linked-test runtime loading setup. `gofmt -s` and
`git diff --check` are clean.

Retained evidence for unchanged cancellation behavior:

- The same deterministic public-entry probe fails before the fix and
passes after it: caller/reader/returned errors all reflect
`context.Canceled`, with the transaction parent still alive.
- One-row actual persisted fixtures cover VARCHAR/BIGINT data and
tombstones, Modified/Upserted callers, metadata cancellation,
cancellation after admission, completing non-cooperative reads,
full-permit waits, release and healthy reuse detecting real conflicts.
No sleeps or cluster startup.
- The existing real 50001-row tombstone fixture retains
catalog/user-table policy, last-block conflict and commit-time boundary
oracles, with multi-key coverage and no extra heavy fixture.
- Three earlier named cancellation/admission tests have 100-repetition
race evidence; their synchronization is unchanged, and the final disttae
owning race suite exercises them again.
- Earlier lockop checks and full native-aware mo-service build passed.
Before these internal algorithm follow-ups, real-service
`vector_index_plugin_smoke.sql` passed 22/22 twice in normal comparison
mode on one clean-start instance; teardown left no database/table/index
residue and the owned service was stopped. This historical SQL smoke is
not claimed as rerun on the latest hash implementation. Final
encoded-cache and real persisted-object tests validate the changed
internal boundary without another cluster-heavy fixture.

## QA test plan

1. Use `.agents/skills/mo-dev/scripts/mo-cgo-test` to run
`TestReadFilterExact*`, the persisted caller-context tests, and the
related owning/consumer packages. Run objectio/disttae under race and
exact concurrent-reuse/cancellation tests individually under stress.
2. Run `BenchmarkReadFilterExactSearch`,
`BenchmarkReadFilterExactKeyLengths`, `BenchmarkReadFilterExactHotRanks`
and `BenchmarkReadFilterExactConstruction` with allocations. Compare
paired current/linear runs; include different hotspot ranks, cycling
keys, length gaps, same-length misses, small/large groups and short/long
construction. Do not add wall-clock thresholds to ordinary UT.
3. Run `BenchmarkCatalogTombstoneMultiKeyCheck` separately for actual
persisted-object integration cost.
4. For public smoke, start a test-owned service and wait for SQL
readiness plus `ISCP-Task Start`; run the vector index plugin smoke with
normal mo-tester comparison, verify teardown, and repeat on the same
instance.
5. In the original nightly/remote-storage environment, verify unrelated
catalog history does not restart the whole DDL, genuine concurrent
catalog changes still cause safe retry, and cancelled internal SQL stops
its persisted check. Measure complete index-build phases separately from
component benchmarks.

No CI wait or claim that the full CI matrix has passed.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…rigin#28359)

## What type of PR is this?

- [x] BUG
- [x] Improvement
- [ ] API-change
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue matrixorigin#28357

This fixes the reproduced catalog tombstone-row bailout mechanism; keep
the issue's original large-scale nightly acceptance separate from the
focused evidence below.

## What this PR does / why we need it:

### Design intent and root cause

matrixorigin#23868 (`728817e98f`) introduced PK-aware tombstone checks specifically
to prevent unrelated catalog changes from restarting long IVF builds.
However, `tombstonePKExistsInRange` still returned `changed=true` once
selected objects contained more than 50,000 rows, **before checking the
requested PK or row commit timestamp**.

The selection includes physically created/deleted tombstone objects.
Compaction can therefore select historical deletes unrelated to the
requested catalog key; object row counts do not establish a logical
metadata change. The consumer chain is `LockMeta -> LockRows ->
PrimaryKeysMayBeModified -> PKPersistedBetween`. A conservative positive
becomes an RC/definition retry, and `Compile.Run` rolls back/rebuilds
the complete statement. A late index-update registration can
consequently redo clustering and the entire mapping phase.

The issue records three `tombstone_rows_bailout` retries during one
client CREATE INDEX. That incident evidence and the deterministic
source-level mechanism are consistent, but this PR does not
independently identify every concurrent tombstone producer or prove that
each historical target key was unchanged.

### Changes and preserved behavior

- Thread the physical table ID into tombstone checking. The four
canonical IDs recognized by `catalog.IsSystemTable` inspect copied PKs
instead of using the row-count shortcut. No index-algorithm, table-name,
account, or issue-specific special case.
- Preserve the strict `>50,000` cost guard for user tables; count with
`uint64`.
- Use the existing 16-permit PK I/O semaphore for tombstone scans. The
data phase releases its permit first; acquisition is never nested.
Readers release each block before advancing, and the scan releases its
permit with `defer` on every return.
- Check the process context before scanning and between blocks.
Propagate caller/process cancellation during reads instead of converting
it into another apparent metadata-change retry. Ordinary read errors
still conservatively return changed.
- Preserve real PK hits, TN `(from, to]` and abort checks, conservative
CN hits, unknown visibility handling, lock/version fences, and statement
rollback semantics. Tombstones remain searched linearly by copied PK,
not by their rowid sort order.

### Risks, performance, and deliberate limits

This trades additional catalog validation I/O for avoiding a complete
expensive statement restart. It is not a zero-cost change: a missing key
scans selected tombstone blocks, with work proportional to that history
and key search cost. The semaphore bounds concurrent block readers, not
total elapsed time, object metadata, or the existing shared cache. Slow
storage can still prolong a check; process cancellation remains the
termination mechanism, and no new fixed timeout, worker, retry loop,
cache, configuration, or logging stream is introduced.

The existing `changed_objects_bailout` and `candidate_blocks_bailout`
remain unchanged. Real conflicts and unavailable evidence may still
require retries. This is **not** a blanket promise of zero catalog/DDL
retries, nor a redesign of multi-phase index building. Prelocking alone
would not close reentrant validation; suppressing the retry or retrying
only the final REPLACE would weaken transaction/snapshot correctness.

Local Darwin/arm64 Apple M4, Go 1.26.4, LocalFS (disabled MO caches, OS
cache possible), three one-second microbenchmark samples:

| Selected tombstone rows | Scan time/op | Allocated bytes/op |
|---:|---:|---:|
| 1 | 19–21 us | ~5.3 KB |
| 50,000 | 0.78–0.83 ms | ~30 KB |
| 50,001 | 0.76–0.86 ms | ~30 KB |
| 100,000 | 1.59–2.24 ms | ~54 KB |

These measure successful negative checks, not a comparison to the old
incorrect constant-time bailout, not peak RSS, and not remote-S3/nightly
latency. The 10M-row/768-dimensional/109-minute nightly was not rerun
locally; no numeric end-to-end speedup is claimed.

### Validation and counterexamples

Base: latest main `62770aedaa0cf3b5613bb7a42371bb08ef14ed5c`. Three
changed files, production behavior localized to disttae.

- **Red before green:** the same `PKPersistedBetween` regression using a
real encoded 50,001-row TN tombstone object failed on `0b195e4f5a` with
`tombstone_rows_bailout`: absent catalog keys and out-of-range deletes
returned true; an already-cancelled context returned no error. It passes
with the fix.
- Reused lightweight file-service/process fixtures, no new cluster UT.
Tests cover all canonical catalog policies, retained user-table guard,
CN and TN objects, a real hit in the last block, compaction of
historical deletes, open lower/closed upper timestamp boundaries, mpool
accounting, read errors, cancellation before work/while awaiting a
saturated permit/during I/O, permit release, and a successful subsequent
check. Phase barriers, not sleeps, trigger cancellation; cleanup joins
the worker and closes owned file services.
- Full disttae normal suite passed (final run 8.238 s); full disttae
race suite passed (final run 11.118 s). Focused cancellation race test
measured 0.02 s, then ran 100 times in one process (final run 3.637 s).
Existing tombstone and timestamp/abort tests remain enabled.
- Full lockop consumer suite passed. `go vet` for disttae and `make -j8
build` passed. Native artifacts were built through the platform-aware
`make cgo` owner, with verified source provenance.
- Existing `vector_index_plugin_smoke.sql` ran in normal mo-tester
comparison mode on a fresh, test-owned standalone service after SQL and
ISCP readiness: **22/22 twice**, 0.262 s and 0.192 s. It validates
HNSW/IVF creation, catalog metadata, SHOW CREATE, search, and rejection
with the feature disabled. Database and table catalog residue were both
zero after each run. No SQL/result files or mo-tester changes. An
initial absolute dotted temporary-path invocation failed result-file
discovery and executed no SQL; it is not counted as BVT evidence.
- Rebased from `0b195e4f5a` to `62770aedaa` (only frontend clone/lineage
locking and its tests changed upstream). Disttae and lockop suites were
rerun after rebase; race/benchmark/IVF evidence is reused because those
exercised paths and native inputs are unchanged.

### Review

Self-review plus an independent read-only counterexample/ownership audit
found no production blocker. Verified permit ownership across
data/tombstone phases, no nested semaphore acquisition, and no reverse
lock edge through tombstone I/O. No wire, persisted catalog format,
configuration, or index implementation changes. The existing
`PKPersistedBetween` process-context contract is unchanged; arbitrary
contexts differing from `tbl.proc.Ctx` are not newly promised.

| Audit | Ownership / termination |
|---|---|
| Q1: cleanup | Per-block readers release buffers; deferred scan permit
release; test-owned FS/process cleanup and zero mpool residue |
| Q2: waits | Non-nested semaphore admission observes context; readers
receive that context; cancellation needs no metadata lock or semaphore
permit |
| Q3: growth | Existing 16-permit block-I/O admission; sequential block
lifetime; no new queue, worker, retry state, or diagnostic cardinality;
selected-object metadata remains snapshot-proportional |

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…matrixorigin#28361)

## What type of PR is this?

- [x] BUG
- [x] Improvement

## Related changes

Follow-up to matrixorigin#28359; related to matrixorigin#28357. The lost caller-context defect
reproduces both on matrixorigin#28359 and its pre-PR base; it was not introduced by
that PR's catalog-tombstone policy change.

Final head: `725319c627ce358827ce54b31025c5d10df89e25`, base `main` at
`074bc173a5b64ed0ff0b6ad6ab091f478bf76c27`. Preserves the earlier
cancellation fix, length-rejection fix and concurrent SCA cleanup.

## Root cause and implementation

### Persisted PK checks must use the operation's context

`PrimaryKeysMayBeModified` / `PrimaryKeysMayBeUpserted` accept a caller
context, but `PKPersistedBetween` replaced it with the relation's
transaction-process context. Internal SQL using an existing transaction
can have a shorter statement deadline, so cancellation did not reach
metadata/block reads or PK I/O admission.

Pass caller context through the persisted boundary, metadata/BF reads,
predicate construction, data/tombstone reads and permit admission.
Observe cancellation between objects/blocks and at return: a synchronous
or cache-backed read completing after cancellation cannot turn
cancellation into successful validation or a metadata-conflict retry.
The shared transaction process is not mutated.

Actual PK conflicts, `(from, to]` commit-TS/abort filtering,
conservative unknown/I/O outcomes, user-table cost guards, and the
existing 16-permit admission policy remain unchanged.

### Exact unsorted membership should not repeatedly compare long common
prefixes

Tombstones are ordered by rowid, not their copied original PK;
binary-searching the source would be incorrect. The previous unsorted
varlen algorithm is O(rows × keys). Searching owned needles improves
large misses, but full-tail byte binary search has two counterexamples:

1. Unequal lengths with long common prefixes lose equality's cheap
length rejection.
2. Equal-length duplicate-heavy input concentrated just beyond the first
eight keys regresses: with 4096 needles and a 2KB prefix, hot rank nine
previously measured about 998 us versus linear's 289 us per 1024 rows.

The final immutable descriptor keeps original byte ordering for
sorted-source lookup and the first eight comparisons. Its tail is
length-ordered, copying only slice headers when the original order is
not length-monotone. Search rejects absent lengths before touching
payloads, then:

- compares a same-length group of at most eight keys directly;
- keeps binary search for larger inline-key groups;
- uses a once-built standard Go string map for larger out-of-line-key
groups.

Only eligible long groups pay for hashing. The threshold uses the
existing `types.VarlenaInlineSize` representation boundary, not an
issue-specific key size or table/index type. Pure exponential bracketing
was measured and rejected because moving from rank nine to rank
seventeen still regressed.

Map keys share only the descriptor's already-cloned, immutable Go-heap
payloads via the existing byte-to-string helper; no second payload copy
or caller/cache-buffer retention. Maps are completely constructed before
publication, never mutated by search, and may safely be shared by
combined predicates. Transient source-byte string lookups do not
allocate or retain source values. There is no per-block lookup
construction, global cache, lazy initialization, new worker, lock, retry
or timeout.

Small-key, sorted-source, constant, prefix/range,
NULL/unavailable-column and OID-mismatch semantics remain intact. No
wire/storage/catalog formats, authorization rules, config, native code
or generated files change.

## Performance and costs

Darwin arm64 / Apple M4, Go 1.26.4. Same-process paired
current/previous-linear benchmarks, median of three 100ms samples. These
are component measurements, not SQL/TPCC/nightly throughput claims.

1024 flat source rows, 2048-byte common prefix, 4096 needles:

| Hot byte-order rank | Previous linear | Final implementation |
| --- | ---: | ---: |
| 9 | 291 us | 288 us |
| 10 | 324 us | 282 us |
| 17 | 538 us | 313 us |
| Cycle over 32 tail keys | 770 us | 302 us |

The prior 998us regression is removed. The cycling case does not depend
on consecutive-value memoization. Repeated original PKs across different
rowids/versions are valid tombstone input; this is not the shape of an
ordinary unique-PK data block.

8192 rows, short-key **in-range misses**:

| Needles | Previous linear | Final implementation |
| ---: | ---: | ---: |
| 9 | 516 us | 168 us |
| 64 | 3.23 ms | 0.331 ms |
| 1024 | 48.3 ms | 0.645 ms |
| 4096 | 181 ms | 0.766 ms |

Miss scans allocate zero bytes. The 4096-key all-first-key control is
37.6us versus linear64.5us. Every measured length-shape variant (9/16/64
keys, 16/256/2048-byte prefixes, shorter/gap/present-length nonmembers
plus actual hits) remains faster than its paired linear control.

Construction is not free and can be paid even if subsequent blocks are
sorted or constant:

- Short single-key descriptors remain 168B/4 allocations; 4096
equal-length short keys remain 163968B/4099 allocations. Mixed short
keys needing a secondary order use 262304B/4101 allocations; the
existing auxiliary holder grows by eight bytes.
- A 4096-key, 2KB-prefix constructor totals about 1.47ms/9.75MB for
equal lengths or 5.18ms/9.85MB for mixed lengths, including original
payload cloning and sorting. Its once-built hash metadata is roughly
0.21MiB for 4096 entries, not another 8MiB payload copy.
- No claim of universal improvement on every input or platform.
Machine-load variation is visible in controls; the original nightly
workload has not been rerun.

Selected history still determines total scan work. The permit limit
bounds concurrent block readers, not total metadata/history.
Cancellation remains cooperative for synchronous CPU work and
third-party readers that ignore context.

## Validation

Final source, before committing without further code edits:

- Focused `TestReadFilterExact*`: PASS, 0.547s. Complete offset oracles
cover VARCHAR/VARBINARY, empty/duplicate/arbitrary bytes, all key
positions, unequal-length gaps, sparse mixed small/large groups,
original-buffer mutation, sorted/unsorted and combined predicates, and
real sealed cache-backed vectors without full-column cloning.
- Explicit group-size and inline/out-of-line boundary tests cover 16/17
total keys and `VarlenaInlineSize` / `VarlenaInlineSize+1`.
- New concurrent reuse test: four private source vectors share one
immutable combined hash-backed descriptor after caller buffers are
overwritten; exact offsets and misses verified. `-race -count=100` PASS,
1.568s.
- Final normal owning/consumer packages: objectio2.781s,
objectio/ioutil1.032s, readutil2.126s, disttae9.010s. All four pass `go
vet`.
- Final owning race suites: objectio6.644s, disttae12.056s.
- Final complete Search/KeyLengths/Construction/HotRanks benchmark
matrix: PASS, 74.354s. Functional offsets are checked independently
before timing the added hotspots.
- Native-aware tests verify matching native-source/platform provenance
and use the supported linked-test runtime loading setup. `gofmt -s` and
`git diff --check` are clean.

Retained evidence for unchanged cancellation behavior:

- The same deterministic public-entry probe fails before the fix and
passes after it: caller/reader/returned errors all reflect
`context.Canceled`, with the transaction parent still alive.
- One-row actual persisted fixtures cover VARCHAR/BIGINT data and
tombstones, Modified/Upserted callers, metadata cancellation,
cancellation after admission, completing non-cooperative reads,
full-permit waits, release and healthy reuse detecting real conflicts.
No sleeps or cluster startup.
- The existing real 50001-row tombstone fixture retains
catalog/user-table policy, last-block conflict and commit-time boundary
oracles, with multi-key coverage and no extra heavy fixture.
- Three earlier named cancellation/admission tests have 100-repetition
race evidence; their synchronization is unchanged, and the final disttae
owning race suite exercises them again.
- Earlier lockop checks and full native-aware mo-service build passed.
Before these internal algorithm follow-ups, real-service
`vector_index_plugin_smoke.sql` passed 22/22 twice in normal comparison
mode on one clean-start instance; teardown left no database/table/index
residue and the owned service was stopped. This historical SQL smoke is
not claimed as rerun on the latest hash implementation. Final
encoded-cache and real persisted-object tests validate the changed
internal boundary without another cluster-heavy fixture.

## QA test plan

1. Use `.agents/skills/mo-dev/scripts/mo-cgo-test` to run
`TestReadFilterExact*`, the persisted caller-context tests, and the
related owning/consumer packages. Run objectio/disttae under race and
exact concurrent-reuse/cancellation tests individually under stress.
2. Run `BenchmarkReadFilterExactSearch`,
`BenchmarkReadFilterExactKeyLengths`, `BenchmarkReadFilterExactHotRanks`
and `BenchmarkReadFilterExactConstruction` with allocations. Compare
paired current/linear runs; include different hotspot ranks, cycling
keys, length gaps, same-length misses, small/large groups and short/long
construction. Do not add wall-clock thresholds to ordinary UT.
3. Run `BenchmarkCatalogTombstoneMultiKeyCheck` separately for actual
persisted-object integration cost.
4. For public smoke, start a test-owned service and wait for SQL
readiness plus `ISCP-Task Start`; run the vector index plugin smoke with
normal mo-tester comparison, verify teardown, and repeat on the same
instance.
5. In the original nightly/remote-storage environment, verify unrelated
catalog history does not restart the whole DDL, genuine concurrent
catalog changes still cause safe retry, and cancelled internal SQL stops
its persisted check. Measure complete index-build phases separately from
component benchmarks.

No CI wait or claim that the full CI matrix has passed.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…rigin#28359)

## What type of PR is this?

- [x] BUG
- [x] Improvement
- [ ] API-change
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue matrixorigin#28357

This fixes the reproduced catalog tombstone-row bailout mechanism; keep
the issue's original large-scale nightly acceptance separate from the
focused evidence below.

## What this PR does / why we need it:

### Design intent and root cause

matrixorigin#23868 (`728817e98f`) introduced PK-aware tombstone checks specifically
to prevent unrelated catalog changes from restarting long IVF builds.
However, `tombstonePKExistsInRange` still returned `changed=true` once
selected objects contained more than 50,000 rows, **before checking the
requested PK or row commit timestamp**.

The selection includes physically created/deleted tombstone objects.
Compaction can therefore select historical deletes unrelated to the
requested catalog key; object row counts do not establish a logical
metadata change. The consumer chain is `LockMeta -> LockRows ->
PrimaryKeysMayBeModified -> PKPersistedBetween`. A conservative positive
becomes an RC/definition retry, and `Compile.Run` rolls back/rebuilds
the complete statement. A late index-update registration can
consequently redo clustering and the entire mapping phase.

The issue records three `tombstone_rows_bailout` retries during one
client CREATE INDEX. That incident evidence and the deterministic
source-level mechanism are consistent, but this PR does not
independently identify every concurrent tombstone producer or prove that
each historical target key was unchanged.

### Changes and preserved behavior

- Thread the physical table ID into tombstone checking. The four
canonical IDs recognized by `catalog.IsSystemTable` inspect copied PKs
instead of using the row-count shortcut. No index-algorithm, table-name,
account, or issue-specific special case.
- Preserve the strict `>50,000` cost guard for user tables; count with
`uint64`.
- Use the existing 16-permit PK I/O semaphore for tombstone scans. The
data phase releases its permit first; acquisition is never nested.
Readers release each block before advancing, and the scan releases its
permit with `defer` on every return.
- Check the process context before scanning and between blocks.
Propagate caller/process cancellation during reads instead of converting
it into another apparent metadata-change retry. Ordinary read errors
still conservatively return changed.
- Preserve real PK hits, TN `(from, to]` and abort checks, conservative
CN hits, unknown visibility handling, lock/version fences, and statement
rollback semantics. Tombstones remain searched linearly by copied PK,
not by their rowid sort order.

### Risks, performance, and deliberate limits

This trades additional catalog validation I/O for avoiding a complete
expensive statement restart. It is not a zero-cost change: a missing key
scans selected tombstone blocks, with work proportional to that history
and key search cost. The semaphore bounds concurrent block readers, not
total elapsed time, object metadata, or the existing shared cache. Slow
storage can still prolong a check; process cancellation remains the
termination mechanism, and no new fixed timeout, worker, retry loop,
cache, configuration, or logging stream is introduced.

The existing `changed_objects_bailout` and `candidate_blocks_bailout`
remain unchanged. Real conflicts and unavailable evidence may still
require retries. This is **not** a blanket promise of zero catalog/DDL
retries, nor a redesign of multi-phase index building. Prelocking alone
would not close reentrant validation; suppressing the retry or retrying
only the final REPLACE would weaken transaction/snapshot correctness.

Local Darwin/arm64 Apple M4, Go 1.26.4, LocalFS (disabled MO caches, OS
cache possible), three one-second microbenchmark samples:

| Selected tombstone rows | Scan time/op | Allocated bytes/op |
|---:|---:|---:|
| 1 | 19–21 us | ~5.3 KB |
| 50,000 | 0.78–0.83 ms | ~30 KB |
| 50,001 | 0.76–0.86 ms | ~30 KB |
| 100,000 | 1.59–2.24 ms | ~54 KB |

These measure successful negative checks, not a comparison to the old
incorrect constant-time bailout, not peak RSS, and not remote-S3/nightly
latency. The 10M-row/768-dimensional/109-minute nightly was not rerun
locally; no numeric end-to-end speedup is claimed.

### Validation and counterexamples

Base: latest main `62770aedaa0cf3b5613bb7a42371bb08ef14ed5c`. Three
changed files, production behavior localized to disttae.

- **Red before green:** the same `PKPersistedBetween` regression using a
real encoded 50,001-row TN tombstone object failed on `0b195e4f5a` with
`tombstone_rows_bailout`: absent catalog keys and out-of-range deletes
returned true; an already-cancelled context returned no error. It passes
with the fix.
- Reused lightweight file-service/process fixtures, no new cluster UT.
Tests cover all canonical catalog policies, retained user-table guard,
CN and TN objects, a real hit in the last block, compaction of
historical deletes, open lower/closed upper timestamp boundaries, mpool
accounting, read errors, cancellation before work/while awaiting a
saturated permit/during I/O, permit release, and a successful subsequent
check. Phase barriers, not sleeps, trigger cancellation; cleanup joins
the worker and closes owned file services.
- Full disttae normal suite passed (final run 8.238 s); full disttae
race suite passed (final run 11.118 s). Focused cancellation race test
measured 0.02 s, then ran 100 times in one process (final run 3.637 s).
Existing tombstone and timestamp/abort tests remain enabled.
- Full lockop consumer suite passed. `go vet` for disttae and `make -j8
build` passed. Native artifacts were built through the platform-aware
`make cgo` owner, with verified source provenance.
- Existing `vector_index_plugin_smoke.sql` ran in normal mo-tester
comparison mode on a fresh, test-owned standalone service after SQL and
ISCP readiness: **22/22 twice**, 0.262 s and 0.192 s. It validates
HNSW/IVF creation, catalog metadata, SHOW CREATE, search, and rejection
with the feature disabled. Database and table catalog residue were both
zero after each run. No SQL/result files or mo-tester changes. An
initial absolute dotted temporary-path invocation failed result-file
discovery and executed no SQL; it is not counted as BVT evidence.
- Rebased from `0b195e4f5a` to `62770aedaa` (only frontend clone/lineage
locking and its tests changed upstream). Disttae and lockop suites were
rerun after rebase; race/benchmark/IVF evidence is reused because those
exercised paths and native inputs are unchanged.

### Review

Self-review plus an independent read-only counterexample/ownership audit
found no production blocker. Verified permit ownership across
data/tombstone phases, no nested semaphore acquisition, and no reverse
lock edge through tombstone I/O. No wire, persisted catalog format,
configuration, or index implementation changes. The existing
`PKPersistedBetween` process-context contract is unchanged; arbitrary
contexts differing from `tbl.proc.Ctx` are not newly promised.

| Audit | Ownership / termination |
|---|---|
| Q1: cleanup | Per-block readers release buffers; deferred scan permit
release; test-owned FS/process cleanup and zero mpool residue |
| Q2: waits | Non-nested semaphore admission observes context; readers
receive that context; cancellation needs no metadata lock or semaphore
permit |
| Q3: growth | Existing 16-permit block-I/O admission; sequential block
lifetime; no new queue, worker, retry state, or diagnostic cardinality;
selected-object metadata remains snapshot-proportional |

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…matrixorigin#28361)

## What type of PR is this?

- [x] BUG
- [x] Improvement

## Related changes

Follow-up to matrixorigin#28359; related to matrixorigin#28357. The lost caller-context defect
reproduces both on matrixorigin#28359 and its pre-PR base; it was not introduced by
that PR's catalog-tombstone policy change.

Final head: `725319c627ce358827ce54b31025c5d10df89e25`, base `main` at
`074bc173a5b64ed0ff0b6ad6ab091f478bf76c27`. Preserves the earlier
cancellation fix, length-rejection fix and concurrent SCA cleanup.

## Root cause and implementation

### Persisted PK checks must use the operation's context

`PrimaryKeysMayBeModified` / `PrimaryKeysMayBeUpserted` accept a caller
context, but `PKPersistedBetween` replaced it with the relation's
transaction-process context. Internal SQL using an existing transaction
can have a shorter statement deadline, so cancellation did not reach
metadata/block reads or PK I/O admission.

Pass caller context through the persisted boundary, metadata/BF reads,
predicate construction, data/tombstone reads and permit admission.
Observe cancellation between objects/blocks and at return: a synchronous
or cache-backed read completing after cancellation cannot turn
cancellation into successful validation or a metadata-conflict retry.
The shared transaction process is not mutated.

Actual PK conflicts, `(from, to]` commit-TS/abort filtering,
conservative unknown/I/O outcomes, user-table cost guards, and the
existing 16-permit admission policy remain unchanged.

### Exact unsorted membership should not repeatedly compare long common
prefixes

Tombstones are ordered by rowid, not their copied original PK;
binary-searching the source would be incorrect. The previous unsorted
varlen algorithm is O(rows × keys). Searching owned needles improves
large misses, but full-tail byte binary search has two counterexamples:

1. Unequal lengths with long common prefixes lose equality's cheap
length rejection.
2. Equal-length duplicate-heavy input concentrated just beyond the first
eight keys regresses: with 4096 needles and a 2KB prefix, hot rank nine
previously measured about 998 us versus linear's 289 us per 1024 rows.

The final immutable descriptor keeps original byte ordering for
sorted-source lookup and the first eight comparisons. Its tail is
length-ordered, copying only slice headers when the original order is
not length-monotone. Search rejects absent lengths before touching
payloads, then:

- compares a same-length group of at most eight keys directly;
- keeps binary search for larger inline-key groups;
- uses a once-built standard Go string map for larger out-of-line-key
groups.

Only eligible long groups pay for hashing. The threshold uses the
existing `types.VarlenaInlineSize` representation boundary, not an
issue-specific key size or table/index type. Pure exponential bracketing
was measured and rejected because moving from rank nine to rank
seventeen still regressed.

Map keys share only the descriptor's already-cloned, immutable Go-heap
payloads via the existing byte-to-string helper; no second payload copy
or caller/cache-buffer retention. Maps are completely constructed before
publication, never mutated by search, and may safely be shared by
combined predicates. Transient source-byte string lookups do not
allocate or retain source values. There is no per-block lookup
construction, global cache, lazy initialization, new worker, lock, retry
or timeout.

Small-key, sorted-source, constant, prefix/range,
NULL/unavailable-column and OID-mismatch semantics remain intact. No
wire/storage/catalog formats, authorization rules, config, native code
or generated files change.

## Performance and costs

Darwin arm64 / Apple M4, Go 1.26.4. Same-process paired
current/previous-linear benchmarks, median of three 100ms samples. These
are component measurements, not SQL/TPCC/nightly throughput claims.

1024 flat source rows, 2048-byte common prefix, 4096 needles:

| Hot byte-order rank | Previous linear | Final implementation |
| --- | ---: | ---: |
| 9 | 291 us | 288 us |
| 10 | 324 us | 282 us |
| 17 | 538 us | 313 us |
| Cycle over 32 tail keys | 770 us | 302 us |

The prior 998us regression is removed. The cycling case does not depend
on consecutive-value memoization. Repeated original PKs across different
rowids/versions are valid tombstone input; this is not the shape of an
ordinary unique-PK data block.

8192 rows, short-key **in-range misses**:

| Needles | Previous linear | Final implementation |
| ---: | ---: | ---: |
| 9 | 516 us | 168 us |
| 64 | 3.23 ms | 0.331 ms |
| 1024 | 48.3 ms | 0.645 ms |
| 4096 | 181 ms | 0.766 ms |

Miss scans allocate zero bytes. The 4096-key all-first-key control is
37.6us versus linear64.5us. Every measured length-shape variant (9/16/64
keys, 16/256/2048-byte prefixes, shorter/gap/present-length nonmembers
plus actual hits) remains faster than its paired linear control.

Construction is not free and can be paid even if subsequent blocks are
sorted or constant:

- Short single-key descriptors remain 168B/4 allocations; 4096
equal-length short keys remain 163968B/4099 allocations. Mixed short
keys needing a secondary order use 262304B/4101 allocations; the
existing auxiliary holder grows by eight bytes.
- A 4096-key, 2KB-prefix constructor totals about 1.47ms/9.75MB for
equal lengths or 5.18ms/9.85MB for mixed lengths, including original
payload cloning and sorting. Its once-built hash metadata is roughly
0.21MiB for 4096 entries, not another 8MiB payload copy.
- No claim of universal improvement on every input or platform.
Machine-load variation is visible in controls; the original nightly
workload has not been rerun.

Selected history still determines total scan work. The permit limit
bounds concurrent block readers, not total metadata/history.
Cancellation remains cooperative for synchronous CPU work and
third-party readers that ignore context.

## Validation

Final source, before committing without further code edits:

- Focused `TestReadFilterExact*`: PASS, 0.547s. Complete offset oracles
cover VARCHAR/VARBINARY, empty/duplicate/arbitrary bytes, all key
positions, unequal-length gaps, sparse mixed small/large groups,
original-buffer mutation, sorted/unsorted and combined predicates, and
real sealed cache-backed vectors without full-column cloning.
- Explicit group-size and inline/out-of-line boundary tests cover 16/17
total keys and `VarlenaInlineSize` / `VarlenaInlineSize+1`.
- New concurrent reuse test: four private source vectors share one
immutable combined hash-backed descriptor after caller buffers are
overwritten; exact offsets and misses verified. `-race -count=100` PASS,
1.568s.
- Final normal owning/consumer packages: objectio2.781s,
objectio/ioutil1.032s, readutil2.126s, disttae9.010s. All four pass `go
vet`.
- Final owning race suites: objectio6.644s, disttae12.056s.
- Final complete Search/KeyLengths/Construction/HotRanks benchmark
matrix: PASS, 74.354s. Functional offsets are checked independently
before timing the added hotspots.
- Native-aware tests verify matching native-source/platform provenance
and use the supported linked-test runtime loading setup. `gofmt -s` and
`git diff --check` are clean.

Retained evidence for unchanged cancellation behavior:

- The same deterministic public-entry probe fails before the fix and
passes after it: caller/reader/returned errors all reflect
`context.Canceled`, with the transaction parent still alive.
- One-row actual persisted fixtures cover VARCHAR/BIGINT data and
tombstones, Modified/Upserted callers, metadata cancellation,
cancellation after admission, completing non-cooperative reads,
full-permit waits, release and healthy reuse detecting real conflicts.
No sleeps or cluster startup.
- The existing real 50001-row tombstone fixture retains
catalog/user-table policy, last-block conflict and commit-time boundary
oracles, with multi-key coverage and no extra heavy fixture.
- Three earlier named cancellation/admission tests have 100-repetition
race evidence; their synchronization is unchanged, and the final disttae
owning race suite exercises them again.
- Earlier lockop checks and full native-aware mo-service build passed.
Before these internal algorithm follow-ups, real-service
`vector_index_plugin_smoke.sql` passed 22/22 twice in normal comparison
mode on one clean-start instance; teardown left no database/table/index
residue and the owned service was stopped. This historical SQL smoke is
not claimed as rerun on the latest hash implementation. Final
encoded-cache and real persisted-object tests validate the changed
internal boundary without another cluster-heavy fixture.

## QA test plan

1. Use `.agents/skills/mo-dev/scripts/mo-cgo-test` to run
`TestReadFilterExact*`, the persisted caller-context tests, and the
related owning/consumer packages. Run objectio/disttae under race and
exact concurrent-reuse/cancellation tests individually under stress.
2. Run `BenchmarkReadFilterExactSearch`,
`BenchmarkReadFilterExactKeyLengths`, `BenchmarkReadFilterExactHotRanks`
and `BenchmarkReadFilterExactConstruction` with allocations. Compare
paired current/linear runs; include different hotspot ranks, cycling
keys, length gaps, same-length misses, small/large groups and short/long
construction. Do not add wall-clock thresholds to ordinary UT.
3. Run `BenchmarkCatalogTombstoneMultiKeyCheck` separately for actual
persisted-object integration cost.
4. For public smoke, start a test-owned service and wait for SQL
readiness plus `ISCP-Task Start`; run the vector index plugin smoke with
normal mo-tester comparison, verify teardown, and repeat on the same
instance.
5. In the original nightly/remote-storage environment, verify unrelated
catalog history does not restart the whole DDL, genuine concurrent
catalog changes still cause safe retry, and cancelled internal SQL stops
its persisted check. Measure complete index-build phases separately from
component benchmarks.

No CI wait or claim that the full CI matrix has passed.
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…rigin#28359)

## What type of PR is this?

- [x] BUG
- [x] Improvement
- [ ] API-change
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue matrixorigin#28357

This fixes the reproduced catalog tombstone-row bailout mechanism; keep
the issue's original large-scale nightly acceptance separate from the
focused evidence below.

## What this PR does / why we need it:

### Design intent and root cause

matrixorigin#23868 (`728817e98f`) introduced PK-aware tombstone checks specifically
to prevent unrelated catalog changes from restarting long IVF builds.
However, `tombstonePKExistsInRange` still returned `changed=true` once
selected objects contained more than 50,000 rows, **before checking the
requested PK or row commit timestamp**.

The selection includes physically created/deleted tombstone objects.
Compaction can therefore select historical deletes unrelated to the
requested catalog key; object row counts do not establish a logical
metadata change. The consumer chain is `LockMeta -> LockRows ->
PrimaryKeysMayBeModified -> PKPersistedBetween`. A conservative positive
becomes an RC/definition retry, and `Compile.Run` rolls back/rebuilds
the complete statement. A late index-update registration can
consequently redo clustering and the entire mapping phase.

The issue records three `tombstone_rows_bailout` retries during one
client CREATE INDEX. That incident evidence and the deterministic
source-level mechanism are consistent, but this PR does not
independently identify every concurrent tombstone producer or prove that
each historical target key was unchanged.

### Changes and preserved behavior

- Thread the physical table ID into tombstone checking. The four
canonical IDs recognized by `catalog.IsSystemTable` inspect copied PKs
instead of using the row-count shortcut. No index-algorithm, table-name,
account, or issue-specific special case.
- Preserve the strict `>50,000` cost guard for user tables; count with
`uint64`.
- Use the existing 16-permit PK I/O semaphore for tombstone scans. The
data phase releases its permit first; acquisition is never nested.
Readers release each block before advancing, and the scan releases its
permit with `defer` on every return.
- Check the process context before scanning and between blocks.
Propagate caller/process cancellation during reads instead of converting
it into another apparent metadata-change retry. Ordinary read errors
still conservatively return changed.
- Preserve real PK hits, TN `(from, to]` and abort checks, conservative
CN hits, unknown visibility handling, lock/version fences, and statement
rollback semantics. Tombstones remain searched linearly by copied PK,
not by their rowid sort order.

### Risks, performance, and deliberate limits

This trades additional catalog validation I/O for avoiding a complete
expensive statement restart. It is not a zero-cost change: a missing key
scans selected tombstone blocks, with work proportional to that history
and key search cost. The semaphore bounds concurrent block readers, not
total elapsed time, object metadata, or the existing shared cache. Slow
storage can still prolong a check; process cancellation remains the
termination mechanism, and no new fixed timeout, worker, retry loop,
cache, configuration, or logging stream is introduced.

The existing `changed_objects_bailout` and `candidate_blocks_bailout`
remain unchanged. Real conflicts and unavailable evidence may still
require retries. This is **not** a blanket promise of zero catalog/DDL
retries, nor a redesign of multi-phase index building. Prelocking alone
would not close reentrant validation; suppressing the retry or retrying
only the final REPLACE would weaken transaction/snapshot correctness.

Local Darwin/arm64 Apple M4, Go 1.26.4, LocalFS (disabled MO caches, OS
cache possible), three one-second microbenchmark samples:

| Selected tombstone rows | Scan time/op | Allocated bytes/op |
|---:|---:|---:|
| 1 | 19–21 us | ~5.3 KB |
| 50,000 | 0.78–0.83 ms | ~30 KB |
| 50,001 | 0.76–0.86 ms | ~30 KB |
| 100,000 | 1.59–2.24 ms | ~54 KB |

These measure successful negative checks, not a comparison to the old
incorrect constant-time bailout, not peak RSS, and not remote-S3/nightly
latency. The 10M-row/768-dimensional/109-minute nightly was not rerun
locally; no numeric end-to-end speedup is claimed.

### Validation and counterexamples

Base: latest main `62770aedaa0cf3b5613bb7a42371bb08ef14ed5c`. Three
changed files, production behavior localized to disttae.

- **Red before green:** the same `PKPersistedBetween` regression using a
real encoded 50,001-row TN tombstone object failed on `0b195e4f5a` with
`tombstone_rows_bailout`: absent catalog keys and out-of-range deletes
returned true; an already-cancelled context returned no error. It passes
with the fix.
- Reused lightweight file-service/process fixtures, no new cluster UT.
Tests cover all canonical catalog policies, retained user-table guard,
CN and TN objects, a real hit in the last block, compaction of
historical deletes, open lower/closed upper timestamp boundaries, mpool
accounting, read errors, cancellation before work/while awaiting a
saturated permit/during I/O, permit release, and a successful subsequent
check. Phase barriers, not sleeps, trigger cancellation; cleanup joins
the worker and closes owned file services.
- Full disttae normal suite passed (final run 8.238 s); full disttae
race suite passed (final run 11.118 s). Focused cancellation race test
measured 0.02 s, then ran 100 times in one process (final run 3.637 s).
Existing tombstone and timestamp/abort tests remain enabled.
- Full lockop consumer suite passed. `go vet` for disttae and `make -j8
build` passed. Native artifacts were built through the platform-aware
`make cgo` owner, with verified source provenance.
- Existing `vector_index_plugin_smoke.sql` ran in normal mo-tester
comparison mode on a fresh, test-owned standalone service after SQL and
ISCP readiness: **22/22 twice**, 0.262 s and 0.192 s. It validates
HNSW/IVF creation, catalog metadata, SHOW CREATE, search, and rejection
with the feature disabled. Database and table catalog residue were both
zero after each run. No SQL/result files or mo-tester changes. An
initial absolute dotted temporary-path invocation failed result-file
discovery and executed no SQL; it is not counted as BVT evidence.
- Rebased from `0b195e4f5a` to `62770aedaa` (only frontend clone/lineage
locking and its tests changed upstream). Disttae and lockop suites were
rerun after rebase; race/benchmark/IVF evidence is reused because those
exercised paths and native inputs are unchanged.

### Review

Self-review plus an independent read-only counterexample/ownership audit
found no production blocker. Verified permit ownership across
data/tombstone phases, no nested semaphore acquisition, and no reverse
lock edge through tombstone I/O. No wire, persisted catalog format,
configuration, or index implementation changes. The existing
`PKPersistedBetween` process-context contract is unchanged; arbitrary
contexts differing from `tbl.proc.Ctx` are not newly promised.

| Audit | Ownership / termination |
|---|---|
| Q1: cleanup | Per-block readers release buffers; deferred scan permit
release; test-owned FS/process cleanup and zero mpool residue |
| Q2: waits | Non-nested semaphore admission observes context; readers
receive that context; cancellation needs no metadata lock or semaphore
permit |
| Q3: growth | Existing 16-permit block-I/O admission; sequential block
lifetime; no new queue, worker, retry state, or diagnostic cardinality;
selected-object metadata remains snapshot-proportional |

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
VioletQwQ-0 pushed a commit to VioletQwQ-0/matrixone that referenced this pull request Sep 17, 2026
…matrixorigin#28361)

## What type of PR is this?

- [x] BUG
- [x] Improvement

## Related changes

Follow-up to matrixorigin#28359; related to matrixorigin#28357. The lost caller-context defect
reproduces both on matrixorigin#28359 and its pre-PR base; it was not introduced by
that PR's catalog-tombstone policy change.

Final head: `725319c627ce358827ce54b31025c5d10df89e25`, base `main` at
`074bc173a5b64ed0ff0b6ad6ab091f478bf76c27`. Preserves the earlier
cancellation fix, length-rejection fix and concurrent SCA cleanup.

## Root cause and implementation

### Persisted PK checks must use the operation's context

`PrimaryKeysMayBeModified` / `PrimaryKeysMayBeUpserted` accept a caller
context, but `PKPersistedBetween` replaced it with the relation's
transaction-process context. Internal SQL using an existing transaction
can have a shorter statement deadline, so cancellation did not reach
metadata/block reads or PK I/O admission.

Pass caller context through the persisted boundary, metadata/BF reads,
predicate construction, data/tombstone reads and permit admission.
Observe cancellation between objects/blocks and at return: a synchronous
or cache-backed read completing after cancellation cannot turn
cancellation into successful validation or a metadata-conflict retry.
The shared transaction process is not mutated.

Actual PK conflicts, `(from, to]` commit-TS/abort filtering,
conservative unknown/I/O outcomes, user-table cost guards, and the
existing 16-permit admission policy remain unchanged.

### Exact unsorted membership should not repeatedly compare long common
prefixes

Tombstones are ordered by rowid, not their copied original PK;
binary-searching the source would be incorrect. The previous unsorted
varlen algorithm is O(rows × keys). Searching owned needles improves
large misses, but full-tail byte binary search has two counterexamples:

1. Unequal lengths with long common prefixes lose equality's cheap
length rejection.
2. Equal-length duplicate-heavy input concentrated just beyond the first
eight keys regresses: with 4096 needles and a 2KB prefix, hot rank nine
previously measured about 998 us versus linear's 289 us per 1024 rows.

The final immutable descriptor keeps original byte ordering for
sorted-source lookup and the first eight comparisons. Its tail is
length-ordered, copying only slice headers when the original order is
not length-monotone. Search rejects absent lengths before touching
payloads, then:

- compares a same-length group of at most eight keys directly;
- keeps binary search for larger inline-key groups;
- uses a once-built standard Go string map for larger out-of-line-key
groups.

Only eligible long groups pay for hashing. The threshold uses the
existing `types.VarlenaInlineSize` representation boundary, not an
issue-specific key size or table/index type. Pure exponential bracketing
was measured and rejected because moving from rank nine to rank
seventeen still regressed.

Map keys share only the descriptor's already-cloned, immutable Go-heap
payloads via the existing byte-to-string helper; no second payload copy
or caller/cache-buffer retention. Maps are completely constructed before
publication, never mutated by search, and may safely be shared by
combined predicates. Transient source-byte string lookups do not
allocate or retain source values. There is no per-block lookup
construction, global cache, lazy initialization, new worker, lock, retry
or timeout.

Small-key, sorted-source, constant, prefix/range,
NULL/unavailable-column and OID-mismatch semantics remain intact. No
wire/storage/catalog formats, authorization rules, config, native code
or generated files change.

## Performance and costs

Darwin arm64 / Apple M4, Go 1.26.4. Same-process paired
current/previous-linear benchmarks, median of three 100ms samples. These
are component measurements, not SQL/TPCC/nightly throughput claims.

1024 flat source rows, 2048-byte common prefix, 4096 needles:

| Hot byte-order rank | Previous linear | Final implementation |
| --- | ---: | ---: |
| 9 | 291 us | 288 us |
| 10 | 324 us | 282 us |
| 17 | 538 us | 313 us |
| Cycle over 32 tail keys | 770 us | 302 us |

The prior 998us regression is removed. The cycling case does not depend
on consecutive-value memoization. Repeated original PKs across different
rowids/versions are valid tombstone input; this is not the shape of an
ordinary unique-PK data block.

8192 rows, short-key **in-range misses**:

| Needles | Previous linear | Final implementation |
| ---: | ---: | ---: |
| 9 | 516 us | 168 us |
| 64 | 3.23 ms | 0.331 ms |
| 1024 | 48.3 ms | 0.645 ms |
| 4096 | 181 ms | 0.766 ms |

Miss scans allocate zero bytes. The 4096-key all-first-key control is
37.6us versus linear64.5us. Every measured length-shape variant (9/16/64
keys, 16/256/2048-byte prefixes, shorter/gap/present-length nonmembers
plus actual hits) remains faster than its paired linear control.

Construction is not free and can be paid even if subsequent blocks are
sorted or constant:

- Short single-key descriptors remain 168B/4 allocations; 4096
equal-length short keys remain 163968B/4099 allocations. Mixed short
keys needing a secondary order use 262304B/4101 allocations; the
existing auxiliary holder grows by eight bytes.
- A 4096-key, 2KB-prefix constructor totals about 1.47ms/9.75MB for
equal lengths or 5.18ms/9.85MB for mixed lengths, including original
payload cloning and sorting. Its once-built hash metadata is roughly
0.21MiB for 4096 entries, not another 8MiB payload copy.
- No claim of universal improvement on every input or platform.
Machine-load variation is visible in controls; the original nightly
workload has not been rerun.

Selected history still determines total scan work. The permit limit
bounds concurrent block readers, not total metadata/history.
Cancellation remains cooperative for synchronous CPU work and
third-party readers that ignore context.

## Validation

Final source, before committing without further code edits:

- Focused `TestReadFilterExact*`: PASS, 0.547s. Complete offset oracles
cover VARCHAR/VARBINARY, empty/duplicate/arbitrary bytes, all key
positions, unequal-length gaps, sparse mixed small/large groups,
original-buffer mutation, sorted/unsorted and combined predicates, and
real sealed cache-backed vectors without full-column cloning.
- Explicit group-size and inline/out-of-line boundary tests cover 16/17
total keys and `VarlenaInlineSize` / `VarlenaInlineSize+1`.
- New concurrent reuse test: four private source vectors share one
immutable combined hash-backed descriptor after caller buffers are
overwritten; exact offsets and misses verified. `-race -count=100` PASS,
1.568s.
- Final normal owning/consumer packages: objectio2.781s,
objectio/ioutil1.032s, readutil2.126s, disttae9.010s. All four pass `go
vet`.
- Final owning race suites: objectio6.644s, disttae12.056s.
- Final complete Search/KeyLengths/Construction/HotRanks benchmark
matrix: PASS, 74.354s. Functional offsets are checked independently
before timing the added hotspots.
- Native-aware tests verify matching native-source/platform provenance
and use the supported linked-test runtime loading setup. `gofmt -s` and
`git diff --check` are clean.

Retained evidence for unchanged cancellation behavior:

- The same deterministic public-entry probe fails before the fix and
passes after it: caller/reader/returned errors all reflect
`context.Canceled`, with the transaction parent still alive.
- One-row actual persisted fixtures cover VARCHAR/BIGINT data and
tombstones, Modified/Upserted callers, metadata cancellation,
cancellation after admission, completing non-cooperative reads,
full-permit waits, release and healthy reuse detecting real conflicts.
No sleeps or cluster startup.
- The existing real 50001-row tombstone fixture retains
catalog/user-table policy, last-block conflict and commit-time boundary
oracles, with multi-key coverage and no extra heavy fixture.
- Three earlier named cancellation/admission tests have 100-repetition
race evidence; their synchronization is unchanged, and the final disttae
owning race suite exercises them again.
- Earlier lockop checks and full native-aware mo-service build passed.
Before these internal algorithm follow-ups, real-service
`vector_index_plugin_smoke.sql` passed 22/22 twice in normal comparison
mode on one clean-start instance; teardown left no database/table/index
residue and the owned service was stopped. This historical SQL smoke is
not claimed as rerun on the latest hash implementation. Final
encoded-cache and real persisted-object tests validate the changed
internal boundary without another cluster-heavy fixture.

## QA test plan

1. Use `.agents/skills/mo-dev/scripts/mo-cgo-test` to run
`TestReadFilterExact*`, the persisted caller-context tests, and the
related owning/consumer packages. Run objectio/disttae under race and
exact concurrent-reuse/cancellation tests individually under stress.
2. Run `BenchmarkReadFilterExactSearch`,
`BenchmarkReadFilterExactKeyLengths`, `BenchmarkReadFilterExactHotRanks`
and `BenchmarkReadFilterExactConstruction` with allocations. Compare
paired current/linear runs; include different hotspot ranks, cycling
keys, length gaps, same-length misses, small/large groups and short/long
construction. Do not add wall-clock thresholds to ordinary UT.
3. Run `BenchmarkCatalogTombstoneMultiKeyCheck` separately for actual
persisted-object integration cost.
4. For public smoke, start a test-owned service and wait for SQL
readiness plus `ISCP-Task Start`; run the vector index plugin smoke with
normal mo-tester comparison, verify teardown, and repeat on the same
instance.
5. In the original nightly/remote-storage environment, verify unrelated
catalog history does not restart the whole DDL, genuine concurrent
catalog changes still cause safe retry, and cancelled internal SQL stops
its persisted check. Measure complete index-build phases separately from
component benchmarks.

No CI wait or claim that the full CI matrix has passed.

This branch was previously deployed

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

Labels

kind/bug Something isn't working kind/enhancement size/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants