Skip to content

[Bug]: Python fetchmany with negative size rewinds result cursors #31314

Closed

Description

@MatrixAdventurer

Is there an existing issue for the same bug?

  • I have checked the existing issues.
    Search for fetchmany returned no matching issue.

Branch Name

main

Commit ID

24c1ac8

Other Environment Information

Python 3.12, SQLAlchemy 2.0.55, SDK offline tests.

Actual Behavior

Both ResultSet and AsyncResultSet accept negative fetchmany sizes and set their cursor to a negative or earlier index. For rows [(10,), (20,), (30,)], fetchone(); fetchmany(-1); fetchone() returns (10,) again. With fetchmany(-100), the next fetchone() can raise IndexError: list index out of range. Empty and exhausted results can likewise be rewound.

Expected Behavior

Reject negative sizes with ValueError before mutating the cursor. Keep zero, omitted size, positive and oversized reads unchanged.

Steps to Reproduce

Instantiate either SDK result class with the three rows above and run the sequence. The attached tests cover empty, initial, partially consumed and exhausted results, sizes -1 and -100, and normal controls.
Before fix: 16 failed, 2 passed. Fixed focused suite: 18 passed.

Additional information

由 LW 授权的 ChatGPT Agent 操作。
@XuPeng-SH complete candidate patch below. Scope: 3 files, +48/-2 lines.
Validation from clients/python:

  • PYTHONPATH=. python -m pytest tests/offline/test_resultset_fetchmany_bounds.py -o addopts='' -q: 18 passed.
  • PYTHONPATH=. python -m pytest tests/offline/ -o addopts='' -q: 1972 passed, 95 subtests passed, 6 warnings.
  • git diff --cached --check: passed.

The owner is the buffered SDK result cursor, shared in behavior by sync and async wrappers. This changes local invalid-argument handling only; no SQL generation, network, engine, or persisted state changes. Existing tests did not exercise negative sizes. Tests assert observable remaining rows after rejection, not cursor implementation details. Live MatrixOne and hosted CI were not run. No PR opened in this handoff.

Save the full diff below and run git apply --check followed by git apply against the pinned base.

diff --git a/clients/python/matrixone/async_client.py b/clients/python/matrixone/async_client.py
index cfcdefc..f0679d5 100644
--- a/clients/python/matrixone/async_client.py
+++ b/clients/python/matrixone/async_client.py
@@ -86,7 +86,9 @@ class AsyncResultSet:
         return None
 
     def fetchmany(self, size: int = 1) -> List[Tuple]:
-        """Fetch many rows"""
+        """Fetch up to size rows; reject negative sizes without moving the cursor."""
+        if size < 0:
+            raise ValueError("size must be non-negative")
         start = self._cursor
         end = min(start + size, len(self.rows))
         rows = self.rows[start:end]
diff --git a/clients/python/matrixone/client.py b/clients/python/matrixone/client.py
index 5c8532b..1ca5ec1 100644
--- a/clients/python/matrixone/client.py
+++ b/clients/python/matrixone/client.py
@@ -3060,7 +3060,9 @@ class ResultSet:
         return None
 
     def fetchmany(self, size: int = 1) -> List[Tuple[Any, ...]]:
-        """Fetch many rows"""
+        """Fetch up to size rows; reject negative sizes without moving the cursor."""
+        if size < 0:
+            raise ValueError("size must be non-negative")
         start = self._cursor
         end = min(start + size, len(self.rows))
         rows = self.rows[start:end]
diff --git a/clients/python/tests/offline/test_resultset_fetchmany_bounds.py b/clients/python/tests/offline/test_resultset_fetchmany_bounds.py
new file mode 100644
index 0000000..936dec6
--- /dev/null
+++ b/clients/python/tests/offline/test_resultset_fetchmany_bounds.py
@@ -0,0 +1,42 @@
+# Copyright 2021 - 2022 Matrix Origin
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Rejected batch sizes must leave result consumption unchanged."""
+import pytest
+from matrixone.client import ResultSet
+from matrixone.async_client import AsyncResultSet
+
+
+@pytest.mark.parametrize('result_type', [ResultSet, AsyncResultSet])
+@pytest.mark.parametrize(
+    'rows,consumed',
+    [([], 0), ([(10,), (20,), (30,)], 0), ([(10,), (20,), (30,)], 1), ([(10,), (20,), (30,)], 3)],
+)
+@pytest.mark.parametrize('size', [-1, -100])
+def test_negative_fetchmany_preserves_cursor(result_type, rows, consumed, size):
+    result = result_type(['id'], rows)
+    assert result.fetchmany(consumed) == rows[:consumed]
+    with pytest.raises(ValueError, match='non-negative'):
+        result.fetchmany(size)
+    assert result.fetchall() == rows[consumed:]
+    assert result.fetchone() is None
+
+
+@pytest.mark.parametrize('result_type', [ResultSet, AsyncResultSet])
+def test_fetchmany_zero_default_and_oversized(result_type):
+    result = result_type(['id'], [(10,), (20,), (30,)])
+    assert result.fetchmany(0) == []
+    assert result.fetchmany() == [(10,)]
+    assert result.fetchmany(100) == [(20,), (30,)]
+    assert result.fetchmany() == []

Activity

  1. added a commit that references this issue on Oct 27, 2026
    baa83f4
  2. XuPeng-SH commented on Oct 27, 2026

    @XuPeng-SH
    Contributor

    QA on merged SDK source baa83f4b96e56ec214f92c68f7b56539b9e0fa45: the complete offline suite passed (2,279 tests plus 95 subtests) on Python 3.12.14 / SQLAlchemy 2.0.55. The result-boundary tests cover sync and async buffered results, negative sizes at empty, initial, partially consumed and exhausted positions, preservation of remaining rows after rejection, and zero/default/oversized controls. These checks cover the reported local cursor contract; no live database is needed to exercise it. Hosted CI was not verified by this run. Assignment remains unchanged pending handoff.

  3. Ariznawlll commented on Oct 27, 2026

    @Ariznawlll
    Collaborator

    测试版本

    • main:d4ffbae43d55da21526eab01722cbef14bb01ed5;修复 PR #31322 的 merge commit baa83f4b96e56ec214f92c68f7b56539b9e0fa45 在祖先链中。
    • 2026-10-27,macOS/arm64,Python 3.14.3、SQLAlchemy 2.1.6;缓冲结果游标是本地 SDK 行为,不依赖 SQL 网络。MOTR 同时使用对应版本隔离服务。

    原问题验证

    同步 ResultSet 与异步 AsyncResultSet 使用 (10,20,30) 的三行结果;空、未读取、部分读取和耗尽等位置分别调用 fetchmany(-1)、fetchmany(-100),均抛出 ValueError,之后剩余行不变、没有倒退或 IndexError。定向 SDK 测试和 MOTR 场景各重复 3 轮通过。

    Happy Path 覆盖

    两种结果类型的 fetchmany(0) 返回空列表且不移动游标;默认、正数、超大值与耗尽后读取均返回预期行。整数索引协议、列信息和 affected rows 保持预期。

    Unhappy Path 覆盖

    负值在空/初始/部分/耗尽位置拒绝,拒绝后检查完整剩余行;非整数、Decimal、字符串和 None 保留 TypeError 且不改变剩余结果。

    白盒验证

    这是 Python 本地游标契约,不涉及 Go race。独立运行 tests/offline/contracts/test_config_result_boundaries.py 和全文分页参数化测试,总计 58 项,3 轮均通过。

    回归测试

    MOTR #284 新增 SDK 场景,验证同步/异步游标、负值与正常控制;场景及相邻 #30824 用例各 3/3。未运行完整 MOTR 套件。

    测试证据

    修复 PR 的 Python SDK 离线 CI 矩阵通过,online job skipped;MOTR 新 head 的四项托管离线检查通过,不等同完整在线 CI。

    测试结论

    测试通过。

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