Repository navigation
chore(skill): reuse CGo artifacts across worktrees - #27852
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
Fixes #27775 > [!IMPORTANT] > **Draft status on exact head `f48843c9e2`, rebased on `main` `07fe9a69c6`: deterministic implementation/code closure is complete. The causal A/B, 100M/1B endpoint evidence, and exact-head SQL/compile plus lockservice owner approvals are still required. Do not merge or call #27775 fixed from local tests.** Design: `docs/design/load_data_unique_index_locking.md`, revision v8. ## Problem and evidence boundary The reported 100M/1B indexed `LOAD DATA` regression correlates with hidden-UNIQUE per-batch lock encoding/submission, lock coarsening, higher mutex delay, and lower CPU utilization. The no-index control is comparatively stable. This is still a hypothesis, not proven causality. The exact #26706 parent/merge A/B (`6742f958d466` vs `35db232dfc3b`) has not been run. The earlier 5M experiment changed the normalized indexed/no-index ratio by only about 2.5%, so it is mechanism evidence, not proof that #27775 is fixed. Implementation was explicitly requested before that external gate; the PR therefore remains Draft. ## Current v8 design and implementation Only a positively identified large modern `LOAD DATA` can qualify: - fresh physical generation zero, retry enabled, non-internal and non-prepared; - statement-owned autocommit pessimistic RC (`Autocommit=true`, `ByBegin=false`); - finite effective input estimate `Cost*Rowsize >= 1 GiB`, uncompressed CSV/JSONLINE remote source; - one ordinary non-FK/non-partitioned/non-temporary user base table; - synchronous default/BTREE indexes with at least one regular UNIQUE hidden table; - v39 protocol and a real underlying `engine.LogtailReadBarrier` capability; - authoritative base/hidden PK types whose lockop table range covers the complete physical keyspace. Missing, contradictory, duplicated, unsupported, reused, or ambiguous state fails closed to exact `main` behavior. FLOAT/DOUBLE remain ineligible because the current finite table-range endpoints do not cover infinities and every NaN payload. Real production shapes such as a `uint32` base PK and binary-`varchar` composite hidden PK are admitted. The canonical logical plan is never mutated. Before source initialization, generation zero: 1. acquires the existing metadata/general and base full-domain locks; 2. acquires an Exclusive full-domain lock for every promotable hidden UNIQUE table, sorted by physical table ID; 3. invokes the existing v39 TN-ordered logtail read barrier; 4. advances the same pessimistic-RC transaction snapshot strictly beyond the applied frontier; and 5. returns one ordinary physical retry. The retry validates an exact coordinator-local proof: transaction ID, logical plan identity, physical generation, installed snapshot, frontier, and target value. It filters only covered hidden row targets from a local `LockOp` copy. Logical rebuild, reused generation, capability/protocol mismatch, or proof mismatch permanently disables the optimization for that `Compile.Run`. No protobuf/wire/catalog/durable-state change, planner cache policy, generic lock ordering, goroutine, channel, or production log site is introduced. ## Correctness and unhappy-path closure - The promotion creates one bounded context: `min(lock_wait_timeout, 120s, caller deadline)`. - That context's **absolute deadline** is copied into every lock RPC and clamped by any shorter session timeout. Remote owners therefore see the same authoritative deadline; target N cannot restart the budget consumed by targets 1..N-1. - Caller cancellation/deadline is preserved. Only expiry of the internal aggregate budget maps to lock timeout. - Hidden-lock, barrier, snapshot-update, capability, protocol, or proof failure publishes no proof and never initializes the source. - A successful lock wait may refresh the transaction snapshot. The narrow helper suppresses only the incomplete ordinary retry; the stronger common barrier still runs before proof publication. Definition changes keep the existing retry behavior. - Locks remain transaction/lockservice-owned. Compiler cancellation stops the wait but does not unlock a partially acquired prefix behind the transaction owner's back. Existing terminal autocommit rollback releases the whole transaction exactly once. - A real two-target test proves target 1 is owned while target 2 waits, cancellation returns, no barrier runs, rollback releases target 1, and a FastFail point contender then succeeds. - A real binary-`varchar` full-range test proves an interior Exclusive writer waits, the fenced retry is reentrant with no second barrier, and transaction rollback lets the writer proceed. - Admission tests cover the positive implicit-autocommit pessimistic-RC case and reject `BEGIN`, `autocommit=0`, SI, optimistic, mirror, aborted, and missing-ID transactions. Lifecycle audit: | Question | Closure | | --- | --- | | Q1: who owns cleanup? | The transaction/lockservice owns every acquired lock; compiler owns only schema-bounded proof metadata and disables/clears it on failure/rebuild. | | Q2: what can wait? | Each target wait ends through holder release, caller cancellation, aggregate deadline, lock timeout, deadlock, or service error; barrier/update use the same bounded context. No new goroutine or join edge exists. | | Q3: what can grow? | Targets and proof state are bounded by schema index count; there is one deadline, one barrier attempt, one retry, and one fixed-cardinality metric sample per admitted run. | ## Performance and operational risk The intended complexity change is: ```text before: O(input batches * UNIQUE targets * encoded keys) after: O(UNIQUE targets log targets) + one applied-logtail barrier + one physical recompile ``` Safeguards: - the ordinary non-LOAD top-level gate remains about 1.76 ns/op, 0 B/op, 0 allocs/op on Apple M4; - the complete eligible-plan classifier remains about 1.69 us/op, 1120 B/op, 14 allocs/op, once per fresh candidate LOAD; - retry proof lookup is binary over sorted physical IDs; - ordinary `doLock` callers pass a zero scalar deadline; no `LockOptions` growth, wrapper call around the existing non-inlined lock function, allocation, goroutine, log, or retained state was added; - `time.Now()` is not evaluated when neither the existing session timeout nor the promotion deadline is present; - the barrier metric has four pre-bound outcomes and fixed buckets; there is no dynamic label or log-amplification path. These checks bound implementation overhead only. Eligible LOAD still holds base and hidden domains through barrier, retry, execution, and commit, and pays one barrier plus recompile. Exact-main/final-head endpoint runs must decide whether that tradeoff is worthwhile. ## Why review kept finding new blockers, and what changed The repeated `Request changes` loop was a review-process failure, not one endlessly recurring defect: 1. implementation started before causal evidence and owner-approved design; 2. each pass repaired the latest counterexample and declared convergence without freezing the complete decision surface; 3. the design promised a broader matrix than committed tests actually proved; 4. code correctness, causal/performance evidence, and owner acceptance were mixed together, so an external pending gate repeatedly appeared as a new code defect. V8 separates three gates: deterministic code closure, causal/endpoint evidence, and owner acceptance. A missing code oracle requires code/test change; pending scale evidence or approval does not. Conversely, local green tests are not promoted into causal proof. Concrete issues found and resolved or explicitly removed from scope: - replaced the early planner/protobuf/FK-routing mechanism with a compiler-local, no-wire-change design; - rejected non-total FLOAT/DOUBLE key ranges; - normalized target ordering and static-NULL UNIQUE handling; - removed explicit transaction admission, redundant planner cache mutation, and a lock-held metric/fence design; - reused the existing close-aware v39 TN barrier instead of introducing a future-HLC/client protocol; - bound physical retry/source state to the installed snapshot and kept the canonical plan immutable; - aligned stated tests with reachable feature-owned contracts instead of duplicating all generic lockservice fault matrices; - fixed the final v7 gap where one context existed locally but each remote lock RPC recomputed its deadline; - fixed incomplete Apache headers that caused SCA failure. ## Exact-head local validation On `f48843c9e2` / base `07fe9a69c6`: - normal affected packages passed: `./pkg/sql/compile`, `./pkg/sql/colexec/lockop`, `./pkg/util/metric/v2`; - full owning-package race passed for compile and lockop; - measured focused race stress used `B=30s`, `N=100` and passed for both real-lockservice success/reentry and cancellation/deadline/prefix-release tests; - `go vet` passed for all three affected packages; - `license-eye header check`: 5906 checked, 4840 valid, 0 invalid, 1066 ignored; - `license-eye dep check` passed; - `git diff --check` passed. The isolated macOS worktree reused unchanged, platform-matched CGo and third-party artifacts from the primary checkout for these tests; no CGo source changes are in this PR. The reusable platform/provenance guard is submitted separately as #27852. ## Remaining merge gates and residual risks 1. **Causality:** alternating #26706 parent/merge 100M A/B with same-run no-index control and aligned lock/mutex evidence. If that boundary does not reproduce, abandon this mechanism and bisect the original range. 2. **Endpoint performance:** alternate exact current `main` and exact final head for at least three successful 100M runs per indexed shape plus no-index control; require >=80% recovery of the normalized regression gap and <=15% no-index median regression, then one 1B confirmation. 3. **Availability/deadlock:** direct/internal writers to hidden physical tables can wait behind a long full-domain LOAD lock and can add a multi-table deadlock edge. The real conflict/release contract is tested, but scale/cycle observations and lockservice-owner acceptance remain required. 4. **Optimistic writers:** they do not honor the promoted pessimistic lock. This PR preserves exact-main TN conflict/retry behavior and does not claim stronger exclusion. 5. **Lock retention:** successful LOAD retains base and hidden locks through retry, source initialization, execution, and commit; terminal failure relies on existing whole-transaction rollback. 6. **Shared prerequisite:** the design depends on #27842's v39 TN-ordered barrier and fails closed for older protocol/capability states. 7. **Mandatory exact-head review:** one SQL planner/compile owner and one lockservice owner must approve the same final commit. The existing `fengttt` approval is on the pre-v8 head and does not close this gate.
7d943ae to
e67682b
Compare
e8d0d53 to
46affec
Compare
|
Revision 2 implementation is now pushed at exact head Closed blockers:
Exact-head evidence: all four deterministic contract suites passed; shell/YAML/diff checks passed; license-eye checked 5010 files with 0 invalid; real Darwin/arm64 provenance verification and CGo wrapper passed; stable Per explicit delivery direction, implementation was pushed without waiting for remote CI. Real GPU compilation remains dependent on the CUDA/cuVS runner; hermetic Make counterexamples cover the semantic transitions locally. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
Review decision: REQUEST_CHANGES. GitHub does not allow the PR author to submit the REQUEST_CHANGES state, so this is recorded as a COMMENT review. This review covers every changed hunk at exact head 46affec048 and Revision 2 of the design.
The blockers from reviews 5060075176 and 5060172200 are materially addressed, and the overall direction—one structured generation key, one Make owner, atomic per-file staging, and monotonic recovery—is sound. A fresh first-principles pass still found three blocking gaps:
-
Git inspection failures after
prepareare treated as a clean tree and can publish dirty-built bytes under clean provenance. Incgo/mo-native-provenance:468-470and573-575, the checks use[ -n "$(git ... status ...)" ]. A failed command substitution produces an empty string; the surrounding[returns false, andset -edoes not preserve the lostgit statusexit code inside this conditional. Concrete path: cleanpreparewrites a reusable marker; native source becomes dirty; the worktree index becomes temporarily unreadable whilerev-parse HEADstill works; bothbeginandrecordcontinue; the build uses dirty source, whileemit_provenancerecords cleanHEAD. After the edit/index is restored, another worktree can accept those dirty-built artifacts.mo-cgo-test:80-81has the same fail-open form for the current/candidate worktree status checks. Capture status output and exit status separately and reject any inspection error at prepare/begin/record/verify and both wrapper roots. Add injected status-failure cases at every phase; the current test only covers failure duringprepare. -
The GPU generation omits a required runtime artifact.
emit_artifact_metadataandverify(cgo/mo-native-provenance:243-249,651-670) bind only the platformlibmoandthirdparties/install. GPUlibmo, however, loadscgo/cuda/mocl_kernel64.fatbinat runtime (cgo/cuda/cuda.cpp:40,90-95). Deleting or corrupting that fatbin after a stamped GPU build therefore leavesverifygreen. The linked-worktree wrapper also points the test at primarylibmobut never makes the fatbin available beside the temporary Go test executable, which is the exact directoryCudaEnv_initsearches. A clean stamped primary GPU generation can consequently be accepted and then return CUDA initialization error-1002/-1111, or execute stale kernel bytes. Make the conditional GPU sidecar part of the generation/provenance and runtime placement contract, then cover missing, corrupted/restored-mtime, and linked-worktree execution paths. Revision 2 cannot claim a complete GPU artifact contract without this. -
Supported CUDA flag channels can still override debug semantics, and the fatbin debug compile has no explicit
-O0.cgo/cuda/Makefile:261-272filtersNVCCFLAGSand setsCUDA_OPT_LEVEL=-O0, butEXTRA_NVCCFLAGS,CCFLAGS, andEXTRA_CCFLAGSare appended later. Exact-head dry-runs showEXTRA_NVCCFLAGS=-O3produces... -O0 ... -g -G -O3 ... cuda.cpp, whileCCFLAGS=-O3produces... -O0 ... -Xcompiler -O3 .... These are explicitly supported and hashed profile inputs. The full debugallpath also emits the fatbin command with-g -Gbut no-O0at all becauseCUDA_OPT_LEVELis used only forcuda.o. Thus a generation stampedoptimization=debugcan still contain optimized host/device code, contradicting design invariant I5. Normalize or reject optimization-bearing values across every supported CUDA flag family, apply the final debug level to bothcuda.oand the fatbin, and test the completealltarget with each conflicting channel rather than onlycuda.owithNVCCFLAGS.
Evidence checked/reused at exact head: Native contract on Ubuntu/macOS, native Docker builds on amd64/arm64, UT, SCA, coverage, and BVT checks all completed successfully; git diff --check is clean. The new counterexamples are outside those selectors: the contract suite targets only cuda.o and does not inject begin/record/wrapper status failures or model the runtime fatbin. Staging Q1/Q3 ownership, marker/temp recycling, one-process Make DAG ownership, old/current recovery monotonicity, format migration, and the SCA/UT duplicate-build removal otherwise close correctly. No SQL-visible behavior changed, so BVT is not the missing layer; deterministic shell/Make fault tests plus a real GPU runtime acceptance path are.
There was a problem hiding this comment.
Reviewed exact head 46affec from the structured-key, publication, interruption/recovery, and linked-worktree consumer boundaries. The prior staging, owner, recovery-monotonicity, GPU-profile, and debug-mode issues are materially closed, but two correctness blockers remain.
-
[P1] SIMSIMD_TARGET aliases distinct thirdparty generations. thirdparties/Makefile lines 146-150 consume SIMSIMD_TARGET directly to construct SIMSIMD_TARGET_ compiler flags, and a command-line value overrides the Makefile ordinary assignment. Consequently MO_CL_SIMSIMD=1 builds with SIMSIMD_TARGET=HASWELL and SIMSIMD_TARGET=SKYLAKE can produce different usearch bytes. cgo/mo-native-provenance lines 71-93 record only the boolean SIMSIMD field and USEARCH_CMAKE_FLAG; they omit SIMSIMD_TARGET, so the second invocation can reuse the first artifact. This violates I1, which requires every supported semantic native input to select a distinct generation. Add this input to the common profile, or remove/reject the override, and add changed/control transition tests proving rebuild-all versus reuse.
-
[P1] A failed current-worktree cleanliness check is interpreted as clean. In .agents/skills/mo-dev/scripts/mo-cgo-test lines 80-86, each git status runs inside a command substitution passed to a nonempty-string test. When git status exits nonzero and prints no stdout, the test sees an empty string and discards the failure. rev-parse and the subsequent tree-to-tree diff can still succeed because neither proves current worktree/index contents, while the provenance verifier only rechecks the primary root. A linked worktree whose status inspection fails can therefore carry dirty Make/CGo/thirdparty inputs yet reuse the primary artifact. Capture both status outputs with explicit failure checks before testing emptiness, and add a wrapper fault-injection test showing status failure rejects reuse.
These are reachable fail-open paths, not requests for speculative machinery. The green native workflows do not exercise either transition.
|
Revision 3 is pushed at exact head Closed review 5060532298:
Closed review 5060590639:
Additional same-shape closure found during self-review:
Exact-head local evidence: all four deterministic suites passed; real Darwin/arm64 full CGo build and wrapper smoke test passed; repeated clean The PR body and versioned design are updated to Revision 3. Remote CI is triggered but was not waited on. |
aunjgr
left a comment
There was a problem hiding this comment.
Reviewed exact head ba3580e, including implementation commit 293e4bd and the non-overlapping main merge. Revision 3 closes both prior blockers: linked-worktree status checks fail closed on command failure, and SIMSIMD_TARGET now selects a distinct common provenance generation with changed and control transitions.\n\nI traced the complete artifact closure through prepare, cleanup, begin, thirdparty/CGo build, atomic runtime-library and CUDA-fatbin publication, record, verify, linked-worktree consumption, CPU/GPU transitions, interruption recovery, and both GPU runtime images. The GPU generation binds matching source and staged fatbins to format 7; missing, mismatched, corrupted, or newer sidecars reject reuse; temporary test executables receive the verified absolute path; production keeps executable-side lookup. Cleanup and markers retain one effective owner, all scripted waits and failure paths terminate, and temporary or retained state is recycled or bounded. The new CUDA initialization also releases partially created module/context state on failure.\n\nAll exact-head CI workflows, including Linux/macOS native contracts and amd64/arm64 native builds, are green. Real CUDA compilation remains the explicitly documented GPU-runner boundary rather than an unsubstantiated validation claim. I found no blocking correctness, compatibility, lifecycle, or performance issue and approve design Revision 3.
LeftHandCold
left a comment
There was a problem hiding this comment.
Deep-reviewed exact head ba3580e against PR base 86aeb0e.
I traced the full native generation closure: prepare and monotonic recovery, required cleanup, one-owner thirdparty Make DAG, CGo and CUDA/cuVS debug propagation, atomic per-file library and fatbin staging, record and verify, linked-worktree selection, runtime fatbin placement, and both GPU images. Git inspection failures fail closed; source, platform, SIMSIMD and SIMSIMD_TARGET, compiler-profile, accelerator, optimization, artifact-content, freshness, and incomplete-generation transitions do not alias. Marker, temporary-file, CUDA module, and context ownership close on error or recovery, with no unbounded wait or retained-growth path.
Fresh exact-head shell syntax and all four deterministic native contract suites pass locally. Exact-head Native Dependency Checks are green on Ubuntu and macOS, including amd64 and arm64 native builds; MatrixOne ALL CI is also green. Real CUDA compilation and device execution remain the explicitly documented GPU-runner boundary.
No blocking correctness, compatibility, lifecycle, build, or performance issue found. Approved.
What changed
make cgoown the orderedprepare -> cleanup -> begin -> thirdparties/staging -> CGo -> recordprotocol.SIMSIMD_TARGET, compiler/SDK/flag profiles, exactlibmo, installed thirdparty content, and the conditional CUDA fatbin.MO_CUDA_FATBIN_PATH; production binaries keep the executable-side default./mo-servicein both GPU runtime images.Design
Versioned design Revision 3:
https://github.com/matrixorigin/matrixone/blob/293e4bda5d0ad8dd55775db6e99be328798a60fd/docs/design/native_artifact_generation.md
The design defines generation identity, ownership and publication linearization, recovery severity, supported concurrency/platform boundaries, GPU runtime placement, alternatives, performance, and acceptance evidence. Independent design approval remains required.
Root cause and reflection
The original implementation distributed generation truth among Make targets, environment variables, shell staging, provenance, and consumers. Repeated reviews found different manifestations of the same missing invariant: no component owned the complete generation from source inspection through runtime consumption.
Revision 3 closes that boundary rather than adding isolated exceptions:
libmo + thirdparties + CUDA fatbin source + identical staged/runtime fatbin, not only the linked library.SIMSIMD_TARGET, selects a distinct generation.The audit also fixed two existing unhappy paths in CUDA initialization:
/proc/self/exefromreadlinkis now checked for truncation and NUL-terminated beforedirname, and partial context/module initialization is released on failure.Correctness and unhappy paths
reuse: exact source/platform/key and all artifact hashes match; final content checks prove no build-time mutation.rebuild-cgo: CGo source/key, CPU/GPU, release/debug, accelerator profile,libmo, or fatbin drift.rebuild-all: SIMSIMD/SIMSIMD_TARGET, common toolchain, Makefile/thirdparty/platform, invalid stamp, or installed thirdparty drift.local: dirty or non-Git source can build locally but cannot publish cross-worktree provenance.TARGET_SIZE != 64is rejected before a GPU generation can be stamped because the runtime contract is 64-bit Linux/x86_64.Performance
make cgoruns.MO_CUDA_FATBIN_PATHis resolved once during CUDA static initialization; it adds no query hot-path work.-O3, while debug receives final device and host-O0.Validation
Exact implementation head
293e4bda5d:SIMSIMD_TARGETchanged/control transitions passed (rebuild-all/reuse).alldry-runs passed for base/extra device and host-O3conflicts; object and fatbin commands end with debug-O0and contain no effective release optimization.make cgopassed; realmo-cgo-test -count=1 -timeout=120s ./cgopassed.make cgocompiled nothing and retained identical stamp hash/mtime.git diff --check, and license-eye passed (5010 files checked, 0 invalid).origin/main86aeb0ecbfhas a conflict-free merge-tree with this head.Real CUDA/cuVS compilation and device execution still require the GPU toolchain/runner. Hermetic contracts cover the configuration, artifact-generation, placement, failure, and consumer boundaries without claiming device-level evidence.
Remote CI was triggered by the push but is not being waited on or used as a substitute for the local counterexample evidence above.