Skip to content

[Bug]: ORM count() rewrites SQL with str.replace in three implementations #31381

Closed

Description

@Ariznawlll

DRAFT 6 (SDK, 2026-10-27) — candidate issue, not yet filed

Title: [Bug]: ORM count() rewrites SQL with str.replace and returns wrong values for custom columns, group_by, or string literals

Description

Three sibling implementations — Query.count() (orm.py:505), BaseMatrixOneQuery.count() (orm.py:1969), and AsyncQuery.count() (async_orm.py) — all "count" by text-surgery on the built SELECT:

sql, params = self._build_sql()
sql = sql.replace("SELECT *", "SELECT COUNT(*)")   # async_orm.B. / BaseMatrixOneQuery — only this one line
result = ... rows[0][0] ...

(Query.count() at :505 additionally tries sql.replace(f"SELECT {', '.join(cols)}", "SELECT COUNT(*)") — same family, one more fallback.)

Failure modes, all reachable from documented API usage:

  1. Custom column select (async_orm/BaseMatrixOneQuery path): session.query(User).select(User.id).filter(...).count() builds SELECT id FROM ...; the replace("SELECT *", ...) misses → the SQL stays SELECT id ..., and rows[0][0] returns the first id value, not the row count. Silent wrong number.
  2. GROUP BY: with group_by(...), the real count is the number of groups; the rewritten query still returns one row per group and rows[0][0] picks the first group's id again.
  3. String literals containing SELECT *: filter(User.note == "SELECT * FROM t") — the replace hits the literal too, corrupting the predicate (SELECT COUNT(*) FROM t inside the WHERE literal → broken quoting). Contrived but demonstrates the fragility of text surgery as an architecture.
  4. Joins with qualified columns: _build_sql() may render SELECT users.id, ... — again misses the literal SELECT * match in the two simpler impls.

Verified statically (code above quoted verbatim from all three sites); behavior follows directly.

Reproduction

with client.session() as s:
    cnt = s.query(User).select(User.id).filter(User.age > 18).count()
    # expected: row count;  actual: first matching user's id (an arbitrary number)

Impact

  • count() is the standard pagination/exists-check primitive; users get plausible-looking-but-wrong numbers with no error — pagination math (page size, has_next) silently off; "count == 0" existence checks give false negatives/positives.
  • The same file already contains a correct pattern (build a fresh query with only WHERE-like clauses and COUNT in the projection, as Query.count()'s copy-then-rebuild does) — the two later rewrites regressed to text surgery.

Expected behavior

Rebuild the count query structurally (the :505 approach minus the replace): a fresh builder with COUNT(*) projection, carrying over where/joins/group/having, and for GROUP BY also wrapping as SELECT COUNT(*) FROM (<grouped query>) g. No string replacement. A regression table: custom-column select, group_by, join, literal-containing-'SELECT *', and plain count asserting exact expected integers.

Activity

  1. added
    kind/bug
    on Oct 27, 2026
  2. added this to the MO-202610 milestone on Oct 27, 2026
  3. added theissue type on Oct 27, 2026
  4. Ariznawlll commented on Oct 29, 2026

    @Ariznawlll
    CollaboratorAuthor

    结论

    测试不通过。当前 main 的新查询接口已能正确计数分组结果,但公开 legacy matrixone.orm.Query.count() 仍返回第一个组的行数。本轮补实际运行证据,不另提同根 issue。

    关键证据

    • 版本:main@c6683bd2f531dcaa80e153c0924dac619c49dc9d;SDK直接导入同提交源码0.1.16,本地隔离CN/TN/LogService;运行时git_version()=c6683bd2f5。
    • 三个独立新库,每库Sales(id,grp,amount)为4行,grp分别1、1、2、3。Query(Sales,client).select('grp','SUM(amount)').group_by('grp').count() 三次均返回2,正确分组结果数为3。
    • 正常对照 client.query(Sales.grp,func.sum(Sales.amount)).group_by(Sales.grp).count() 三次均返回3。底表仍4行,后续SELECT1正常。
    • clients/python/matrixone/orm.py:566-584仍将SELECT文本替换为COUNT并读取第一行;同文件新接口1550附近已使用子查询包装。复现只需先写4行上述分组数据,再执行两条Python查询,无特殊SQL模式或边界名称。

    待解决点

    • 修复或明确停止支持legacy Query.count的分组、投影、分页语义;用相同结果集行数对照验收,不能把新接口通过外推到legacy接口。
  5. Ariznawlll commented on Oct 29, 2026

    @Ariznawlll
    CollaboratorAuthor

    结论

    测试不通过。当前 main 的 legacy Query.count() 仍会在分组、HAVING 和分页下返回错误计数;属于本 issue 的扩展,不重复提单。

    关键证据

    • 版本:main@c6683bd2f531dcaa80e153c0924dac619c49dc9d;同提交构建的隔离双 CN,3 个新建库。legacy Query 走同步客户端;现代查询另验证同步及异步客户端。
    • 源表 15 行,三个分组分别有 5、4、6 行。查询 SELECT grp FROM sales GROUP BY grp 的实际结果是 3 行,legacy all() 也是 3 行,但 legacy count() 返回 5;加入 HAVING count(*) >= 4 同样返回 5 而非 3,均 3/3。
    • 同一分组查询添加 LIMIT 2,实际结果 2 行但 legacy count 返回 5;添加 LIMIT 1 OFFSET 1,实际结果 1 行但返回 5;普通非分组 LIMIT 2 OFFSET 1 返回 15 而不是 2,均 3/3。
    • 现代 SDK 同步/异步相同查询的计数与完整结果数一致,48 项比较通过;原生派生表计数对照一致。普通未分页查询返回 15、空集返回 0;错误列查询后原表仍为 15 行,连接可用。
    • legacy Query.count 构造计数查询时遗漏分页信息,分组时又只取第一组结果;这不代表现代查询入口也仍存在相同现象。完整 SQL、参数和结果见 sdk_legacy_count5.json/.log。

    待解决点

    • 保留的 legacy 接口应与其结果集数量一致;回归覆盖分组、HAVING、LIMIT/OFFSET、空集、正常计数及同步/异步现代入口对照。
  6. added a commit that references this issue on Oct 30, 2026
    bbfe556
  7. XuPeng-SH commented on Oct 30, 2026

    @XuPeng-SH
    Contributor

    QA handoff for merged #31774 (main bbfe55669a1440424914d45a283a1d0e36f722fa): please verify legacy and modern count with GROUP BY, HAVING, pagination and empty sets. This isolated QA run inspected the issue and merged source but did not run tests or a live MatrixOne service at this SHA because resource headroom under the existing guard was insufficient. Earlier QA counterexamples and PR author-reported validation remain scoped to their recorded versions and are not results of this QA run.

  8. Ariznawlll commented on Oct 30, 2026

    @Ariznawlll
    CollaboratorAuthor

    结论

    测试通过。legacy、现代同步和异步 ORM 的 count 保留分组、HAVING 和分页语义,不再把第一组的行数当作结果集数量。

    关键证据

    • 官方 main@d39d8a40343ccd40bf665036388df7a40ee867f8;修复 PR fix(python): unify SDK query and analytics lifecycle contracts #31774 合并提交 bbfe55669a1440424914d45a283a1d0e36f722fa 在祖先链;实际二进制和 SDK 同完整 SHA。本地隔离 1 CN / 1 TN / 1 LogService,Python 3.12、SQLAlchemy 2.0.43。
    • 三个独立库,15 行分为 5、4、6 行三组。三个接口的分组结果行数及 count 均为 3;HAVING count>=4 仍为 3;LIMIT 2 返回 2,LIMIT 1 OFFSET 1 返回 1;legacy 非分组 LIMIT 2 OFFSET 1 返回 2。
    • 现代同步 JOIN 对照返回 5;包含字面量 SELECT * FROM t 的过滤 count 为 1,空集为 0。未知字段被拒绝后源表仍 15 行、连接可用,每轮测试库清理。
    • 回归已加入 MOTR #295,定向 3/3 通过、0 skipped。

    待解决点

  9. Ariznawlll commented on Oct 30, 2026

    @Ariznawlll
    CollaboratorAuthor

    回归位置更正:#295 已关闭并汇总至 MOTR #298,该 issue 的定向用例已包含在 #298。此前测试证据与未覆盖项不变;#298 尚未合入,完整 MOTR suite 未运行。

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

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions