Skip to content

[Bug]: Python ORM count/first and async failed builds break query semantics #30960

Closed

Description

@MatrixAdventurer

Is there an existing issue for the same bug?

  • I have checked the existing issues.

Searched Python SDK count(), first(), query reuse and async table-name issues plus current SDK PRs. The SQL-parameter-boundary work in #30059 / PR #30073 and SQL-builder clone-state PR #30877 concern separate owners.

Branch Name

main

Commit ID

e19f698

Other Environment Information

Linux, Python 3.12.14. Reproduced through the public Client/AsyncClient query entry points with a real SQLite SELECT executor. The source defects are in SDK query construction/state handling; no MatrixOne server or production environment was exercised. SQLAlchemy 1.4.54 and 2.0.55 are the repository CI compatibility ranges.

Actual Behavior

Three independently reproducible SDK bugs:

  1. count() textually replaces only SELECT *. With four rows (IDs 10/20/30/40, categories a/a/b/c), .select("id").count() returns 10 instead of 4; grouped/distinct category queries return "a" instead of 3; a SUM projection returns 100 instead of 1. .limit(2).offset(1).count() returns 0 instead of 2 because pagination is applied to the single aggregate row.
  2. first() sets the original query's LIMIT to 1. On an ordered page with limit=3, offset=1, a later all() returns only ID 20 instead of 20/30/40. The same corruption persists after the executor raises.
  3. Async _build_sql() restores its database-prefixed table only on success. A projection compilation error leaves the original table prefixed; fixing the projection and reusing the query generates a doubled database prefix.

Original-source regression output:

collected 19 items
test_count_reports_query_cardinality[projection-4-sync]
E assert 10 == 4
test_count_reports_query_cardinality[page-2-async]
E assert 0 == 2
test_first_preserves_original_page[sync]
E assert [20] == [20, 30, 40]
test_async_database_prefix_restored_after_build_failure
E sqlite3.OperationalError: near ".": syntax error
17 failed, 2 passed

The positive controls are zero-limit sync/async counts. The original source was exported from the exact commit above, with only the new behavioral test added.

Expected Behavior

count() returns the cardinality of the original query, including projection/grouping/distinct/aggregation/pagination, preserving its parameters. first() leaves the caller's query reusable after both success and failure. A failed async compilation restores the original table name.

Steps to Reproduce

Create query_rows(id, category) with rows (10,a), (20,a), (30,b), (40,c), route public Client/AsyncClient execute calls to that SQL executor, then:

client.query(QueryRow).select("id").count()  # expect 4
client.query(QueryRow).limit(2).offset(1).count()  # expect 2
query = client.query(QueryRow).order_by("id").limit(3).offset(1)
query.first()
assert [row.id for row in query.all()] == [20, 30, 40]

The accompanying regression file also exercises public async operations and reuses a query after a deliberately failing projection compilation.

Additional information

The prepared fix counts a derived query without rewriting its contents, executes first() on a shallow private copy that changes only LIMIT, and restores the async table prefix in finally. Scope: 3 files, +155/-20 including tests; no server, dependency, gate or workflow changes.

Verification: full SDK offline suite passes under SQLAlchemy 2.0 (1329 tests + 95 subtests) and 1.4 (1333 tests + 95 subtests). Fatal Python lint, focused test lint, compileall and diff check pass. MatrixOne online tests, SQL BVT and remote CI remain unverified.

Follow-up: legacy Query first()/scalar() state preservation (2026-11-01)

由 LW 授权的 ChatGPT Business 智能体提交。

The original fix covered modern sync/async query objects, but the separately exported legacy matrixone.orm.Query still mutates its own LIMIT. Its scalar() calls first(), so both terminal methods shrink a reusable page even after execution fails. Related legacy execution issue #31263 is already resolved; this is the remaining terminal-state behavior.

Verified on main 0df8dde, Python 3.12.14. Reuse the existing four-row SQLite fixture and instantiate the real exported Query directly. Before the fix, the expanded test file reports 4 failed, 23 passed: legacy first/scalar on success and executor error all leave all() returning only [20] rather than [20,30,40]. Modern sync/async controls pass.

Reuse the existing _first_query() private-copy owner. No new helper, query state, dependency or server SQL contract. Final focused regression: 27 passed on SQLAlchemy 2.1.6 and 27 passed on 1.4.54. Full offline suite on 2.1.6: 2916 passed, 103 subtests passed, 11 warnings, exit 0. Compileall, dependency check and diff whitespace check pass; test formatting passes after removing one blank line. SQLite fixture cleanup is reused. This proves Python query-object reuse, not live MatrixOne BVT or hosted CI.

Complete patch (2 files, +12/-10 lines):

diff --git a/clients/python/matrixone/orm.py b/clients/python/matrixone/orm.py
index ce56856..49ccb83 100644
--- a/clients/python/matrixone/orm.py
+++ b/clients/python/matrixone/orm.py
@@ -488,8 +488,7 @@ class Query:
 
     def first(self) -> Optional:
         """Execute query and return first result"""
-        self._limit_count = 1
-        results = self.all()
+        results = _first_query(self).all()
         return results[0] if results else None
 
     def one(self):
diff --git a/clients/python/tests/offline/test_query_execution_state.py b/clients/python/tests/offline/test_query_execution_state.py
index ab0287f..907c916 100644
--- a/clients/python/tests/offline/test_query_execution_state.py
+++ b/clients/python/tests/offline/test_query_execution_state.py
@@ -27,7 +27,7 @@ from sqlalchemy import Column, Integer, String
 from sqlalchemy.orm import declarative_base
 
 from matrixone import AsyncClient, Client
-
+from matrixone.orm import Query
 
 Base = declarative_base()
 
@@ -60,7 +60,7 @@ def make_query():
                 return client.query(QueryRow)
             client = Client()
             client.execute = execute
-            return client.query(QueryRow)
+            return Query(QueryRow, client) if kind == "legacy" else client.query(QueryRow)
 
         yield build
     finally:
@@ -103,20 +103,23 @@ async def test_count_preserves_filter_parameters(make_query, kind):
 
 
 @pytest.mark.asyncio
-@pytest.mark.parametrize("kind", ["sync", "async"])
-async def test_first_preserves_original_page(make_query, kind):
+@pytest.mark.parametrize("kind", ["sync", "async", "legacy"])
+@pytest.mark.parametrize("terminal", ["first", "scalar"])
+async def test_first_preserves_original_page(make_query, kind, terminal):
     query = make_query(kind).order_by("id").limit(3).offset(1)
-    assert (await resolve(query.first())).id == 20
+    result = await resolve(getattr(query, terminal)())
+    assert (result.id if terminal == "first" else result) == 20
     assert [row.id for row in await resolve(query.all())] == [20, 30, 40]
 
 
 @pytest.mark.asyncio
-@pytest.mark.parametrize("kind", ["sync", "async"])
-async def test_failed_first_preserves_original_page(make_query, kind):
+@pytest.mark.parametrize("kind", ["sync", "async", "legacy"])
+@pytest.mark.parametrize("terminal", ["first", "scalar"])
+async def test_failed_first_preserves_original_page(make_query, kind, terminal):
     query = make_query(kind).order_by("id").limit(3).offset(1)
     with patch.object(query.client, "execute", side_effect=RuntimeError("executor failed")):
         with pytest.raises(RuntimeError, match="executor failed"):
-            await resolve(query.first())
+            await resolve(getattr(query, terminal)())
     assert [row.id for row in await resolve(query.all())] == [20, 30, 40]
 
 

Activity

  1. XuPeng-SH commented on Oct 24, 2026

    @XuPeng-SH
    Contributor

    Local QA validation for merged PR #30961 (2b94111625d746d048468ccc214c6b27fc23bd0d).

    The Python SDK source was taken from pinned upstream main 0abc1d317aea608f3a228297d68e1ae4e619a3a2; the affected orm.py and async_orm.py blobs match the merge commit. I ran the public sync and async ORM entry points against isolated real MatrixOne SQL on the existing local service built from 6f773c556d4f3177f5373eb193cd576e080b662f (binary SHA-256 51489b59a60310e79eddcf1182c582685b2c60f800f35a0a625eb5359469349b, server reports 1.3.0). This is not a runtime binary built from 0abc.

    Result: 44/44 assertions passed; exit 0. Live SQL reproduced the pre-merge count rewrite’s projection 10 vs 4, offset page 0 vs 2, grouped result “a” vs 3, and SUM value 100 vs result cardinality 1. The fixed sync/async APIs passed projection, pagination, grouping, DISTINCT, aggregate, zero-limit and bound-filter counts. first() preserved the original page after success and SQL execution failure; an async projection build failure was followed by successful reuse; two concurrent AsyncClient sessions returned independent expected counts/rows. The disposable database cleanup read back zero.

    The pre-merge comparisons apply the old source-level count rewrite to live SQL; an old SDK binary was not run. This is focused issue-scope validation, not the full SDK suite, SQL BVT, restart testing or concurrency stress.

    Local fixture: current_main_0abc_30961_live_query_semantics.py; final log: live-query-attempt4.jsonl (SHA-256 bc4300332804f5d3b48b8c03f496c7585c20d3a67815f9832bf108f7f8dacde6).

  2. Ariznawlll commented on Oct 24, 2026

    @Ariznawlll
    Collaborator

    测试版本

    • 分支:官方 main;commit:a1888d62f89232a9bbe5830881b4f9b4d749cf42(修复 PR fix(python-sdk): preserve query execution semantics #30961 的 merge commit 2b94111625d746d048468ccc214c6b27fc23bd0d 为其祖先)。
    • 部署方式:隔离本地 macOS arm64,1 LogService / 1 TN / 1 CN,etc/launch,独立数据库;SDK 源码与服务均取上述 main。服务二进制 SHA-256:6cb033ea67757407ebdb946f784366b3a7819a11c61cd1a0fb4dac7a7ea1caab。Go 构建元数据的 vcs.revision 为上述 main;vcs.modified=true 是工作树内未跟踪的构建产物,构建时 git diff HEAD 无已跟踪文件改动。
    • 测试日期:2026-10-24(北京时间);Python 3.11.4、SQLAlchemy 2.0.45。

    原问题验证

    以四行 (10,a),(20,a),(30,b),(40,c) 通过真实 MatrixOne SQL 执行 Python SDK 的同步和异步公开 query() API,连续 3 轮,均通过:select(id).count() 实得 4;GROUP BY category 和 DISTINCT category 各得 3;SUM(id) 投影的结果行数为 1;LIMIT 2 OFFSET 1 的 count 为 2,原查询再读仍返回 ID [20,30]。这些均与 issue 的错误值 10、a、100、0 区分。

    Happy Path 覆盖

    1. 同步/异步 first() 在 ORDER BY id LIMIT 3 OFFSET 1 上都返回 ID 20,复用原查询仍得 [20,30,40];3/3。
    2. 带参数 id > 10 的 count 为 3,原查询仍得 [20,30,40];零 LIMIT 的 count 为 0;同步/异步各 3/3。每轮结束源表仍为 4 行。

    Unhappy Path 覆盖

    1. 故意令执行器抛错后,first() 将原异常传出且不污染原查询;恢复后仍得 [20,30,40],同步/异步各 3/3。
    2. 异步查询的投影编译故意失败后,改为合法投影复用,同一查询正确读取 [10,20,30,40],3/3;未产生额外表或改动四行数据。

    白盒验证

    在同一 main SDK 源码上,tests/offline/test_query_execution_state.py 与 test_stage_sql.py 合计 57 项各跑 3 轮,均通过;本问题主要为 Python 客户端构造/状态逻辑,不适用 Go race 路径。

    回归测试

    修复 PR #30961 已加入 clients/python/tests/offline/test_query_execution_state.py;本轮另用隔离脚本 /private/tmp/qa_sdk_a188_orm.py 做真实 SQL 3 轮复验。该缺陷发生在 SDK count/first 状态处理,纯 MOTR SQL 无法覆盖客户端复用语义;未新增 MO 或 MOTR PR。PR 的 Python SDK offline CI 与 CI Required 均成功;online CI 被跳过,本轮在线复验补充了上述路径;未运行全量 SDK/SQL BVT。

    测试证据

    测试结论

    测试通过。

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

Metadata

Metadata

Assignees

Labels

kind/bugneeds-triage

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions