Skip to content

fix(python): unify SDK query and analytics lifecycle contracts - #31774

Merged
XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/python-sdk-systemic-20261029
Oct 30, 2026
Merged

XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/python-sdk-systemic-20261029

Conversation

@XuPeng-SH

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

Copy link
Copy Markdown
Contributor

What type of PR is this?

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

Which issue(s) this PR fixes:

Fixes #31745
Fixes #31741
Fixes #31730
Fixes #31729
Fixes #31672
Fixes #31671
Fixes #31670
Fixes #31660
Fixes #31657
Fixes #31652
Fixes #31651
Fixes #31650
Fixes #31648
Fixes #31644
Fixes #31643
Fixes #31642
Fixes #31641
Fixes #31640
Fixes #31639
Fixes #31638
Fixes #31615
Fixes #31613
Fixes #31612
Fixes #31610
Fixes #31588
Fixes #31440
Fixes #31416
Fixes #31415
Fixes #31414
Fixes #31405
Fixes #31404
Fixes #31403
Fixes #31402
Fixes #31400
Fixes #31399
Fixes #31398
Fixes #31395
Fixes #31394
Fixes #31393
Fixes #31392
Fixes #31391
Fixes #31390
Fixes #31389
Fixes #31385
Fixes #31382
Fixes #31381
Fixes #31378
Fixes #31238
Fixes #31195
Fixes #31185
Fixes #31177
Fixes #31149
Fixes #31123
Fixes #31106
Fixes #30069
Fixes #30068
Fixes #30067
Fixes #30066
Fixes #30059
Fixes #30053
Fixes #30052
Fixes #30051
Fixes #30050
Fixes #30049
Fixes #30048

What this PR does / why we need it:

Python SDK entry points disagree about mapped table identity, type processing, batch columns and transaction ownership. The resulting failures include writing to a current-database namesake, materializing values against the wrong columns, losing queued rows and reporting ambiguous writes as definite failures. File/Arrow APIs also need one consistent contract across sync, async, pooled connections, cancellation and cleanup.

This change closes those boundaries in their existing owners:

  • Use shared SQLAlchemy compilation and result processing for mapped schemas, aliases, projections, scalar ordinals, typed mutations, indexes and actual EXPLAIN statements. Reject snapshot mutations before dispatch; preserve queued insert order and the common missing-NULL/extra-column policy.
  • Keep actual alias/selectable identity through inferred JOINs and re-aliasing. Compile correlated SQLAlchemy expressions with their enclosing SELECT; reject missing required binds before execution. Statement-local bind/CTE ownership evaluates a shared callable once without leaking values between statements or into reentrant user callbacks.
  • Consolidate shorthand DDL/type and manager result handling. Preserve DATETIME/TIME/TIMESTAMP fractional precision, align qualified/quoted CREATE and DROP targets, and register all six existing vector types for table/view reflection. Preserve DOUBLE/BINARY/primary keys; validate vector/JSON/fulltext inputs; apply pool settings per physical connection with serialized publication and rollback.
  • Complete async file/Arrow APIs using the existing file plan. Bound blocking conversion, staging and independent unlink work; retain exact file/table ownership through cancellation, reconnect and cleanup failure. Direct relation close, context exit and construction failure share one retained cleanup task; retries join pending work and repeat only failed identities. Public cleanup retries obey the same operation deadline. Stream with unbuffered cursors and discard unread transports on early exit.
  • Preserve original catch classes while exposing known phase/commit outcomes. Add explicit driver-bound execution, read-only capability observations and optional value-free phase telemetry. Cached capability observations cannot veto a different selected CN.
  • Make default LOCAL import usable through a one-use exact-path grant on the actual connection, including aiomysql setup. Explicit disabled/unrestricted settings retain their documented meanings.
  • Route generic Stage file suffixes through the existing file loader, preserving per-file sync errors and async awaitables.
  • Correct native Stage catalog literals, canonical names, URI resolution and combined ALTER using the existing transaction. Add percent-encoded path-form Stage URIs without changing legacy host-form behavior. Report the executing SQL mode in server responses so DBAPI escaping agrees after session changes, without introducing an SDK mode cache.

The scope reconciles all 65 assigned SDK reports, including functionality already present in the base that is retained and validated. It does not represent every existing analytics implementation as newly written here. See design revision 2.4 and the usage/compatibility guide for ownership, alternatives, failure outcomes and migration boundaries.

Issue-to-owner map
Issues Shared owner and corrected behavior
#30059 #31123 #31149 #31177 #31195 #31378 #31381 #31404 #31613 #31639 #31640 #31641 #31642 #31644 #31652 #31657 #31660 SQL text and SQLAlchemy compilation, physical query identity, projections/results, snapshots, mutations and EXPLAIN.
#31106 #31391 #31610 #31612 #31643 Insert/batch column preparation, mapped targets and queued-value ownership.
#31382 #31390 #31392 #31393 #31398 #31399 #31400 #31402 #31403 #31638 #31648 #31650 #31651 #31670 #31671 #31672 Shared type/DDL compilers, index metadata, fulltext grammar and physical pool settings.
#31185 #31238 #31395 #31414 #31415 #31440 File/CSV/JSON contracts, optional dependencies, Stage source mapping and scoped LOCAL authority.
#31385 #31389 #31394 #31405 #31416 #31588 #31615 Shared manager result handling, exact metadata, Stage catalog/URI/transaction ownership and explicit Session boundary.
#31729 #31730 #31741 #31745 Existing vector reflection registry, contextual SQLAlchemy compilation and required-bind validation, and generic Stage file loading.
#30048 #30049 #30050 #30051 #30052 #30053 #30066 #30067 #30068 #30069 File/Arrow exploration, checked uploads/results, bounded async lifecycle, recovery, capabilities, errors, telemetry and dependency/result contracts.

Validation

Base/merge-base: 641c34d259447a6b70ce1ce0615a610e9d1a108e. Local Go tests use the repository CGo wrapper, verified native artifacts, -race -short -tags matrixone_test -p=1 and bounded timeouts.

  • Python offline/analytics suite: 2604 passed, 206 skipped, 95 subtests passed. Online skips are not counted as native coverage. All 82 Python files in the complete PR delta pass configured fatal flake8 and Black checks.
  • Final wheel compatibility contracts: 153 passed each on Python 3.8 / SQLAlchemy 1.4.24 / minimum PyMySQL+aiomysql without Arrow; Python 3.8 / SQLAlchemy 1.4.54 without Arrow; and Python 3.9 / SQLAlchemy 2.0 / Arrow 21. The final wheel is byte-checked against the source, installed outside the source tree, and includes query/correlation, required/default/callable binds, DDL identity, reflection, Stage, cleanup and worker contracts. Real one-slot pools and blocked unlink controls cover timeout/cancel, joining pending cleanup, partial DROP retry and retained staging admission; mutation testing verifies the deadline oracle rejects an untracked retry.
  • Native follow-up: 9 scenario groups passed on an owned two-CN MatrixOne cluster: exact fractional temporal readback, qualified and atomic-dotted CREATE/DROP, aliased correlated scalar/EXISTS queries on sync/async clients, required-bind UPDATE rejection with unchanged rows, mixed Stage CSV/text/missing inputs, and all six vector types through table/view/nested-view full and scalar-only reflection. Subsequent callback-normalization, result-naming and immutable compiler-adapter changes pass the final offline and wheel suites above; unchanged native SQL behavior reuses these results.
  • Full native analytics coverage on Python 3.12 across SQLAlchemy 1.4.54 / 2.1.4 × PyArrow 18.0 / 18.1 / 21, with S3-compatible service, permissions, two CNs and no skipped cases. Five cells pass 302/302 in one full run. SA1.4/Arrow18.0 combines 301 unchanged passes with successful revalidation of its corrected S3 fixture; the original collision failure is retained in the evidence. All 12 affected S3/proxy/deadline cases × 6 cells (72) pass on the final test source. Shared fixture names and proxy Nagle delays were corrected without weakening the fault/outcome assertions.
  • Eight-thread resource soak: 30 s warmup + 90 s measurement, 2479 measured operations, no query errors, owned catalog leaks, checked-out connections or server pinned bytes; FD count 12 → 12, peak 13; RSS growth stays below the 64 MiB budget. Arrow bytes reach zero after a recorded GC checkpoint; database/FD/catalog counters are measured before GC.
  • Go incremental SCA: go vet ./pkg/frontend ./pkg/datalink ./pkg/stage/... and configured golangci-lint --new-from-rev=<base> pass, 0 new lint issues. Full Datalink/Stage/resolver package race tests and affected existing/new frontend race tests pass, including protocol handshake, actual OK/EOF packets, concurrent close and Stage rollback.
  • Existing mo-tester cases: Stage 156/156 and snapshot system-table restore 365/365 passed through the normal comparator on an owned two-CN fixture. Remove five obsolete combined-ALTER error goldens; retain their following catalog/restore assertions and malformed/empty Stage URI controls. New Go test headers pass the configured license check.
  • Native Stage: 32 passed across sync/async, quoted/encoded/Unicode names, table-case policies 0/1 and default/NBE SQL modes. Normal mo-tester comparison: 7/7 passed. Exact catalog values, combined ALTER, failed-validation atomicity, nested reads, file load/export and cleanup are checked.
  • Native managed/adopted connection controls verify driver-bound quote/backslash values, mode toggles, transaction bits, reconnect/physical pool reuse. Default/disabled/explicit LOCAL imports pass six cells on both current source and release 4.2.5; minimum-driver current-server controls also pass.
  • Reused independent evidence: actual pool/read/LOAD/COMMIT cancellation and lost-reply controls; isolated same-host dual-CN and permission checks; local S3-compatible emulator (11 passed, not cloud certification); SDK-process SIGKILL recovery (4 cases).
  • A 1M-row, 256-byte payload stream under 128 MiB additional address-space headroom returns the exact checksum, with about 6.2 MiB RSS growth. This is a bounded-memory result, not a general throughput claim. Disabled-observer paired SQLite microbenchmark adds about 0.74 microseconds per call; database latency is not inferred from it.
  • Owned native server SIGKILL/restart: 4/4 passed before COMMIT, after acknowledged COMMIT, during an observed live Arrow LOAD, and after the first stream batch. Independent recovered counts/checksums and zero checked-out connections are asserted. The private fixture allows the existing CN lease to drain before readiness (3-minute discovery / 200-second harness bounds); production timeouts are unchanged.

Earlier rebase validation: the SDK/workflow/Stage payload was unchanged at that rebase; this follow-up changes Python only and retains the kernel race/SCA evidence. The new base includes LOCAL framing and tenant-bootstrap changes; new-base frontend/LOCAL framing/Stage/protocol race tests, full Stage package race tests, go vet and configured incremental lint pass; the rebuilt owned two-CN server passes 24 async/Stage/admin/multi-CN cases, 12 current/minimum-driver LOCAL cells, driver SQL-mode/transaction/pool controls and the 7/7 normal Stage BVT. Existing client compatibility, soak and crash evidence is reused only for unchanged boundaries.

CI failure follow-up: the new Go header, Datalink negative-URI and five combined-ALTER golden failures are corrected and pass their affected checks. The earlier five CDC/constraint/restore timeouts and the publication-cancellation failure did not reproduce in isolated race runs after releasing the task-owned fixture. Their original cause is not established; fresh full CI is still required.

Alias and bind ownership follow-up

Mapped ORM aliases now retain their SQLAlchemy selectable during query admission. Callable binds execute once per built statement, including shared fragments, and refresh on query reuse; missing required binds and callback failures surface during build before dispatch. All five public query owners follow the same boundary.

Both built-in logical_in forms use the actual query root for fulltext subqueries, preserving derived projections, filters and re-aliasing. SQLAlchemy columns adapt to that root; strings retain identifier validation and extension overrides remain intact. Async explicit-database queries render anonymous physical aliases consistently with their projected columns; explicit names retain existing validation and quoting.

Validation of this follow-up: full offline contracts pass on SQLAlchemy 1.4.54 / 2.0.43 / 2.1.6 (2,560 / 2,556 / 2,564, zero skipped); analytics has 101 passing and 206 online-only skipped. Black and fatal flake8 pass. Mypy diagnostics match the verified starting-head baseline (8 imported-module diagnostics, no introduced diagnostics), rather than an unqualified mypy pass. Native MatrixOne alias/derived fulltext rows match independent SQL, and async anonymous aliases pass for normal/64-character table names. The owned native binary is 0c519dd414, not a rebuilt PR-head server; its fulltext Boolean planner source matches the PR head. Wheel/sdist and twine pass, with wheel source-byte identity verified. Installed-wheel tests pass 94/94 each on Python 3.8.20 with SQLAlchemy 1.4.24 / 1.4.54 / 2.0.43 (the latter two use mounted SQLAlchemy source overrides). Independent gpt-6.1-terra / max final overall review reports PASS, zero material blockers for commit 54f390bcace20ee595e1f3d9895b3b0e14ec01a9; committed blobs and wheel bytes match the reviewed/tested content. Fresh CI is pending for this update.

This follow-up changes Python only; unchanged kernel race/native matrices above are reused. No Go race gate applies to this delta. Arbitrary derived MATCH support remains backend-dependent; native errors propagate. Duplicate anonymous aliases in self-JOIN remain a separately identified limitation, also present at the merge base.

Compatibility and limits

All CNs must be upgraded before using the new quoted Stage name/URI contract. Stage ALTER in a caller Session is rejected before dispatch because the administrative transaction is owned by the server. Existing comma-separated credential storage remains; ambiguous comma/key forms are rejected before mutation.

Required binds must be supplied; explicit NULL is valid. Conflicting definitions for one non-unique bind name across separately compiled query fragments reject before execution: use distinct names, reuse one bind, or execute a complete SQLAlchemy statement. Correlated expressions that depend on opaque string JOIN sources also reject; modeled SQLAlchemy JOINs retain their correlation.

Core Python 3.8 works without Arrow; analytics requires Python 3.9+. SQLAlchemy 1.4.24 is the supported floor. Release 4.2.5 explicitly lacks native Arrow LOAD; a successful read or version string does not certify upload support. Non-default per-index BM25 configuration is rejected; query-scoped ranking remains available. SQL text logging now defaults to off; explicit legacy log modes remain available.

An externally configured aiomysql engine that skips every OK-producing initialization must initialize each physical session before driver binding under global NBE; some driver versions discard authentication/EOF status. A SELECT alone does not fix that driver behavior. The SDK does not promise arbitrary raw-driver or older-server NBE safety.

Cancellation cannot force-stop caller filesystem/readers. Their bounded operation retains its permit and owned path until actual completion; process SIGKILL may leave recorded artifacts requiring reconciliation. Dispatched COMMIT without acknowledgement remains unknown and is never retried automatically.

A four-expression compilation microbenchmark measures about 286 microseconds/build after immutable compiler-class reuse, down from 375 for the initial repair but up from 168 on the previous PR head. This is the measured correctness cost of shared required/default/callable bind accounting; it is not a database throughput measurement. The bounded cache stores compiler classes only, never query values or engines.

Incorporates and adapts queued-insert work from #31653, credited to MOLW in the commit. That contributor's PR is not modified.

Design: accepted revision 2.4 and the follow-up binding addendum from actual gpt-6.1-terra / max. Final overall review uses that same model/effort, with independent gpt-6-astra / xhigh challenge reconciliation as requested. Both reconcile the complete PR and report no unresolved material blocker for abdaca3e87. Fresh GitHub CI remains pending; local checks do not represent every CI job as green.

Capability observation ownership correction

Capability discovery now keeps one bounded cache slot on the selected physical connection and includes the actual CN server_id in its existing metadata query. Same-build CNs and distinct pooled sessions no longer share observations. Connection replacement, SDK settings policy changes and reconnect generations invalidate the relevant observations. Failed refresh discards old values; invalidated connections preserve the original driver error. Unknown/unsupported node IDs use uncached observations. Manual session-setting changes require explicit refresh; observations do not guarantee a later proxy-selected backend's capabilities. The public version identity tuple remains compatible.

Ordinary SQL adds zero capability probes. A warm explicit discovery still uses one SQL round trip, verified on two owned CNs and through actual pooled connections. Five paired in-memory microbenchmark samples measure about 0.19 microseconds more local CPU per explicit discovery (1.196 → 1.386 µs); this is not database/network latency. Older servers lacking a usable node ID fall back to fresh discovery rather than unsafe cache reuse.

Validation: final-source offline/analytics run 2673 passed, 206 skipped, 95 subtests passed, followed by the added real two-record QueuePool regression passing separately. Final capability closure 29 passed each on Python 3.8 / SQLAlchemy 1.4.24 minimum drivers, Python 3.8 / 1.4.54, and Python 3.9 / 2.0.55. Complete-PR configured fatal flake8 and Black pass across 82 Python files. Native two-CN read-only checks confirm matching versions, distinct nonempty CN IDs, sync/async discovery, and one-round-trip warm discovery. The owned fixture exited successfully. Unchanged Go race/SCA and earlier native evidence retain their original scope; this Python-only correction has no applicable Go race detector. Repeated query-test dispatch setup was replaced with the existing shared helper.

Actual gpt-6.1-terra / max design and final overall review reconcile this correction with the complete PR; no material blocker remains for d19c196876043f9e09895656df140a13ff5a5334. Fresh remote CI is pending.

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

Close mapped query/type/DDL, file/Arrow, async ownership, capability and
execution contracts across the assigned SDK issue set. Repair the shared
Stage catalog/URI and SQL-mode status boundaries required by those APIs.

Adapt queued-insert ownership work from PR matrixorigin#31653.

Co-authored-by: MOLW <[email protected]>
@XuPeng-SH

XuPeng-SH commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor Author

mo-bot review · mo-bot-local · done

Commit: 88a27b2bb94b7cf21269df1c337b18d4e6bd5099

Review completed. Read the assessment.

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

mo-bot review · mo-bot-local · review

Commit: 88a27b2bb94b7cf21269df1c337b18d4e6bd5099

Assessment: request_changes

One confirmed async cleanup lifecycle defect remains. The complete delta and supplied discussion were reviewed; source remains unchanged.

Model: gpt-6-astra / xhigh

Session: 01a1869d-820c-7212-9788-aecfb86a4141 · slot 0 · generation 2

  • P2 clients/python/matrixone/async_analytics.py:461: Calling the documented await relation.close() while the connection pool is exhausted or DROP stalls.
    Impact: Explicit cleanup bypasses both the operation deadline and bounded finalizer wrapper. It can block the caller beyond the documented cleanup bound and remains invisible to disconnect/reconnect tracking.
    Evidence: The retained SQLAlchemy/aiosqlite pool probe shows relation.sql() timing out at 50 ms, while close() remains pending after 5.25 seconds with neither _tasks nor _finalizers registration. Releasing the pool permits successful cleanup. See probes/async_relation_close_unbounded.py and checks/1793284773446644548-2.json. Route public close through bounded, retained cleanup ownership while preserving exact table identities for retry, and cover this direct-call path.

Validation:

  • Python offline and analytics suite: 2525 passed, 95 subtests passed, 206 skipped; receipt checks/1793284467016060005-2.json.

  • Full stage and stageutil short race suites passed; receipt checks/1793284987126530184-2.json.

  • Focused frontend Stage and MySQL status race tests passed; receipt checks/1793284934831152103-2.json.

  • Isolation preflight passed. Receipts, source fingerprints and retained logs reconciled in validation-audit.json; both discussion keys assessed exactly once.

Limitations:

  • Skipped Python cases are not passes. Native dual-CN, crash-recovery and release-wheel matrix claims were not independently rerun.

  • Thirty linked issues were omitted from the supplied evidence.

Use the existing tracked-operation and finalizer owners for direct relation
close and cleanup retries. Join pending DROP work after cancellation or
timeout, seal further relation use, and retry only failed table identities.

Cover real pool exhaustion, partial cleanup and blocked unlink admission.
Align Datalink and existing Stage/snapshot expectations with path-form Stage
URIs and combined ALTER, and repair the new Go test license headers.
This was referenced Oct 30, 2026
XuPeng-SH added a commit that referenced this pull request Oct 30, 2026
…data (#31802)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

Fixes #31736
Fixes #31394

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

`export.to_csv()` currently lets a recognized filename suffix silently
select JSONL or Parquet. Specify `FORMAT 'csv'` in the shared SQL
builder used by sync/async clients and Stage shortcuts. Normal and
unknown suffixes produce CSV; conflicting recognized suffixes receive
the server's existing format-mismatch error. No second suffix parser,
capability probe or export retry is added.

The account mapping reported in #31394 was fixed by #31774, but user
creation and listing still extract the current account from the first
`SHOW ACCOUNTS` column. Pass the result metadata through the existing
shared account converter for those four sync/async consumers. Preserve
empty/multiple-account and legacy rows-only behavior, without
constructing Account objects for every visible tenant just to determine
the current account.

Validation:

- Full Python offline/analytics: **2686 passed, 206 skipped, 95 subtests
passed**. Skips are not native coverage.
- Account/export contracts: **141 passed each** on Python 3.8 /
SQLAlchemy 1.4.24 with minimum drivers; Python 3.8 / 1.4.54; Python 3.9
/ 2.0.55.
- Configured fatal flake8, Black and `git diff --check` pass for the
complete four-file delta. Python-only change; no applicable Go race
detector. Sync/async public entry points are exercised.
- Owned two-CN integration: **18 cases passed** across sync/async and
Stage paths. Actual CSV bytes/readback cover comma, embedded quote,
Unicode and NULL; all ten conflicting-suffix calls reject with a
format-mismatch error, source rows remain unchanged and subsequent
queries succeed. Before the fix, the public CSV API's `.jsonl` output
was independently parsed as JSON. The owned fixture exited successfully.
- That integration fixture uses the earlier task-owned kernel with
unchanged relevant OUTFILE grammar/format-validation paths; it is not an
exact-main native certification. Existing CSV-header behavior is
independently tracked and is outside this format fix.

Compatibility: explicit OUTFILE FORMAT requires server grammar
introduced by #23369 (also used by the existing JSONL exporter). Older
unsupported servers return an error; the SDK does not retry an export
whose outcome could be uncertain. This adds no SQL round trips or
ordinary-query probes.

Actual `gpt-6.1-terra` / `max` design and final overall review are
recorded for this change. Remote CI remains pending.

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/api-change kind/bug Something isn't working kind/documentation Improvements or additions to documentation kind/enhancement kind/feature kind/refactor Code refactor kind/test-ci size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

2 participants