Skip to content

[Bug]: JSONPathElement.asbool compares JSON_EXTRACT output to the string 'true' #31393

Closed

Description

@Ariznawlll

DRAFT 16 (SDK, 2026-10-27) — to be filed

Title: [Bug]: JSONPathElement.asbool compares JSON_EXTRACT output to the string 'true' — yields always-false/ambiguous booleans

Description

JSONPathElement.asbool (matrixone/sqlalchemy_ext/json_type.py) implements JSON-boolean extraction as:

extracted = json_extract(self.column, self._current_path)
return extracted == 'true'

The generated predicate is json_extract(col, '$.path') = 'true' — comparing a JSON-typed extraction against the SQL string literal 'true'. Per MySQL semantics this comparison does not do what the API name promises:

  • In MySQL, JSON_EXTRACT('{"a":true}', '$.a') = 'true' is 0 (false): the left side is a JSON boolean, the right side a string; JSON-vs-string equality coerces through JSON value semantics, and true (JSON) does not equal 'true' (string). The documented way is JSON_UNQUOTE(...) or comparing against CAST('true' AS JSON) — the code path builds neither.
  • Consequently a filter like session.query(Product).filter(Product.specs['active'].astext_ok == True) built on asbool (or asbool == True) fails to match rows where the JSON value is true, and can produce engine-dependent results where JSON-number coercions are involved (a JSON 1 in some paths coerces toward truthiness differently).
  • The MatrixOne JSON comparison layer has its own open correctness issues ([Bug]: JSON boolean sort and comparison precedence is incorrect #28039 — JSON boolean sort/comparison precedence incorrect), which this SDK helper now depends on for its primary semantics: whatever MO decides for JSON-typed comparisons, the SDK assert becomes collateral.

Verified statically (source quoted); the behavior claim follows MySQL's documented JSON-vs-string comparison rules, and the intent mismatch is visible directly from the code comment itself ("Simply check if value equals 'true'") — the implementation treats a JSON scalar as if it were already unquoted text.

Sibling issues in the same class worth fixing together:

  • __getitem__ interpolates keys into the JSON path without escaping ($.{key} then .{key}) — a key containing ., [, ", or ' produces a wrong path or invalid SQL (JSON path escaping rules exist for a reason: $."weird.key" quoting).
  • cast()'s two-track type detection via type_.__class__.__name__ string matching ('Integer', 'VARCHAR'...) breaks for subclasses (e.g. sqlalchemy.BIGINT, custom user types, MOVectorJSON-style aliases) and silently slides them into the "regular cast (may fail in MatrixOne)" branch the docstring itself warns about.

Reproduction

# model: specs = Column(MOJSON) containing {"active": true}
p = JSONPathElement(Product.specs, 'active')
q = session.query(Product).filter(p.asbool == True)      # by-name API demo
# emitted: WHERE json_extract(specs, '$.active') = 'true'
# rows where specs.active == JSON true do NOT match (MySQL semantics);
# result depends on MO's own open JSON-comparison behaviors (#28039)

Path-escape sibling, no DB needed:

JSONPathElement(Product.specs, 'user.name')       # {key} with a dot → '$.user.name' means nested user.name
# → wrong path silently (should be '$."user.name"')

Impact

  • Any application filtering on JSON booleans through this documented convenience builder gets wrong results with no error — the worst failure class (silent data miss on filters). Given booleans are a top use of JSON columns (feature flags, active flags), this is a frequently-hit path.
  • The path-escaping gap corrupts lookups for keys that legitimately contain ., spaces, brackets — common in dynamic/user-specified schemas.
  • The cast() type-name string matching silently degrades on aliased/derived types the docstring claims to support.

Expected behavior

  1. asbool should emit a comparison that is well-defined per MySQL: e.g. json_extract_string(col, '$.path') = 'true' (string-extract then string compare) or JSON_EXTRACT(...) = CAST('true' AS JSON) — pick the one MatrixOne enforces consistently and add a regression asserting rows with JSON true match.
  2. Escape path keys per MySQL JSON-path rules (quote with " when the key contains non-identifier characters).
  3. cast() should decide via isinstance/TypeEngine checks (not class-name strings), raising on unsupported types instead of the "may fail" silent fallback.

Relations

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 28, 2026

    @Ariznawlll
    CollaboratorAuthor

    Engine-side datapoint: the SQL engine itself currently returns the opposite of the MySQL semantics this SDK report assumes

    While extending the JSON-function coverage on main nightly b14d67a (docker nightly-b14d67a2-arm64), I verified the raw SQL predicate json_extract(...) = <string literal> on the engine against MySQL 8.0 (official image, same statements):

    statement MySQL 8.0 (verified) MatrixOne nightly b14d67a (verified)
    SELECT JSON_EXTRACT('{"a":true}','$.a') = 'true' 0 1
    SELECT JSON_EXTRACT('{"a":7}','$.a') = '7' 0 1
    SELECT JSON_EXTRACT('{"a":null}','$.a') = 'null' 0 1
    SELECT JSON_EXTRACT('{"a":"s"}','$a') = 's' 1 1
    SELECT JSON_EXTRACT('{"a":null}','$.a') <> 'null' 1 0

    So on current main, JSON-vs-string equality is implemented as compare against the textual serialization of the JSON value (number → '7', boolean → 'true', JSON null → 'null'), while MySQL coerces through JSON value semantics where a JSON number/boolean/null is never equal to a SQL string.

    Two consequences for this report:

    1. The always-false behavior the SDK fix anticipates (= 'true' correctly yielding 0) does not exist yet in the engine — today the engine returns 1. Whichever way the engine lands (JSON-semantics comparison, per MySQL), the SDK and engine need to agree.
    2. If the engine is fixed to MySQL semantics, the pattern documented here (json_extract(...) == 'true') will correctly become always-false — but until then SDK users are silently getting always-true for booleans, which is arguably more dangerous for this specific predicate.

    Related engine-side siblings found in the same sweep: #31517 (json_extract_string returns NULL for non-string JSON values) and #31544 (IFNULL/IF error out on any json_extract argument).

  5. added a commit that references this issue on Oct 30, 2026
    bbfe556
  6. XuPeng-SH commented on Oct 30, 2026

    @XuPeng-SH
    Contributor

    QA handoff for merged #31774 (main bbfe55669a1440424914d45a283a1d0e36f722fa): please verify JSONPathElement.asbool for JSON boolean, JSON string, JSON null, SQL NULL and missing paths. Source inspection shows the SDK now classifies json_extract_string and compares a serialized value rather than directly comparing JSON to SQL string as in the older b14d67a report. The old raw SQL engine behavior has not been verified fixed. The new SDK path depends on the non-string behavior of json_extract_string; please reassess when the open engine contract #31517 changes. This QA run did not execute functional tests or live SQL at this SHA because the resource guard left insufficient headroom. PR author-reported validation is separate evidence, not a result of this QA run.

  7. Ariznawlll commented on Oct 30, 2026

    @Ariznawlll
    CollaboratorAuthor

    结论

    测试通过。SDK JSON 路径的 asbool 能区分 JSON 布尔值与字符串,特殊键名和类型转换回归也通过。

    关键证据

    • 官方 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。
    • 三个独立库中,JSON true 的过滤仅命中 id 1;false、字符串 "true"、数字 1 不误命中;JSON null、缺失路径和 SQL NULL 的投影为 NULL。含点号键 x.y 的 Integer、BigInteger 和 Numeric 提取分别为整数 7、整数 7、Decimal 7.00,值及 Python 类型正确。
    • 既有 [Bug]: Python SDK JSON paths containing quotes break SQL statement boundaries #30765 路径回归覆盖 12 类特殊键、嵌套路径和非法路径更新拒绝后源表不变,定向 3/3 通过。原断言将 Integer CAST 的结果要求为 float;本次按实际 Integer/Decimal 类型契约改为精确检查 int 和 Decimal,而非放宽类型。
    • 新增布尔回归及上述类型断言已加入 MOTR #295,定向各 3/3 通过、0 skipped,每轮测试库清理。

    待解决点

    • 本次不声称修复底层 JSON 与 SQL 字符串的所有比较语义,相关引擎问题仍需单独跟踪;未运行完整 MOTR suite。Add build constraint to assembly source files #295 尚未合入,SDK 场景需显式启用和匹配源码,默认 SKIP 不计通过。
  8. 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