Repository navigation
fix(session): strict memory_policy booleans and lossless unicode peer ids - #3422
ZaynJarvis wants to merge 1 commit into
Conversation
… ids Sweep findings: A-05, A-10. Reject ambiguous memory toggles and preserve full external peer identities.
ZaynJarvis
left a comment
There was a problem hiding this comment.
Independent maintainer review (group G03). Verified the diff against both stated findings:
- A-05 (strict booleans): Confirmed the old bug —
{"peer": {"enabled": "false"}}coerced toTrueviabool(), 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 ofmemory_policydicts:session.meta.memory_policyandSessionCommitMsg.memory_policyhave always been persisted viaMemoryPolicy.to_dict()(genuine booleans since #2236), and_resource_memory_policybuilds 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 withInvalidArgumentError). - A-10 (lossless unicode peer ids): Confirmed the collision —
_sanitize_component("张三 Alice")and"李四 Alice"both reduced toAlice(and could also collide with a genuine ASCII user namedAlice). Routing any non-ASCII input to the base64ext-path fixes it losslessly; the encoded output stays within the[a-zA-Z0-9_.@-]+peer-id charset sosafe_peer_idcannot 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).
| text = str(raw).strip() | ||
| if not text: | ||
| return None | ||
| if not text.isascii(): |
There was a problem hiding this comment.
[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.
| if not text: | ||
| return None | ||
| if not text.isascii(): | ||
| encoded = base64.urlsafe_b64encode(text.encode("utf-8")).decode("ascii").rstrip("=") |
There was a problem hiding this comment.
[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): |
There was a problem hiding this comment.
[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
left a comment
There was a problem hiding this comment.
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.pyuv run --extra test python -m pytest -q --no-cov tests/unit/session/test_memory_policy.py tests/ingest/test_peer.py— 15 passedgit 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.
* 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>
|
感谢这个 PR。这里不写一句「已由 #3553 解决」了事,分四段照实说 —— 两半的结局不一样,其中一半是方向相反的取舍。 合入 PR 是 #3553,commit 一、
二、 本 PR 要的是: main 上是 #3553 的正文写明了理由:不能破坏已经持久化的 policy 字典,所以保留宽松行为并用 三、所以本 PR 自带的这条测试,在当前 main 上会红 它断言非布尔 四、留门 第二段那处是行为取舍,不是漏掉的活 —— 是在「立刻严格」和「先兼容再迁移」之间选了后者。如果你认为该有个终止日期或者一个 strict 开关,欢迎重开,或者单独提一个只打 |
* 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>
概述
两个会把用户身份/隐私开关搞错的输入处理缺陷:memory_policy 的
enabled按 truthiness 判断,字符串"false"反而当成开启;含 Unicode 的用户名清洗有损,不同用户折叠成同一 peer_id。改为严格布尔校验 + 非 ASCII 用户名整体 base64 编码。为什么必要(可达性/严重性)
两处都是第一道防线,上游无任何拦截:
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。_sanitize_component把非 ASCII 字符全部剥掉,实测"张三 Alice"和"李四 Alice"都塌缩成Alice——不同人的消息与记忆归到同一 peer,跨用户错误串联。诚实定级 P1 而非 P0:A-05 需要调用方发非布尔值才触发(JSON 的 true/false 解析为 Python bool,不受影响);A-10 需要群聊日志里出现混合文字用户名。都真实可达,但有输入条件。
关键设计与取舍
"false"/"true"字符串。隐私开关宁可 fail-loud:静默猜语义会让"no"、"0"这类值继续歧义。缺省enabled键仍走默认值,行为不变。ext-前缀),而不是"清洗 + hash 后缀"。整体编码可逆、无碰撞,且与已有的 unsanitizable fallback 用同一编码公式——纯 CJK 用户名的 peer_id 完全不变(main 与本分支都是ext-5byg5LiJ)。base64 urlsafe 字母表落在 peer_id 允许字符集内,safe_peer_id恒通过。作用域与已知限制
"张三 Alice"→Alice,现在 →ext-…。这正是修复本身,但意味着这批用户历史数据在旧 peer_id 下,新数据在新 id 下,本 PR 不做存量迁移;此前已被污染的 peer(真 Alice + 被塌缩进来的他人数据)也无法回溯拆分。"enabled": "true"/1的调用方(若存在)现在会收到 400 而不是静默开启。这是有意的收紧。修复的问题
"false"也会开启记忆抽取(openviking/session/memory_policy.py:36)合入价值
P1 · 隐私开关行为可预测(fail-loud),不同用户的消息/记忆不再因用户名清洗合并到同一 peer。
验证
pytest -q --no-cov tests/unit/session/test_memory_policy.py tests/ingest/test_peer.py— 15 passedfrom_dict({'peer': {'enabled': 'false'}}).peer_enabled→ True;safe_external_peer('张三 Alice') == safe_external_peer('李四 Alice')→ 都是Alicememory_policy.peer.enabled must be a boolean;后者ext-5byg5LiJIEFsaWNl≠ext-5p2O5ZubIEFsaWNlalice@corp.com)、纯 CJK id 与 main 一致(ext-5byg5LiJ)、真布尔与缺省enabled行为不变自动化全仓清扫(2026-07)· draft 待 review