Repository navigation
fix(python-sdk): unify query contracts and atomic manager operations - #31262
Merged
XuPeng-SH merged 15 commits intoOct 26, 2026
Merged
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? |
Contributor
Author
|
mo-bot review · Commit: PR head changed during fetch |
This was referenced Oct 27, 2026
Closed
Closed
Closed
Closed
Closed
Closed
XuPeng-SH
added a commit
that referenced
this pull request
Oct 27, 2026
…1322) ## What type of PR is this? - [x] API-change - [x] BUG - [x] Improvement - [x] Documentation - [ ] Feature - [x] Test and CI - [x] Code Refactoring ## Which issue(s) this PR fixes: Closes #30963 Closes #31023 Closes #31312 Closes #31314 Related to #30067, #30068, #30069 and #31262. ## What this PR does / why we need it: Unify Python SDK execution and SQL construction across MatrixOne 4.1.x and 4.2.x. Immutable snapshot Selects remain cache-keyed through Client, Session and export compilation, including caller caches warmed before engine adoption. Preserve the caller's driver, dialect, pool and typed results. Shared-engine adoption preserves supported SQLAlchemy 1.4 string execution. Compiler-owned late snapshot literals preserve percent/placeholder-like names, avoid caller parameter collisions, and prevent execution arguments from replacing snapshot identity. Raw/export compilation preserves escaped parameter names and their type processors across SQLAlchemy versions. Explicit configuration overrides take precedence over invalid lower-priority environment values. Buffered fetch sizes cannot rewind cursors and retain integer-index compatibility. Administrative managers/builders share identifier and grammar-string construction; metadata booleans, fulltext LIMIT 0, native error sources/errno and async user cleanup preserve their public contracts. Clone managers verify target existence after acknowledgement on the same executor. Safe manager `if_not_exists=True` uses a catalog observation and plain CLONE because native CLONE IF NOT EXISTS can append duplicate data. The catalog check now preserves exact names for `lower_case_table_names=0` and uses binary comparisons, so an existing `target` no longer makes an absent `Target` a successful no-op. Released servers can still lowercase a CLONE internally in mode 0, so a conflicting sibling may result in a native error; the SDK propagates it. In mode 2 a successful native clone can be followed by a failed `SHOW CREATE` verification for mixed-case names; the SDK reports this instead of claiming success. Raw builders reject the unsafe flag. Session retains transaction/rollback ownership; async clone phases share one timeout. This costs two statements ordinarily, three for a missing target with the safe flag, and one for an existing-target no-op. Snapshot compilation adds one bounded compiler-owned literal and no network roundtrip; no throughput improvement is claimed. Validation of the delivered source: - Python 3.12.12 complete offline suites: SQLAlchemy 1.4.54 / 2.0.43 / 2.1.6 passed **2195 / 2191 / 2199** tests, plus **95 subtests each**, with zero failures/errors/skips. Includes deterministic async cancellation and execution ownership, as well as the explicit disposable-server opt-in guard. - Isolated native **4.1.0 and 4.2.6**, **48 clone cases each**, zero failures/errors/skips. These cover three naming modes, sync/async Client/Session, database and qualified/unqualified table names, differently cased schema and table names, existing-target no-op, native conflict propagation, successful lowercase and mode-1 mixed-case clones, rollback and single-connection pools. Independent native probes exercise Unicode, escaped lookup literals and native CLONE controls. - The earlier **782 native cases on 4.1.0–4.1.6 and 4.2.0–4.2.6** qualified the previous source. The rebase changed no SDK or SDK-workflow inputs; that evidence remains relevant to unchanged boundaries, while clone behavior was revalidated as described above. [Earlier qualification](https://gist.github.com/XuPeng-SH/0329a8729ef9194c9e325f0ddd9178bf). - Changed-file Black, configured fatal flake8, syntax and diff checks pass. Changed-runtime-file mypy reports **458 diagnostics versus 460 on the merge base**, with no introduced path/message/code finding. Wheel/sdist build and twine checks pass; all 56 shipped Python modules match the tested source. - `gpt-6.1-sol/xhigh` design and final overall review completed with no unresolved material blocker. No Go code changed; Go race detection is not applicable. Current source hashes, dependencies, native release identities, test results and per-case JUnit: [validation evidence](https://gist.github.com/XuPeng-SH/b52035e12a1d99564cf757f919621757). Hosted checks must run on the new head; previous hosted results apply only to `36721e73cf`. Full native server contracts require `MO_SDK_DISPOSABLE_SERVER=1` and a serial, exclusively owned disposable server or tenant because the case-mode tests temporarily change a tenant-global setting. Standalone qualification excludes optional TLS/S3/HNSW, multi-CN, async Arrow and the baseline unsupported direct `matrixone://` DBAPI entrypoint. Native Stage/fulltext limitations remain narrow native-versus-SDK negative contracts. The separate existing analytics suite is outside this release certification.
4 tasks done
This was referenced Oct 28, 2026
mergify Bot
pushed a commit
that referenced
this pull request
Oct 28, 2026
…31524) The escaping parts of #31384 are already fixed on `main` (#31262 for `metadata_scan` and #31322 for `_build_moctl_sql`; see the issue comment). This PR fixes what is left: expected behavior #2, a non-JSON `mo_ctl` reply. **Root cause.** 1. `_execute_moctl` (sync in `moctl.py`, async in `async_client.py`) called `json.loads(result_str)` directly. On a plain-text reply it raised `MoCtlError("Failed to parse mo_ctl result: Expecting value: line 1 column 1 (char 0)")`, and the server's actual output was lost. 2. A `MoCtlError` raised inside the `try` block (no rows, or a `returnStr` other than `OK`) was caught again by `except Exception` and re-wrapped, so the message read `mo_ctl operation failed: mo_ctl operation failed: table not found`. In the async manager the same re-wrap also hid the JSON error behind the generic prefix. **Fix.** - New `_decode_moctl_result()` in `moctl.py`, shared by both managers. On non-JSON it raises the manager's own `MoCtlError` class: the sync manager uses `matrixone.moctl.MoCtlError` and the async manager uses `matrixone.exceptions.MoCtlError`, as before. - The error message includes a raw-output preview (capped at 500 chars). The full text is available as `error.raw_output`. - `except MoCtlError: raise` lets SDK errors pass through unwrapped. Other exceptions are still wrapped as before. **Tests** (`tests/offline/test_moctl.py`): - `test_execute_moctl_non_json_keeps_raw_output`: a sync plain-text reply keeps the raw text in the message and in `raw_output`. - `test_async_execute_moctl_non_json_keeps_raw_output`: the same check for the async manager. - `test_execute_moctl_failed_return_str_is_not_double_wrapped`: the message is exactly `mo_ctl operation failed: table not found`. **Results:** - Before the fix, all 3 new tests fail (the actual message was `mo_ctl operation failed: mo_ctl operation failed: table not found`). After the fix, all 3 pass. - `test_moctl.py` + `test_moctl_simple.py`: 26 passed. - `pytest tests/offline` (Python 3.13, run locally): 2289 passed, 95 subtests passed. - `black --check` is clean. `flake8` reports no new warnings (4 before, 4 after; all are existing unused imports in `async_client.py`). 3 files, +61/-9. 本操作由 LW 授权的 Grok Bot 智能体执行 Approved by: @XuPeng-SH
XuPeng-SH
added a commit
that referenced
this pull request
Oct 28, 2026
## What type of PR is this? - [x] Improvement - [x] Code Refactoring - [x] Test and CI - [x] Documentation ## Which issue(s) this PR fixes: Follow-up to #29947 and the changes in #31020, #28987, #31000, #30054 and #31262. ## What this PR does / why we need it: `cumrank` rescanned the partition prefix for every output row, while wide constant-width `mrank` repeatedly scanned its frame. Use a compressed frequency index that starts at the current output demand and grows geometrically. This reduces repeated comparisons without indexing the entire partition before the first result. Rebuilds seed the active physical frame, preserving NULL, NaN, tie and eviction semantics. The index is optional and accounted. Capacity rejection falls back to scanning; if required output allocation runs out of capacity, release the index and retry the same fixed-width append once. Cancellation and invalid-account errors still propagate. Completed partitions, reset and free release the index. Small/variable widths and all-NULL partitions retain scan paths; `tmrank` retains its civil-time semantics. Also share the SORT ROLLUP type capability between planner and executor, consolidate Python identifier quoting while preserving API behavior, fix test-helper cleanup on error, correct the Decimal64 DISTINCT benchmark's group distribution and repeated-hit workload, and replace review-history transcripts with links. Existing inexpensive small-input oracle tests remain. [Design and execution/memory contract at this revision](https://github.com/matrixorigin/matrixone/blob/e4fb331b5229b52ef8613151e083c8e7dbe1966c/docs/design/20261023-local-sliding-window-ranks.md). ## Validation - Full Window package tests and full package race run passed. Regressions cover output-budget fallback, later-batch pressure, failed retry, cancellation, sealed accounts, reset/reuse, short/NULL prefixes and frame seeding across growth. - Focused ROLLUP planner/executor, Decimal64 and nonempty colexec mock lifecycle race checks passed; unchanged-path evidence remains applicable. - Incremental `go vet`, configured golangci-lint v2.14.0 and molint passed for affected Go packages. Golangci reported no new issues; molint emitted only pre-existing diagnostics on unchanged source. - Python SQL parameter/identifier boundary suite: 105 passed. - Isolated single-CN SQL smoke through the real MySQL frontend: 8,205 rows with NULLs and ties; cumulative and width-128 ranks matched an independent row-by-row oracle across output-batch growth. - Same-host baseline/candidate microbenchmarks used the same harness and native build, GOMAXPROCS=2, three one-operation samples. Medians against the merge-base implementation: | Workload | Baseline | This PR | | --- | ---: | ---: | | 1M rows, mrank width 128, first output | 17.64 ms | 4.56 ms | | 1M rows, mrank width 128, full consumption | 2,174 ms | 1,329 ms | | 1M rows, cumrank, first output | 505.95 ms | 4.41 ms | | 16K rows, cumrank, full consumption | 2,069.90 ms | 7.91 ms | Width-127 scan control remained approximately 32 ms. These are microbenchmarks, not production workload results. Geometric rebuilding raises total allocated bytes for full 1M-row width-128 consumption from about 41.7 MB to 91.9 MB; first-output allocation is about 8.86 MB versus 8.65 MB. These figures are cumulative allocation, not peak memory. Full 100K-row all-NULL cases were approximately 0.6–0.9 ms slower. Input remains materialized. Variable-width/time-based rank scans, explicit-frame weighted percentile, and ROLLUP state reuse remain separate follow-ups. Distributed BVT was not run locally; CI for the updated head is pending.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What type of PR is this?
Which issue(s) this PR fixes:
Closes #30242
Closes #31202
Closes #31203
Closes #31204
Closes #31205
Closes #31206
Closes #31207
Closes #31208
Closes #31209
Closes #31210
Closes #31211
Closes #31212
Closes #31213
Closes #31214
Closes #31215
Closes #31216
Closes #31217
Closes #31218
Closes #31219
Closes #31220
Closes #31221
Closes #31223
Closes #31224
Closes #31225
Closes #31226
Closes #31227
Closes #31228
Closes #31229
Closes #31230
Closes #31231
Closes #31233
Closes #31234
Closes #31235
Closes #31236
Closes #31238
Closes #31240
Closes #31242
Closes #31243
Closes #31244
Closes #31245
Closes #31246
Closes #31247
Closes #31248
Closes #31249
Closes #31251
Closes #31252
Closes #31253
Closes #31254
Closes #31255
Closes #31258
Closes #31259
Closes #31260
Closes #31241
Closes #31263
Closes #31266
Closes #31267
Closes #31276
Related to #30067 and #30069; this does not claim completion of their broader scope.
What this PR does / why we need it:
The Python SDK had divergent sync/async SQL construction, incomplete transaction ownership and manager APIs that could silently return incorrect data or partially apply batches. This consolidates those boundaries and adds native-result, failure, cancellation and dependency-version contracts.
Validation
README.md,README_USER.mdanddocs/quickstart.rst, and rejects the prior same-sessionasyncio.gather(session.execute(...))pattern.git_version=1a44f3d): 70 required native contracts passed, zero skips. Source server v20261026, actual binary 305be60 built from main 83c1e23: 70 passed, zero skips. Later kernel merges were not rebuilt or claimed as tested.5fbb1bc564aefc1f9059236646fe61faef32019ecompleted successfully (run): all six Python SDK offline matrix jobs, CI preflight and CI Required passed. Online/native and kernel/coverage jobs were skipped by SDK-only routing; the separate Iceberg adapter tidy job passed, while Iceberg E2E Local was skipped. The retained local native JUnit reports predate the documentation and SQLite fixture corrections; neither correction changes SDK runtime or native tests. CI for the updated head is pending.Review correction: portable schema-routing oracle
The legacy
Query.first()retainsLIMIT 1. Reusing that Query for an UPDATE made the schema-routing offline test depend on SQLite's optionalENABLE_UPDATE_DELETE_LIMITextension. The mutation now uses a fresh legacy Query, preserving every schema-routing, row-value, default-table isolation and deletion assertion. MatrixOne UPDATE/DELETE LIMIT semantics remain unchanged.E9,F63,F7,F82) passed for the changed test module. No Go code changes; Go race is not applicable, and Python has no equivalent Go race detector.CI routing
This PR changes only
clients/python/**. The SDK workflow configuration enhancement is split into supporting CI PR #31265, so the existing trusted classifier selects scope=sdk and omits kernel UT/BVT/coverage. The new AsyncSession documentation regression is undertests/offline; the existing issue contract tests remain undertests/offline/contractsandtests/online, selected by the existing trusted SDK workflow. The supporting CI change also filters the independently triggered Iceberg workflow; that filter only takes effect after it enters the trusted base.Compatibility and cost
Decimal literal expansion is capped at 4096 characters before allocation. The native report records a 4.2.5 limitation for some 38-fractional-place literal values; no SDK workaround changes server semantics. Both native release and source targets are tested explicitly; these results do not imply support for every historical MatrixOne release. LOCAL loading now defaults off. Invalid/ambiguous IDs, metric names, duplicate vector labels, conflicting explicit database targets, joined UPDATE/DELETE and unsupported snapshot/fulltext syntax raise instead of silently producing misleading results. Stage ALTER IF EXISTS returns None when absent.
Vector metadata is refreshed with two reads per query. Explicit per-column metadata statistics require sequential scans proportional to the observed column count; wildcard metadata retains its fast path. Upsert performs whole-batch validation before its transaction. CSV inference is bounded and cannot guarantee an immutable file after validation. Submitted COMMIT outcomes are not retried or represented as guaranteed rollback. Details and reproduction commands are in clients/python/TESTING.md and the design documents.
Mapped file checks add O(number of explicit files) bounded reads per validation point and reuse the active stream/write connection. They require native DATALINK read permission and do not pin object versions. A removed-and-restored file between checks may evade detection; emitted stream batches cannot be retracted after a terminal error. Unsupported URI/glob forms raise before execution. Fulltext group() supports positive word/prefix branches; conjunction/exclusion/phrase/nested branches are explicitly rejected.