Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion backend/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@ models:
lint:
uv run ruff check src examples tests migrations scripts

# Parallel over all CPUs (pytest-xdist); loadfile keeps each test file in one process, so module fixtures load
# once. A plain `uv run pytest <file>` still runs in one process.
unit-test:
uv run pytest
uv run pytest -n auto --dist loadfile

check: lint unit-test

Expand Down
1 change: 1 addition & 0 deletions backend/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ dev = [
"jsonschema>=4.26.0",
"pytest>=9.1.1",
"pytest-asyncio>=1.4.1",
"pytest-xdist>=3.8.0",
"ruff>=0.17.2",
"types-httplib2>=0.32.0.20260720",
"types-jsonschema>=4.26.0.20261006",
Expand Down
6 changes: 3 additions & 3 deletions backend/src/graph/core/ontology/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,11 +214,11 @@ def _discover_submodule_sources() -> list[_Source]:
# Parsing (check 1)


class _UniqueKeyLoader(yaml.SafeLoader):
"""Safe YAML loader that rejects a mapping key written twice."""
class _UniqueKeyLoader(yaml.CSafeLoader):
"""Safe YAML loader (libyaml, about 10x faster than the pure-Python one); rejects a mapping key written twice."""


def _construct_unique_mapping(loader: yaml.SafeLoader, node: yaml.MappingNode) -> dict[Any, Any]:
def _construct_unique_mapping(loader: yaml.CSafeLoader, node: yaml.MappingNode) -> dict[Any, Any]:
loader.flatten_mapping(node)
seen: set[Any] = set()
for key_node, _ in node.value:
Expand Down
7 changes: 3 additions & 4 deletions backend/tests/drive/test_drive_real.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,15 +402,14 @@ def test_nfr_perf_0001_thousand_files_hundred_folders_with_300ms_calls():
for n in range(1000):
holder = holders[n % len(holders)]
tree[holder].append(file_(holder, n))
http = FakeHttp(tree_routes(tree, root), latency=0.3)
started = time.monotonic()
http = FakeHttp(tree_routes(tree, root))
listing = gateway(http).list_all(root)
elapsed = time.monotonic() - started
assert (listing.folder_count, len(listing.items)) == (100, 1000)
assert elapsed <= 20
# root get + root + 9 + ceil(90 / 20) = 5 list calls = 8 calls (paging adds none: < 1000 rows each)
assert len(http.calls) == 8
assert len(http.threads) == 1
# The walk is serial (one thread), so at 300 ms per call it takes calls x 0.3 s: computed, not waited out.
assert len(http.calls) * 0.3 <= 20


# -- download ----------------------------------------------------------------
Expand Down
8 changes: 4 additions & 4 deletions backend/tests/gap_acceptance_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,12 @@
from graph.build import BuildOptions
from graph.build.models import DedupRefusal
from graph.build.ports import CorpusRevision
from graph.core import LLMConfig, load_ontology
from graph.core import LLMConfig
from graph.core.errors import LLMError, LLMErrorReason
from graph.core.reader import GraphFragment, GraphNode
from graph.gap.names import GATEWAY_ROLES, GatewayRole, ReconcileOutcome
from graph.gap.prompts import REFUTE_PROMPT
from graph_plan_support import ShopGraphReader, fixture_graph, write_spec_graph
from graph_plan_support import ShopGraphReader, fixture_graph, plan_ontology, write_spec_graph
from graph_support import NO_ANSWER, GraphProject, ScriptedGateway, ScriptedRequest

__all__ = [
Expand Down Expand Up @@ -241,7 +241,7 @@ def gap_corpus_graph() -> GapCorpusGraph:
return GapCorpusGraph(
build_id=str(data["build_id"]),
build_options=BuildOptions.model_validate(data.get("build_options", {})),
reader=fixture_graph(data, load_ontology()),
reader=fixture_graph(data, plan_ontology()),
dedup_refused=tuple(DedupRefusal.model_validate(item) for item in data.get("dedup_refused", ())),
data=data,
)
Expand All @@ -251,7 +251,7 @@ async def write_gap_corpus_graph(project: GraphProject, project_id: str) -> GapC
"""Write the built graph to a live store project (spec nodes as owner ``build``) and return it."""

graph = gap_corpus_graph()
await write_spec_graph(project, project_id, graph.reader, load_ontology())
await write_spec_graph(project, project_id, graph.reader, plan_ontology())
return graph


Expand Down
16 changes: 8 additions & 8 deletions backend/tests/gap_detection_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

from gap_acceptance_support import GapCorpusGraph, RecordedGapGateway, gap_corpus_graph
from gap_port_fakes import MemoryGapRecords
from graph.core import Ontology, load_ontology
from graph.core import Ontology
from graph.core.evidence import EvidenceItem
from graph.core.expand import Expansion, ExpansionItem, SimilarResult
from graph.core.ontology.compiled import COUPLED, RELATED, USED_BY, USES
Expand All @@ -37,12 +37,12 @@
from graph.gap.models import BuildFacts, CutEdge, RefusedPair
from graph.gap.names import RunMode
from graph.gap.ports import PlanView
from graph.gap.rules import GapRules, load_gap_rules
from graph.gap.rules import GapRules
from graph.gap.steps.detect import DetectOutcome, detect
from graph.gap.steps.relevance import RelevanceOutcome, classify_sections
from graph.gap.steps.sites import ExistingGap, SiteRun, SitesOutcome, form_sites
from graph.gap.steps.snapshot import GraphSnapshot, read_snapshot
from graph_plan_support import fixture_graph
from graph_plan_support import fixture_graph, gap_rules, plan_ontology

PROJECT = "shop"
RUN_ID = "run-1"
Expand Down Expand Up @@ -306,8 +306,8 @@ async def run_detection(
) -> Detection:
"""``relevance``, ``detect`` and ``sites`` on ``reader`` (default: the shop corpus graph with trace)."""

ontology = load_ontology()
rules = load_gap_rules(ontology=ontology)
ontology = plan_ontology()
rules = gap_rules()
given = setup or DetectionSetup()
source = reader or TracingReader(gap_corpus_graph().reader, ontology)
snapshot = await read_snapshot(source, project_id, ontology)
Expand Down Expand Up @@ -429,10 +429,10 @@ def edge(self, source: str, relation: str, target: str, *, evidence: Sequence[tu
)

def snapshot(self) -> GraphSnapshot:
return GraphSnapshot(load_ontology(), self.nodes, self.edges, self.documents.values(), self.fragments)
return GraphSnapshot(plan_ontology(), self.nodes, self.edges, self.documents.values(), self.fragments)

def reader(self) -> TracingReader:
return TracingReader(_ListReader(self), load_ontology())
return TracingReader(_ListReader(self), plan_ontology())


@dataclass(frozen=True)
Expand Down Expand Up @@ -477,7 +477,7 @@ def corpus_reader(
fragment["line_end"] += 1
data["nodes"] += [dict(item) for item in nodes]
data["edges"] += [dict(item) for item in edges]
return TracingReader(fixture_graph(data, load_ontology()), load_ontology())
return TracingReader(fixture_graph(data, plan_ontology()), plan_ontology())


def _replaced(value: Any, old: str, new: str) -> Any:
Expand Down
9 changes: 5 additions & 4 deletions backend/tests/gap_run_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,13 @@
from gap_detection_support import PROJECT, TracingReader, build_facts
from gap_port_fakes import MemoryAmendments, MemoryGapRecords, SeedInvestigator
from gap_support import MemoryGapExecutor
from graph.core import Ontology, load_ontology
from graph.core import Ontology
from graph.gap import GapContext, MemoryGapRunStore
from graph.gap.models import BuildFacts, GapChangeReport, InvestigationResult, SiteBudget, SitePack
from graph.gap.ports import Investigator, PlanView, SiteReads
from graph.gap.rules import GapRules, load_gap_rules
from graph.gap.rules import GapRules
from graph.gap.settings import GapSettings
from graph_plan_support import gap_rules, plan_ontology


class CountingInvestigator:
Expand Down Expand Up @@ -107,13 +108,13 @@ def about(self, gap_id: str) -> set[str]:
async def corpus_world(reader: Any = None, *, plan: PlanView | None = None, project_id: str = PROJECT) -> GapWorld:
"""A world over the shop corpus graph (or ``reader``)."""

ontology = load_ontology()
ontology = plan_ontology()
source = reader or TracingReader(gap_corpus_graph().reader, ontology)
return GapWorld(
reader=source,
executor=await executor_for(source, project_id),
ontology=ontology,
rules=load_gap_rules(ontology=ontology),
rules=gap_rules(),
plan=plan,
project_id=project_id,
)
26 changes: 23 additions & 3 deletions backend/tests/graph_plan_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import json
from collections.abc import Iterable, Mapping, Sequence
from dataclasses import dataclass
from functools import cache
from pathlib import Path
from typing import Any

Expand All @@ -17,6 +18,7 @@
from graph.core.queries import DOCUMENT, FRAGMENT
from graph.core.reader import GraphDocument, GraphEdge, GraphFragment, GraphNode
from graph.core.writer import NodeRef
from graph.gap.rules import GapRules, load_gap_rules
from graph.plan.answers import (
ConventionAnswer,
DescribeAnswer,
Expand Down Expand Up @@ -71,6 +73,7 @@
"SnapshotQueries",
"applied_plan",
"change_reports",
"gap_rules",
"generic_planners",
"live_context",
"next_view",
Expand All @@ -96,16 +99,32 @@
_EMPTY_REVISIONS = MeaningRevisions()


@cache
def plan_ontology() -> Ontology:
"""The merged ontology the shipped plan rules target."""
"""The merged ontology the shipped plan rules target. Parsed once per process: thousands of tests share it, and
``Ontology`` is frozen."""

return load_ontology()


def plan_rules(ontology: Ontology | None = None) -> PlanRules:
"""The shipped plan rules, validated against the merged ontology."""
"""The shipped plan rules, validated against the merged ontology (``ontology`` when given)."""

return load_plan_rules(ontology=ontology or plan_ontology())
if ontology is None or ontology is plan_ontology():
return _shipped_plan_rules()
return load_plan_rules(ontology=ontology)


@cache
def _shipped_plan_rules() -> PlanRules:
return load_plan_rules(ontology=plan_ontology())


@cache
def gap_rules() -> GapRules:
"""The shipped gap rules against the merged ontology, loaded once per process (``GapRules`` is frozen)."""

return load_gap_rules(ontology=plan_ontology())


@dataclass(frozen=True)
Expand Down Expand Up @@ -741,6 +760,7 @@ def _changed_edge(edge: ChangedEdge) -> ChangedSpecEdge:
)


@cache # the models are frozen and the fixture holds tuples, so every caller can share one parse
def _load_shop_fixture() -> _ShopFixture:
with _SHOP_FIXTURE.open(encoding="utf-8") as stream:
data = yaml.safe_load(stream)
Expand Down
10 changes: 9 additions & 1 deletion backend/tests/graph_trace_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import shutil
from collections.abc import Mapping, Sequence
from dataclasses import dataclass, field
from functools import cache
from pathlib import Path
from typing import Any, Final

Expand Down Expand Up @@ -53,10 +54,17 @@ def by_uuid(self) -> dict[str, tuple[str, dict[str, Any]]]:
return {node["uuid"]: (spec_id, node) for spec_id, node in self.nodes.items()}


@cache
def _shop_data() -> dict[str, Any]:
"""The parsed shop fixture, read once; only read here (``shop_graph`` copies what it keeps)."""

return yaml.safe_load(SHOP_FIXTURE.read_text(encoding="utf-8"))


def shop_graph() -> TraceGraph:
"""The shop fixture (``fixtures/graph/plan/shop.yaml``): its spec nodes and edges, copied."""

data = yaml.safe_load(SHOP_FIXTURE.read_text(encoding="utf-8"))
data = _shop_data()
graph = TraceGraph()
for node in data["nodes"]:
graph.nodes[node["spec_id"]] = {
Expand Down
6 changes: 3 additions & 3 deletions backend/tests/people_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,11 @@
from gap_support import Clock, MemoryGapExecutor
from graph.core import GraphReader
from graph.core.reader import GraphEdge, GraphNode
from graph.gap import GapService, NewGap, load_gap_rules
from graph.gap import GapService, NewGap
from graph.gap.gaps import gap_uuid
from graph.plan import PlanService
from graph.plan.lifecycle import TaskLifecycle
from graph_plan_support import plan_ontology, plan_rules
from graph_plan_support import gap_rules, plan_ontology, plan_rules
from plan_claims_support import MemoryPlanExecutor, mini_plan
from specflow_api_agent_support import ALPHA, AgentRig, serve_agent

Expand Down Expand Up @@ -172,7 +172,7 @@ async def serve_people(
gap,
GraphReader(rig.executor, ontology),
ontology,
load_gap_rules(ontology=ontology),
gap_rules(),
records,
MemoryAmendments(),
holds=PlanHolds(plan),
Expand Down
14 changes: 11 additions & 3 deletions backend/tests/spec_reads_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
from collections.abc import AsyncIterator, Sequence
from contextlib import asynccontextmanager
from dataclasses import dataclass
from functools import cache
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Final
Expand All @@ -38,14 +39,14 @@
from gap_support import Clock, MemoryGapExecutor
from graph.core import GraphReader, LLMError
from graph.core.queries import Query
from graph.gap import GapService, NewGap, load_gap_rules
from graph.gap import GapService, NewGap
from graph.gap.gaps import gap_uuid
from graph.plan import PlanService
from graph.plan.models import CurrentTask
from graph.plan.reader import LoadedPlan
from graph.stores._bolt.cypher import binds_project_id, render_cypher
from graph.stores.postgres.dialect import PostgresDialect
from graph_plan_support import plan_ontology, plan_rules
from graph_plan_support import gap_rules, plan_ontology, plan_rules
from graph_support import OfflineExecutor
from graph_trace_support import TraceExecutor, TraceGraph, shop_graph
from plan_claims_support import MemoryPlanExecutor
Expand Down Expand Up @@ -100,6 +101,13 @@ def vector_score(first: Sequence[float], second: Sequence[float]) -> float:


def load_shop() -> dict[str, Any]:
"""A fresh copy of the parsed shop fixture (callers change it)."""

return copy.deepcopy(_shop_data())


@cache
def _shop_data() -> dict[str, Any]:
return yaml.safe_load(SHOP.read_text(encoding="utf-8"))


Expand Down Expand Up @@ -407,7 +415,7 @@ async def serve_spec(
runner = DevelopmentRunner()
port = OpenGaps(lambda: runner)
records = MemoryGapRecords()
rules = load_gap_rules(ontology=ontology)
rules = gap_rules()
clock = Clock() # one clock: a gap raised through a route is newer than the seeds

def gap_service(holds: Any) -> GapService:
Expand Down
3 changes: 2 additions & 1 deletion backend/tests/test_db_source_files_offline.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@
from db.sources import UPLOAD_STALE_AFTER

CONTRACT = Path(sf.__file__).resolve().parents[1] / "api" / "fixtures" / "sources-contract.json"
ID = uuid.uuid4()
# Fixed, not uuid4(): it is in parametrize ids, which every xdist worker must collect the same.
ID = uuid.UUID("9e924a8f-6663-4418-8cc7-e758414b4a6a")
FRESH = timedelta(minutes=5)
STALE = UPLOAD_STALE_AFTER + timedelta(seconds=1)

Expand Down
11 changes: 6 additions & 5 deletions backend/tests/test_logger_concurrency.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,18 +280,19 @@ def blocking_emit(self, record):
log_event(logger_, INFO, "test.overflow", i=i)

assert dropped_count() in (149, 150)

heartbeat_lines = [
line for line in central_log.stderr().splitlines() if "[central-logger]" in line and "queue" in line.lower()
]
assert len(heartbeat_lines) == 1
finally:
# Always release the blocked listener thread, even on assertion
# failure — otherwise it stays blocked for up to 10s, slowing down
# the rest of the suite.
release.set()

assert flush(timeout=10.0) is True
# Read stderr only after the release: ``stderr()`` flushes the pipeline first, which waits out its whole 5 s
# timeout while ``emit`` is blocked.
heartbeat_lines = [
line for line in central_log.stderr().splitlines() if "[central-logger]" in line and "queue" in line.lower()
]
assert len(heartbeat_lines) == 1


# ---------------------------------------------------------------------------
Expand Down
6 changes: 4 additions & 2 deletions backend/tests/test_mcp_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,16 +225,18 @@ async def hang(request: httpx.Request) -> httpx.Response:
assert (event.outcome, event.error_type) == ("internal_error", "ApiTimeout")


async def test_a_hanging_api_makes_readyz_503_api_unreachable_within_the_probe_timeout(valid_env) -> None:
async def test_a_hanging_api_makes_readyz_503_api_unreachable_within_the_probe_timeout(valid_env, monkeypatch) -> None:
async def hang(_request: httpx.Request) -> httpx.Response:
await asyncio.Event().wait() # never answers
return httpx.Response(200)

assert READYZ_TIMEOUT_SECONDS == 3 < API_TIMEOUT_SECONDS
short = 0.2 # the probe reads its timeout at call time; a short one keeps the real wait out of the test
monkeypatch.setattr("mcp_server.api_client.READYZ_TIMEOUT_SECONDS", short)
async with serving(build_app(mcp_env(valid_env), transport=httpx.MockTransport(hang))) as client:
started = time.monotonic()
reply = await client.get("/readyz")

assert time.monotonic() - started < READYZ_TIMEOUT_SECONDS + 1
assert time.monotonic() - started < short + 1
assert reply.status_code == 503
assert {c["detail"] for c in reply.json()["checks"].values()} == {"api_unreachable"}
Loading
Loading