[Proposal] Avoid widening single-peer memory to user-global when extraction omits peer_id
Issue Origin
Observed or reproduced in a real environment.
Summary
This is a design proposal, not a bug report or regression. The current behavior is intentional and test-asserted; I am asking whether the narrow case below is worth tightening.
When a session's user messages all unambiguously belong to exactly one peer (every user-role message carries the same peer_id, and there are no self/personal turns), a memory-extraction operation that omits peer_id still resolves to user-global scope, silently widening project-bound memory into the shared user space. Whether project memory stays isolated then depends on whether the extraction LLM happens to emit the optional peer_id field on each operation — a prompt/model-level property the server does not guarantee.
Environment
- OpenViking v0.4.23 (Docker)
openviking/session/memory/memory_isolation_handler.pyis byte-identical between v0.4.23 and currentmainat the time of writing.
Current code path
openviking/session/memory/memory_isolation_handler.py, _resolve_operation_target():
def _resolve_operation_target(self, raw_peer_id: Any) -> _TargetResolution:
if raw_peer_id not in (None, ""):
... # explicit peer routing/validation
if self.allow_self:
return _TargetResolution([_SELF_PEER_ID]) # <- fires first on omission
peer_targets = ... # unique message-derived peer fallback (only when allow_self=False)
if len(peer_targets) == 1:
return _TargetResolution(peer_targets)
...
Trace for the affected case:
all user messages carry peer_id = P (single peer, no self turns)
-> session._resolve_memory_extraction_scope: allowed_peer_ids={P}, allow_self=True (default MemoryPolicy)
-> extractor emits operation WITHOUT peer_id
-> _resolve_operation_target(None)
-> allow_self branch returns [__self] (provenance never consulted)
-> final URI: viking://user/<user>/memories/... (user-global)
Note the provenance-inheritance fallback already exists one branch later — it is only reachable when allow_self=False (the multi-tenant bot configuration).
Reproduction
Deterministic resolver-level A/B against the deployed v0.4.23 code, with message provenance = exactly one peer on all user messages:
| allow_self | operation peer_id |
resolved target |
|---|---|---|
| True (session default) | present | peer scope ✅ |
| True (session default) | absent | user-global (__self) ❌ |
| False | absent | peer scope (provenance inherited) ✅ |
| False | present | peer scope ✅ |
The model-dependent part: the extraction model can omit peer_id (observed in real extraction history with default prompt templates; e.g. identical single-peer sessions producing both viking://user/<user>/peers/<peer>/memories/... and viking://user/<user>/memories/... for the same repository-rule content). Once the field is omitted, the user-global outcome is deterministic server behavior.
Mitigation today is prompt-level only: tightening the custom memory-type templates (field descriptions instructing the model to set peer_id for repo-bound facts) reduced observed leakage to 0/5 in my controlled runs — but that is model compliance, not a guarantee, and it regresses silently whenever a different extraction model or looser template is in play.
Why current behavior is intentional (acknowledged)
tests/session/memory/test_memory_isolation_handler.py::test_calculate_memory_uris_missing_peer_id_prefers_self_when_allowedasserts SELF wins when the operation omitspeer_id.test_calculate_memory_uris_missing_peer_id_uses_unique_user_peer_when_self_absentasserts the provenance fallback withallow_self=False.- Self-first ordering is correct for mixed sessions (personal turns + peer turns): defaulting such an operation to the peer would mis-scope genuinely personal memories. This proposal does not ask to change that case.
The gap: there is currently no test where all user messages carry one identical peer_id, there are no self turns, allow_self=True, and the operation omits peer_id — and in that unambiguous case the memory still lands user-global.
Proposed behavior
When an operation omits peer_id, the memory type is peer-enabled, and every peer-owner (user-role) message in the extraction context resolves to exactly one peer (zero self turns, zero additional peers), resolve the operation to that peer instead of __self — or, if that is too aggressive, skip with AMBIGUOUS_TARGET/a new skip code rather than silently widening scope. Mixed sessions keep today's SELF-first behavior unchanged.
Suggested implementation shape (one guarded branch in _resolve_operation_target, before the allow_self return):
if self.allow_self:
owner_targets = self._target_ids_in_messages() # user-role messages only
self_turns_present = any(
self._is_peer_owner_message(m) and getattr(m, "peer_id", None) in (None, "")
for m in self._messages()
)
if (
not self_turns_present
and len(owner_targets) == 1
and owner_targets[0] != _SELF_PEER_ID
):
return _TargetResolution(owner_targets)
return _TargetResolution([_SELF_PEER_ID])
Regression test ideas (minimal, deterministic, no LLM):
- all user messages carry one peer, op
peer_idabsent,allow_self=True→ expect peer-scoped URI. - same, but one additional self turn (no
peer_id) → expect user-global (current behavior preserved). - same, but two distinct peers across user messages → expect
AMBIGUOUS_TARGETskip, not a silent choice.
Related work (adjacent, not duplicates)
- #4487 / #4632 — client plugin dropped
peerIdbefore it reached the server (no messagepeer_idat all). Different layer. - #3326 — explicit
remember/add-memorytool routing andactor_peer_idsemantics discussion; maintainer comments confirm write scope is deliberately "MemoryPolicy + per-message peer_id". Different mechanism. - #5433 / PR #5480 — read-side
peer_scope="actor"recall isolation. Different direction. - #5241 — profile-injection read/write scope asymmetry.
Why this matters
For multi-project coding agents (per-repository peers), a silently user-global project convention is exactly the cross-project contamination the peer model exists to prevent, and the failure is nondeterministic from the user's perspective: the same repository rule sometimes lands in the peer scope and sometimes in the shared user space, depending on model output. A deterministic server-side default for the unambiguous case would make isolation a guarantee rather than a prompt-engineering outcome.
Happy to contribute a focused PR with the tests above if the direction sounds right.
A bounded candidate for the single-peer case uses each user message's existing target resolution. It inherits a peer only when every user message resolves to the same writable peer; assistant messages cannot establish that ownership. Explicit operation targets and self-only schemas keep their current behavior. Mixed, empty, invalid-owner and denied-owner contexts keep the existing fallback.
The candidate exercises calculate_memory_uris with actual URI rendering: three proposed-contract cases fail on main 6c11075, and the full handler test file passes 56 cases with the change. This is resolver coverage, without a live extraction model. The candidate also leaves two-peer sessions on today's self fallback, rather than adding the separate ambiguous-target change suggested above.
Should uniform single-peer inheritance become the default, or require an opt-in MemoryPolicy setting? Could you confirm that boundary before a PR? If the reporter is already implementing this proposal, the candidate can serve as complementary test coverage instead of a parallel implementation.
Extending the candidate through fill_identity_fields exposed another boundary: normalization drops an explicit __self before URI resolution, so the new inheritance rule would then treat it as an omitted target. The candidate now retains that sentinel internally until target resolution; it is still removed from the resulting memory fields.
The handler matrix now covers each of the 11 routing cases both directly and after normalization, and all 67 tests pass. The related timestamp and extraction-protocol files bring the result to 198 passes and one timestamp failure, also reproduced with unchanged production source. The default-versus-opt-in decision remains open; no PR has been submitted.