mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
fix(memory): fail closed for unresolved tools (#3655)
## Description Explicit memory tools did not honor the existing fail-closed behavior for unresolved PROJECT scope. They resolved the sentinel scope but still used its backend, allowing save/search/update/delete/list to proceed without a resolved workspace. Closes #3651 ## Type of Change - [x] Bug fix (non-breaking change that fixes an issue) - [ ] New feature (non-breaking change that adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) - [ ] Documentation update - [ ] Performance improvement - [ ] Code refactoring (no functional changes) ## Changes Made - Reject explicit memory operations when PROJECT routing resolves to the fail-closed unresolved sentinel. - Keep GLOBAL fallback behavior unchanged when explicitly configured. - Add regression coverage for save, search, update, delete, and list. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text $ PYTHONPATH=. /tmp/headroom3651-venv/bin/python -m pytest -q tests/test_memory_handler_project_isolation.py 10 passed in 1.32s $ /tmp/headroom3651-venv/bin/ruff check headroom/proxy/memory_handler.py tests/test_memory_handler_project_isolation.py All checks passed! $ git diff --check # no output ``` ## Real Behavior Proof - Environment: current repository main at base commit `ff23cfbc178424f3c085493fa9e5b1809461c189` was not used here; this branch is based on Headroom commit `7639bca`'s parent. Regression was run before the production-code change in this worktree. - Exact command / steps: added a parameterized regression invoking `memory_save`, `memory_search`, `memory_update`, `memory_delete`, and `memory_list` with PROJECT storage and no resolvable project identity. - Observed result: before the fix all 5 cases failed the fail-closed assertion (`saved`, `found`, `updated`, `deleted`, `ok`); after the fix the complete isolation test file passes 10/10. - Not tested: full repository test suite and mypy were not run. ## Runtime Rollout Safety - Rollout-managed feature(s): memory PROJECT storage mode. - Minimum rollout channel: N/A; correctness fix within existing PROJECT fail-closed semantics. - Stable/default behavior changed: only explicit memory tool calls with unresolved PROJECT scope now fail closed instead of reaching the fallback backend. - Kill switch / disable path: existing `unresolved_project_fallback=global` remains the explicit opt-in to legacy global fallback. - Unsafe override required: no. - Qualification impact: prevents unresolved workspace operations from crossing the intended project boundary. - Rollback path: revert this commit; no schema or persisted-data migration is involved. ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of my code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] New and existing targeted unit tests pass locally with my changes - [x] I did **not** edit `CHANGELOG.md` ## Screenshots (if applicable) N/A. ## Additional Notes Documentation is unchanged because this restores the already-documented fail-closed PROJECT behavior rather than introducing a new configuration or API. No new complex logic required inline comments. --------- Co-authored-by: tayfuryldzz <238304586+TayfurYldz@users.noreply.github.com> Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
co-authored by
tayfuryldzz
JD Davis
parent
3f3cf19e1a
commit
7c3cbc824c
@@ -674,6 +674,21 @@ class MemoryHandler:
|
||||
)
|
||||
return self._backend, scope, composed
|
||||
|
||||
@staticmethod
|
||||
def _unresolved_project_error(scope: ResolvedScope | None) -> str | None:
|
||||
if (
|
||||
scope is not None
|
||||
and scope.mode is MemoryStorageMode.PROJECT
|
||||
and scope.project_key is None
|
||||
):
|
||||
return json.dumps(
|
||||
{
|
||||
"status": "error",
|
||||
"error": "Memory operation refused because the project could not be resolved",
|
||||
}
|
||||
)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _format_memory_block_header(scope: ResolvedScope | None) -> str:
|
||||
"""Workspace / scope provenance header for the injected memory block.
|
||||
@@ -1239,6 +1254,8 @@ your responses, not to drive new actions."""
|
||||
extracted_relationships = input_data.get("extracted_relationships")
|
||||
|
||||
backend, scope, effective_user_id = self._resolve_for_request(user_id, request_context)
|
||||
if error := self._unresolved_project_error(scope):
|
||||
return error
|
||||
|
||||
# Agent provenance metadata. Workspace lineage is recorded on
|
||||
# the memory itself so cross-project leaks (if any ever
|
||||
@@ -1332,6 +1349,8 @@ your responses, not to drive new actions."""
|
||||
entities_filter = input_data.get("entities")
|
||||
|
||||
backend, _scope, effective_user_id = self._resolve_for_request(user_id, request_context)
|
||||
if error := self._unresolved_project_error(_scope):
|
||||
return error
|
||||
|
||||
results = await backend.search_memories(
|
||||
query=query,
|
||||
@@ -1388,6 +1407,8 @@ your responses, not to drive new actions."""
|
||||
}
|
||||
|
||||
backend, _scope, effective_user_id = self._resolve_for_request(user_id, request_context)
|
||||
if error := self._unresolved_project_error(_scope):
|
||||
return error
|
||||
|
||||
# Check if backend has update_memory method
|
||||
if hasattr(backend, "update_memory"):
|
||||
@@ -1448,6 +1469,8 @@ your responses, not to drive new actions."""
|
||||
return json.dumps({"status": "error", "error": "memory_id is required"})
|
||||
|
||||
backend, _scope, _effective = self._resolve_for_request(user_id, request_context)
|
||||
if error := self._unresolved_project_error(_scope):
|
||||
return error
|
||||
deleted = await backend.delete_memory(memory_id)
|
||||
|
||||
return json.dumps(
|
||||
@@ -1486,6 +1509,8 @@ your responses, not to drive new actions."""
|
||||
return json.dumps({"status": "error", "error": "Memory backend not initialized"})
|
||||
|
||||
backend, _scope, effective_user_id = self._resolve_for_request(user_id, request_context)
|
||||
if error := self._unresolved_project_error(_scope):
|
||||
return error
|
||||
|
||||
# Prefer a native list_memories if the backend has one (LocalBackend
|
||||
# does); fall back to a recency-keyed search when not available.
|
||||
|
||||
@@ -316,3 +316,40 @@ def test_unresolved_project_returns_no_context(tmp_path: Path) -> None:
|
||||
)
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("tool_name", "input_data"),
|
||||
[
|
||||
("memory_save", {"content": "must not persist"}),
|
||||
("memory_search", {"query": "must not read"}),
|
||||
("memory_update", {"memory_id": "m1", "new_content": "must not update"}),
|
||||
("memory_delete", {"memory_id": "m1"}),
|
||||
("memory_list", {}),
|
||||
],
|
||||
)
|
||||
def test_unresolved_project_memory_tools_fail_closed(
|
||||
tmp_path: Path, tool_name: str, input_data: dict[str, Any]
|
||||
) -> None:
|
||||
cfg = MemoryConfig(
|
||||
enabled=True,
|
||||
backend="local",
|
||||
db_path=str(tmp_path / "memory.db"),
|
||||
mode=MemoryMode.TOOL,
|
||||
storage_mode=sr_mod.MemoryStorageMode.PROJECT,
|
||||
)
|
||||
handler = MemoryHandler(cfg, agent_type="test")
|
||||
|
||||
async def run() -> None:
|
||||
await handler._ensure_initialized()
|
||||
ctx = sr_mod.RequestContext(
|
||||
headers={}, system_prompt="You are helpful.", base_user_id="alice"
|
||||
)
|
||||
result = await handler._execute_memory_tool(
|
||||
tool_name, input_data, "alice", request_context=ctx
|
||||
)
|
||||
payload = __import__("json").loads(result)
|
||||
assert payload["status"] == "error"
|
||||
assert "project" in payload["error"].lower()
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
Reference in New Issue
Block a user