Skip to content

Dev v2.0.23 sdk - #2105

Merged
bittergreen merged 5 commits into
MemTensor:dev-v2.0.24from
Zyntrael:dev-v2.0.23-sdk
Jul 14, 2026
Merged

bittergreen merged 5 commits into
MemTensor:dev-v2.0.24from
Zyntrael:dev-v2.0.23-sdk

Conversation

@Zyntrael

Copy link
Copy Markdown
Contributor

Description

Please include a summary of the change, the problem it solves, the implementation approach, and relevant context. List any dependencies required for this change.

Related Issue (Required): Fixes #issue_number

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Refactor (does not change functionality, e.g. code style improvements, linting)
  • Documentation update

How Has This Been Tested?

Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration

  • Unit Test
  • Test Script Or Test Steps (please provide)
  • Pipeline Automated API Test (please provide)

Checklist

  • I have performed a self-review of my own code | 我已自行检查了自己的代码
  • I have commented my code in hard-to-understand areas | 我已在难以理解的地方对代码进行了注释
  • I have added tests that prove my fix is effective or that my feature works | 我已添加测试以证明我的修复有效或功能正常
  • I have created related documentation issue/PR in MemOS-Docs (if applicable) | 我已在 MemOS-Docs 中创建了相关的文档 issue/PR(如果适用)
  • I have linked the issue to this PR (if applicable) | 我已将 issue 链接到此 PR(如果适用)
  • I have mentioned the person who will review this PR | 我已提及将审查此 PR 的人

Reviewer Checklist

  • closes #xxxx (Replace xxxx with the GitHub issue number)
  • Made sure Checks passed
  • Tests have been provided

@Memtensor-AI Memtensor-AI added area:api 云服务 / FastAPI / OpenAPI / MCP status:in-progress Someone or AI is working on it | 人工或 AI 正在处理 labels Jul 14, 2026
@Memtensor-AI
Memtensor-AI requested a review from bittergreen July 14, 2026 09:34
@Memtensor-AI

Copy link
Copy Markdown
Collaborator

🤖 Open Code Review

Target: PR #2105
Task: 4156f74632c182ef
Base: dev-v2.0.24
Head: dev-v2.0.23-sdk

🔍 OpenCodeReview found 9 issue(s) in this PR.

⚠️ 1 warning(s) occurred during review.


1. src/memos/api/product_models.py (L1231-L1234)

The messages property wraps a single GetTaskStatusData object in a list to preserve backward compatibility, but the return type annotation list[GetTaskStatusData] is misleading — the original property returned list[GetTaskStatusMessageData] (a list from self.data), whereas now it always returns a one-element list wrapping the single data object. Any caller that previously iterated .messages and accessed .status will still work, but callers that depended on the list having multiple items will silently get only one. Consider documenting this clearly, or exposing a dedicated singular accessor (e.g., a task_status property returning GetTaskStatusData directly) and deprecating messages.


2. src/memos/api/product_models.py (L1232-L1234)

The messages property now always returns a one-element list wrapping the single GetTaskStatusData object, purely for backward compatibility. Both the property name messages and the return type list[GetTaskStatusData] are misleading now that data is a scalar. Callers that previously expected to iterate over multiple task-status items will silently get exactly one element with no warning. Consider exposing a direct singular accessor (e.g., task_status -> GetTaskStatusData) and deprecating messages, or at minimum documenting that this list is always length-1.

💡 Suggested Change

Before:

    def messages(self) -> list[GetTaskStatusData]:
        """Backward-compatible list access to task status data."""
        return [self.data]

After:

    def messages(self) -> list[GetTaskStatusData]:
        """Backward-compatible list access to task status data.

        .. deprecated::
            This property always returns a one-element list. Prefer the
            ``task_status`` property for direct access to the status object.
        """
        return [self.data]

    @property
    def task_status(self) -> GetTaskStatusData:
        """Direct access to the task status data."""
        return self.data

3. src/memos/api/client.py (L425-L430)

File handles opened inside build_file_form_param (via open(file_path, "rb")) are collected in a list comprehension. If open() succeeds for the first N files but then raises an OSError for file N+1, the already-opened handles for files 0..N-1 are embedded in the partially-built list that is never assigned to file_params, so they are never closed by the finally block.

Suggestion: open each file within build_file_form_param using a try/except that closes already-collected handles on failure, or accumulate handles separately so they can be tracked and closed regardless of where the comprehension stops.


4. src/memos/api/client.py (L444-L465)

The error log message uses an f-string (defeating lazy formatting) and hard-codes the retry count as /3 rather than /MAX_RETRY_COUNT. If MAX_RETRY_COUNT is changed, this message will silently report the wrong total.

Suggestion:

logger.error(
    "Failed to add knowledgebase-file form (retry %s/%s): %s",
    retry + 1,
    MAX_RETRY_COUNT,
    e,
)

5. src/memos/api/client.py (L828-L839)

When stream=True and requests.post raises an exception (e.g., a connection error), the retry loop attempts a new request. However, if requests.post succeeds but response.raise_for_status() raises on a non-2xx status, _iter_sse_data has not been called yet so response.close() is never invoked — the streaming connection is leaked before the retry fires.

Suggestion: Close the response explicitly in the except branch when stream=True:

except Exception as e:
    if stream:
        try:
            response.close()
        except Exception:
            pass
    logger.error(...)
    if retry == MAX_RETRY_COUNT - 1:
        raise

6. src/memos/api/client.py (L610-L614)

The backward-compatibility shim has a silent-ignore bug. When user_ids=["u1"] and memory_ids=["m1"] are both supplied, the first inner if does not raise (because memory_ids is truthy), and the second inner if also does not set user_id (because memory_ids is truthy). Control falls through with user_id still None. Then delete_modes evaluates to [True, False, False, False] — memory_ids becomes the sole condition, and user_ids is silently discarded. The caller may have intended to scope the delete to a specific user, but the filter is lost.

Suggestion: Either raise an error when both user_ids and memory_ids are supplied (forcing callers to use the new memory_ids-only path), or explicitly document that user_ids is ignored when memory_ids is present.


7. src/memos/api/client.py (L661-L662)

The check uses truthiness rather than an is None test, so an empty string "" passed as content, title, or status is treated as absent and raises ValueError, even though an empty string could be a valid value for clearing a field.

Suggestion:

if content is None and title is None and status is None:
    raise ValueError("content, title or status is required")

8. tests/api/test_client.py (L14-L24)

sys.modules is mutated permanently — the stub entries for memos and memos.api are never removed. Because the stubs skip executing src/memos/__init__.py (which wires up MOS, GeneralMemCube, etc.), any test file that runs after test_client.py and does a normal from memos... import will receive this incomplete stub instead of the real package. tests/api/test_server_router.py line 14 does exactly this (from memos.api.product_models import ...), and since test_client.py sorts earlier alphabetically, it will run first and leave the stub in place.

Recommendation: isolate the stub inside a pytest fixture with autouse teardown (using monkeypatch or an explicit try/finally) so sys.modules is restored after the test session:

@pytest.fixture(scope="session", autouse=True)
def _memos_stub(request):
    installed = set()
    if "memos" not in sys.modules:
        memos_pkg = types.ModuleType("memos")
        memos_pkg.__path__ = [str(SRC_DIR)]
        sys.modules["memos"] = memos_pkg
        installed.add("memos")
    if "memos.api" not in sys.modules:
        api_pkg = types.ModuleType("memos.api")
        api_pkg.__path__ = [str(SRC_DIR / "api")]
        sys.modules["memos.api"] = api_pkg
        sys.modules["memos"].api = api_pkg
        installed.add("memos.api")
    yield
    for key in installed:
        sys.modules.pop(key, None)

9. tests/api/test_client.py (L59-L61)

assert decode_unicode is True uses assert for runtime guard logic inside a generator. Two problems:

  1. assert statements are stripped when Python runs under python -O (optimised mode), so the check silently disappears.
  2. is True is an identity check — if the caller passes decode_unicode=1 (truthy but not the True singleton) the assertion fires even though the intent is satisfied.

A clearer, always-evaluated alternative:

def iter_lines(self, decode_unicode: bool = False):
    if not decode_unicode:
        pytest.fail("iter_lines must be called with decode_unicode=True")
    yield from self.lines

🧹 Filtered 9 low-confidence OCR finding(s) before posting/fix-loop (duplicate: 9).

Generated by cloud-assistant via Open Code Review.

@bittergreen
bittergreen merged commit c9745f6 into MemTensor:dev-v2.0.24 Jul 14, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:api 云服务 / FastAPI / OpenAPI / MCP status:in-progress Someone or AI is working on it | 人工或 AI 正在处理

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants