Skip to content

fix(session): strict memory_policy booleans and lossless unicode peer ids - #3422

Closed
ZaynJarvis wants to merge 1 commit into
mainfrom
sweep/memory-policy-peer-strictness
Closed

ZaynJarvis wants to merge 1 commit into
mainfrom
sweep/memory-policy-peer-strictness

Conversation

@ZaynJarvis

@ZaynJarvis ZaynJarvis commented Jul 21, 2026 •

Copy link
Copy Markdown
Collaborator

概述

两个会把用户身份/隐私开关搞错的输入处理缺陷:memory_policy 的 enabled 按 truthiness 判断,字符串 "false" 反而当成开启;含 Unicode 的用户名清洗有损,不同用户折叠成同一 peer_id。改为严格布尔校验 + 非 ASCII 用户名整体 base64 编码。

为什么必要(可达性/严重性)

两处都是第一道防线,上游无任何拦截:

  • A-05:HTTP API CreateSessionRequest.memory_policy 的类型是 Optional[Dict[str, Any]](openviking/server/routers/sessions.py:125),pydantic 不校验内层值,SDK/CLI 也原样透传 dict。{"peer": {"enabled": "false"}} 一路到 MemoryPolicy.from_dict(session_service.py:157 创建路径、session.py:1367 commit 路径),bool("false") 为 True——调用方明确要求关闭 peer 记忆抽取,系统却继续抽取。在 main 上实测复现:peer_enabled == True。
  • A-10:群聊 harness(hermes/openclaw)的 ingest 用日志里的原始用户名生成 peer_id(openviking/ingest/sources/base.py:86 → safe_external_peer)。_sanitize_component 把非 ASCII 字符全部剥掉,实测 "张三 Alice" 和 "李四 Alice" 都塌缩成 Alice——不同人的消息与记忆归到同一 peer,跨用户错误串联。

诚实定级 P1 而非 P0:A-05 需要调用方发非布尔值才触发(JSON 的 true/false 解析为 Python bool,不受影响);A-10 需要群聊日志里出现混合文字用户名。都真实可达,但有输入条件。

关键设计与取舍

  • enabled 非布尔直接报 InvalidArgumentError,而不是解析 "false"/"true" 字符串。隐私开关宁可 fail-loud:静默猜语义会让 "no"、"0" 这类值继续歧义。缺省 enabled 键仍走默认值,行为不变。
  • 非 ASCII 用户名整体 base64(ext- 前缀),而不是"清洗 + hash 后缀"。整体编码可逆、无碰撞,且与已有的 unsanitizable fallback 用同一编码公式——纯 CJK 用户名的 peer_id 完全不变(main 与本分支都是 ext-5byg5LiJ)。base64 urlsafe 字母表落在 peer_id 允许字符集内,safe_peer_id 恒通过。
  • 纯 ASCII 用户名路径零改动,保持人类可读。

作用域与已知限制

  • 行为变化仅限混合 Unicode 用户名:此前 "张三 Alice" → Alice,现在 → ext-…。这正是修复本身,但意味着这批用户历史数据在旧 peer_id 下,新数据在新 id 下,本 PR 不做存量迁移;此前已被污染的 peer(真 Alice + 被塌缩进来的他人数据)也无法回溯拆分。
  • 兼容性:此前发 "enabled": "true" / 1 的调用方(若存在)现在会收到 400 而不是静默开启。这是有意的收紧。
  • 与存储后端无关(S3/本地均同),纯输入解析层。

修复的问题

  • A-05 memory_policy.enabled 用 truthiness 而非严格布尔,字符串 "false" 也会开启记忆抽取(openviking/session/memory_policy.py:36)
  • A-10 混合 Unicode 用户名有损清洗后塌缩成相同 peer_id,跨用户错误归因(openviking/ingest/peer.py:39)

合入价值

P1 · 隐私开关行为可预测(fail-loud),不同用户的消息/记忆不再因用户名清洗合并到同一 peer。

验证

  • pytest -q --no-cov tests/unit/session/test_memory_policy.py tests/ingest/test_peer.py — 15 passed
  • main 复现:from_dict({'peer': {'enabled': 'false'}}).peer_enabled → True;safe_external_peer('张三 Alice') == safe_external_peer('李四 Alice') → 都是 Alice
  • 本分支:前者抛 memory_policy.peer.enabled must be a boolean;后者 ext-5byg5LiJIEFsaWNl ≠ ext-5p2O5ZubIEFsaWNl
  • 回归确认:纯 ASCII id 不变(alice@corp.com)、纯 CJK id 与 main 一致(ext-5byg5LiJ)、真布尔与缺省 enabled 行为不变

自动化全仓清扫(2026-07)· draft 待 review

… ids

Sweep findings: A-05, A-10. Reject ambiguous memory toggles and preserve full external peer identities.

@ZaynJarvis ZaynJarvis left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Independent maintainer review (group G03). Verified the diff against both stated findings:

  • A-05 (strict booleans): Confirmed the old bug — {"peer": {"enabled": "false"}} coerced to True via bool(), silently enabling extraction the caller asked to disable. The new strict check fixes this at the single choke point (_target_enabled) used by all three targets. I checked every internal producer of memory_policy dicts: session.meta.memory_policy and SessionCommitMsg.memory_policy have always been persisted via MemoryPolicy.to_dict() (genuine booleans since #2236), and _resource_memory_policy builds real booleans — so no stored session meta or in-flight queue message can fail the new validation. Only external clients sending non-boolean JSON are affected, which matches the documented contract (docs/en/api/05-sessions.md: invalid shapes rejected with InvalidArgumentError).
  • A-10 (lossless unicode peer ids): Confirmed the collision — _sanitize_component("张三 Alice") and "李四 Alice" both reduced to Alice (and could also collide with a genuine ASCII user named Alice). Routing any non-ASCII input to the base64 ext- path fixes it losslessly; the encoded output stays within the [a-zA-Z0-9_.@-]+ peer-id charset so safe_peer_id cannot reject it. Pure non-ASCII names already took this path, so only mixed-script names change ids.

Ran the PR's tests plus the full tests/ingest/ and tests/unit/session/ suites on a snapshot of the branch: 192 passed. The failures in tests/session/test_session_commit.py reproduce identically at the merge base (pre-existing environment setup errors, not introduced here).

No blocking issues. Three non-blocking notes inline (peer-id migration visibility, a duplicated encode block, and the breaking-change surface of the strict validation).

Comment thread openviking/ingest/peer.py
text = str(raw).strip()
if not text:
return None
if not text.isascii():

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] (non-blocking) Upgrade note on peer-id stability: before this change a mixed-script identity sanitized to a lossy ASCII remnant ("张三 Alice" -> Alice, "José" -> Jos); after it, the same person resolves to ext-<base64>. Memories and messages stored before the upgrade remain attributed to the old id, so one person's history splits across two peer ids after deploy. The remap is inherent to fixing the collision (and the old remnant could also collide with a genuine ASCII Alice, which is worse), so this looks like the right trade-off — but it is user-visible for existing data. If leaving old data under the old ids without a migration/changelog note is the intended plan, please confirm.

Comment thread openviking/ingest/peer.py
if not text:
return None
if not text.isascii():
encoded = base64.urlsafe_b64encode(text.encode("utf-8")).decode("ascii").rstrip("=")

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] (non-blocking) This two-line encode-and-return block is byte-identical to the existing "unsanitizable ASCII" fallback at the bottom of the function (lines 54-56). Both branches produce safe_peer_id(f"ext-{encoded}") from the same expression, so the function now has two copies of the encoding logic that must stay in sync if the ext- convention ever changes.

if "enabled" not in data:
return default_enabled
enabled = data["enabled"]
if not isinstance(enabled, bool):

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] (non-blocking) The strict isinstance(enabled, bool) check also rejects values that previously behaved correctly, not just the ambiguous ones: {"enabled": 1} / {"enabled": 0} used to coerce to the intended True/False, and JSON null used to coerce to False; all three now raise InvalidArgumentError at session create/commit time. This is consistent with the documented contract (invalid shapes rejected with InvalidArgumentError) and no internal producer or persisted data is affected (all go through to_dict() booleans), but it is a client-visible breaking change beyond the "false" case named in the PR description. If shipping this without a changelog/release note is intended, please confirm.

@huangruiteng huangruiteng left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved on exact head 0dfd5a9ed9bdd09700d78e881908bed0b6398ee2.

Validated locally in an isolated detached worktree:

  • uv run python -m py_compile openviking/session/memory_policy.py openviking/ingest/peer.py tests/unit/session/test_memory_policy.py tests/ingest/test_peer.py
  • uv run --extra test python -m pytest -q --no-cov tests/unit/session/test_memory_policy.py tests/ingest/test_peer.py — 15 passed
  • git diff --check origin/main...HEAD

I also traced both changed paths: non-boolean enabled values now fail before policy activation, while any identifier containing non-ASCII characters encodes the complete normalized input instead of retaining a lossy ASCII fragment. The URL-safe encoding remains compatible with safe_peer_id. A bounded open-PR search found no competing implementation; #2772 mentions memory policy but does not touch either changed module.

The migration/backward-compatibility considerations are already captured in the author's non-blocking inline notes. I found no merge-blocking issue.

t0saki pushed a commit that referenced this pull request Jul 31, 2026
* fix(ragfs): preserve cache visibility on partial S3 deletes

Surface exact and per-object S3 deletion failures, while always invalidating the affected directory and stat cache scope after a recursive delete attempt.

Source-PR: #3407
Original-Commit: 8d6addf

* fix(session): preserve legacy policy and peer identity compatibility

Parse string false and other legacy boolean-like memory policy values without silently enabling extraction or breaking persisted configs. Encode mixed-script peers losslessly, while retaining their former lossy IDs as read-only retrieval and extraction aliases.

Source-PR: #3422
Original-Commit: 0dfd5a9

* fix(memory): drain timer flush tasks during shutdown

Retain the shielded timer flush task and await it when close cancels the timer loop, so batch failures are observed and submitters are resolved without unhandled task exceptions.

Source-PR: #3438
Original-Commit: ca1d74e

* fix(storage): preserve peer isolation and cache correctness

* fix(ingest): reserve encoded peer namespace

* ci: skip embedding-dependent resource test without secrets

* fix(ragfs): invalidate caches after partial remove

---------

Co-authored-by: zhiheng.liu <zhiheng.liu@bytedance.com>
@t0saki

t0saki commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator

感谢这个 PR。这里不写一句「已由 #3553 解决」了事,分四段照实说 —— 两半的结局不一样,其中一半是方向相反的取舍。

合入 PR 是 #3553,commit de9c3cec15e82dfe12fd98e67c62e091b49475d0。

一、peer.py 那半进了 main,而且被加强了

  • 非 ASCII 身份走 base64 ext- 无损编码,在(main safe_external_peer)。
  • 本 PR 自带的 test_external_peer_mixed_unicode_encodes_full_value_without_collisions 也在(tests/ingest/test_peer.py:33)。
  • 多做的一步:ext- 被确立为编码身份的保留命名空间 —— ASCII 名字若 sanitize 之后会落进 ext-,同样强制编码,防止它冒充某个非 ASCII 身份的 base64 结果。对应新增测试 test_external_peer_encoded_namespace_cannot_be_impersonated_by_ascii_name。

二、memory_policy.py 那半没有按本 PR 的方向走,方向是相反的

本 PR 要的是:enabled 不是布尔就 raise InvalidArgumentError。

main 上是 _parse_enabled():非布尔时发一条 FutureWarning,然后继续按 legacy 语义强转 —— "false" / "true" 这类字符串会被正确解析(这一点解决了本 PR 指出的「"false" 被 truthiness 判成 True」),其余值走 bool(value)。

#3553 的正文写明了理由:不能破坏已经持久化的 policy 字典,所以保留宽松行为并用 FutureWarning 标记为待废弃。你要的严格拒绝没有被采纳,被换成了「先警告、后迁移」。

三、所以本 PR 自带的这条测试,在当前 main 上会红

test_memory_policy_rejects_non_boolean_enabled

它断言非布尔 enabled 会抛 InvalidArgumentError,而 main 上只会发 FutureWarning 并返回强转结果。main 换成了断言那条 warning 的版本。这一条最不能省:本 PR 的核心主张(严格布尔)在 main 上不成立,只有「"false" 不再被误判为 True」这个后果成立。

四、留门

第二段那处是行为取舍,不是漏掉的活 —— 是在「立刻严格」和「先兼容再迁移」之间选了后者。如果你认为该有个终止日期或者一个 strict 开关,欢迎重开,或者单独提一个只打 memory_policy 这一点的 PR 对着当前 main。

@t0saki t0saki closed this Aug 3, 2026
@github-project-automation github-project-automation Bot moved this from Backlog to Done in OpenViking project Aug 3, 2026
@ZaynJarvis
ZaynJarvis deleted the sweep/memory-policy-peer-strictness branch September 11, 2026 15:16
frankyang2008-eng pushed a commit to frankyang2008-eng/OpenViking that referenced this pull request Oct 9, 2026
* fix(ragfs): preserve cache visibility on partial S3 deletes

Surface exact and per-object S3 deletion failures, while always invalidating the affected directory and stat cache scope after a recursive delete attempt.

Source-PR: volcengine#3407
Original-Commit: 8d6addf

* fix(session): preserve legacy policy and peer identity compatibility

Parse string false and other legacy boolean-like memory policy values without silently enabling extraction or breaking persisted configs. Encode mixed-script peers losslessly, while retaining their former lossy IDs as read-only retrieval and extraction aliases.

Source-PR: volcengine#3422
Original-Commit: 0dfd5a9

* fix(memory): drain timer flush tasks during shutdown

Retain the shielded timer flush task and await it when close cancels the timer loop, so batch failures are observed and submitters are resolved without unhandled task exceptions.

Source-PR: volcengine#3438
Original-Commit: ca1d74e

* fix(storage): preserve peer isolation and cache correctness

* fix(ingest): reserve encoded peer namespace

* ci: skip embedding-dependent resource test without secrets

* fix(ragfs): invalidate caches after partial remove

---------

Co-authored-by: zhiheng.liu <zhiheng.liu@bytedance.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants