Files
strix/tests/tools/test_notes_jsonl_concurrency.py
T
0xallam dc9b9f5f9c refactor: inline non-sandbox actions, strip registry, drop schemas
Cleanup pass after the migration:

#1 Inline ``*_actions.py`` into wrapper ``tool[s].py`` for the
non-sandbox tools (think, todo, notes, reporting, web_search,
finish_scan). One file per tool family now. Helpers + public
function bodies live alongside the ``@strix_tool``-decorated
wrappers that call them.

For notes, the sync helpers are renamed to ``_create_note_impl`` /
``_list_notes_impl`` / etc. so the public names ``create_note`` /
``list_notes`` / etc. can be the FunctionTool instances the agent
factory imports. ``append_note_content`` (used by the agents-graph
wiki-update hook) calls the impl helpers directly.

#2 Delete ``strix/tools/_state_adapter.py``. The ``AgentStateAdapter``
shim only existed to feed legacy ``*_actions.py`` functions a
``state.agent_id`` they could read. With the actions inlined, the
wrappers read ``ctx.context['agent_id']`` directly.

#3 Strip ``strix/tools/registry.py`` from ~250 LOC to ~110.
Deleted: XML schema loading, ``_parse_param_schema``,
``get_tools_prompt``, ``get_tool_param_schema``, ``needs_agent_state``,
``should_execute_in_sandbox``, ``validate_tool_availability`` — all
for the host-side legacy dispatcher path. Kept the ``register_tool``
decorator (sandbox side), ``get_tool_by_name``, ``get_tool_names``,
``tools`` list, ``clear_registry``.

The Jinja prompt template's ``{{ get_tools_prompt() }}`` injection
is dropped — the SDK auto-generates tool descriptions from function
signatures, so the legacy XML tool block was redundant and stale.

#4 Delete every ``*_actions_schema.xml`` (12 files). They were read
by the now-removed ``_load_xml_schema`` to build the legacy prompt's
tool descriptions. No consumer remains.

Side fixes:
- ``reporting_renderer.py`` updated to import ``_parse_*_xml`` from
  the new location with leading underscore.
- ``test_local_tools.py``, ``test_notes_jsonl_concurrency.py``,
  ``test_notes_wiki.py`` updated to point at the new module paths
  and call the ``_*_impl`` sync helpers.

Tests: 279/279 passing. ~1500 LOC of action files moved into the
tool wrappers; ~140 LOC of registry boilerplate removed; ~400 lines
of dead XML deleted.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 11:26:02 -07:00

80 lines
2.6 KiB
Python

"""C6 regression test — concurrent notes JSONL writes must produce valid JSONL.
This test would fail before the C6 fix (AUDIT_R2 §1.1, applied in Phase 2.2):
the legacy ``_append_note_event`` opened the file and called ``f.write``
without holding ``_notes_lock``, so two threads writing simultaneously
could interleave bytes mid-line and corrupt the JSONL.
"""
from __future__ import annotations
import json
import threading
from collections.abc import Iterator
from pathlib import Path
from typing import Any
from unittest.mock import patch
import pytest
from strix.tools.notes.tools import _append_note_event
@pytest.fixture
def notes_path(tmp_path: Path) -> Iterator[Path]:
"""Point ``_get_notes_jsonl_path`` at a tmp file for the test."""
target = tmp_path / "notes" / "notes.jsonl"
target.parent.mkdir(parents=True, exist_ok=True)
with patch(
"strix.tools.notes.tools._get_notes_jsonl_path",
return_value=target,
):
yield target
def test_concurrent_note_writes_yield_valid_jsonl(notes_path: Path) -> None:
"""C6 fix: 50 threads x 20 events = 1000 lines, all valid JSON.
Without the lock, byte-level interleaving on the file produces
fragments like ``{"timesta{"timestamp"...`` that fail json.loads.
"""
def writer(thread_idx: int) -> None:
for i in range(20):
note: dict[str, Any] = {
"title": f"thread-{thread_idx}-note-{i}",
"content": "x" * 200, # non-trivial body to widen the race
"category": "general",
}
_append_note_event(
op="create",
note_id=f"t{thread_idx}-i{i}",
note=note,
)
threads = [threading.Thread(target=writer, args=(t,)) for t in range(50)]
for t in threads:
t.start()
for t in threads:
t.join()
lines = notes_path.read_text(encoding="utf-8").splitlines()
assert len(lines) == 1000, f"expected 1000 lines, got {len(lines)}"
for line in lines:
# raises if the line is malformed JSON
event = json.loads(line)
assert event["op"] == "create"
assert "note_id" in event
def test_single_writer_still_works(notes_path: Path) -> None:
"""Sanity: serial writes still produce a valid JSONL log."""
_append_note_event("create", "n1", {"title": "first"})
_append_note_event("update", "n1", {"title": "first updated"})
_append_note_event("delete", "n1")
events = [json.loads(line) for line in notes_path.read_text().splitlines()]
assert [e["op"] for e in events] == ["create", "update", "delete"]
assert all(e["note_id"] == "n1" for e in events)