Test with and without local infrastructure: the infra profile matrix

tests/infra.py names the box's states as profiles (bare, fresh, index_only, index_graph,
full, graph_partial, vectors_partial, rebuild_pending, upstream_down, upstream_timeout),
built once per session from the search fixture and the fakes, in tmp dirs; the `infra`
fixture runs a test per profile (@pytest.mark.infra, --infra=, INSIDER_INFRA), and
INSIDER_INFRA_DB=1 puts a profile's state in a throwaway Postgres.

tests/test_infra_matrix.py: one response shape, the Civil Code's t.j. first for
"Kodeks cywilny"/"k.c.", rank_prior honesty, vectors only when complete, index notices
exactly when a local source cannot serve, nothing built/downloaded/loaded in a request,
every CELEX opens, charset=utf-8, a per-request memory ceiling.

search_eval --profile prints a table per profile; the regression set is asserted in
bare and full. CI: an infra-matrix job (bare/full, DB-free and on Postgres). Docs in
README and CLAUDE.md. test_indexed_db no longer leaves legal_graph/legal_rank states.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-22 23:03:45 +02:00
co-authored by Claude Opus 5.5
parent f55d679e45
commit fbb758e432
9 changed files with 1145 additions and 4 deletions
+66
View File
@@ -79,6 +79,72 @@ jobs:
# creeping back into compose.
run: python scripts/deploy_check.py
# ── with and without local infrastructure (tests/infra.py) ──────────────────
# The backend job above runs EVERY infra profile DB-free (in-memory store). This one runs the
# two every feature must pass — `bare` (LIVE only) and `full` (index, lexicon, graph, rank,
# vectors, CELLAR) — once DB-free and once with the profile's state in Postgres
# (INSIDER_INFRA_DB=1: a fresh database the profile fills and empties), plus search_eval's table.
infra-matrix:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
profile: ["bare", "full"]
services:
postgres:
image: postgres:17
env:
POSTGRES_DB: insider
POSTGRES_PASSWORD: superpw
ports: ["5432:5432"]
options: >-
--health-cmd "pg_isready -U postgres" --health-interval 5s
--health-timeout 5s --health-retries 20
env:
DATABASE_URL: postgresql+pg8000://app:apppw@localhost:5432/insider
MIGRATION_DATABASE_URL: postgresql+pg8000://migrator:migpw@localhost:5432/insider
DATA_DIR: ${{ github.workspace }}/insider-data
BOOTSTRAP_ADMIN_EMAIL: admin@example.com
BOOTSTRAP_ADMIN_PASSWORD: adminpass1
INSIDER_INFRA: ${{ matrix.profile }}
steps:
- uses: actions/checkout@v5
- uses: actions/setup-python@v6
with: { python-version: "3.12" }
- name: Create least-privilege roles
run: |
PGPASSWORD=superpw psql -h localhost -U postgres -d insider -v ON_ERROR_STOP=1 <<'SQL'
CREATE ROLE migrator LOGIN PASSWORD 'migpw';
CREATE ROLE app LOGIN PASSWORD 'apppw';
GRANT CONNECT ON DATABASE insider TO migrator, app;
ALTER SCHEMA public OWNER TO migrator;
GRANT USAGE ON SCHEMA public TO app;
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
SQL
- name: Authenticate to dredd-core
env:
TOKEN: ${{ secrets.DREDD_CORE_TOKEN }}
run: |
git config --global url."https://x-access-token:${TOKEN}@github.com/Alpaq92/dredd-core".insteadOf "https://github.com/Alpaq92/dredd-core"
- name: Install deps
working-directory: backend
run: pip install -r requirements-dev.txt
- name: Invariants, DB-free (${{ matrix.profile }})
working-directory: backend
run: pytest -q tests/test_infra_matrix.py tests/test_search_quality.py -k infra
- name: search_eval (${{ matrix.profile }})
working-directory: backend
run: python tests/search_eval.py --profile ${{ matrix.profile }}
- name: Migrate + seed
working-directory: backend
run: alembic upgrade head && python -m app.seed
- name: Invariants, state in Postgres (${{ matrix.profile }})
working-directory: backend
env:
INSIDER_RUN_INTEGRATION: "1"
INSIDER_INFRA_DB: "1"
run: pytest -q tests/test_infra_matrix.py tests/test_search_quality.py -k infra
# ── the family's shared managed database, emulated ──────────────────────────
# The backend job runs on a superuser-made `app`/`migrator` pair in `public`. In the shared managed
# database, Insider lives in schema `insider` as `insider_migrator` / `insider_app`,
+15
View File
@@ -122,6 +122,10 @@ DREDD_CORE_TOKEN=... docker compose up -d --build # full stack; the token is a
# shell only, never .env (containers load .env)
cd backend && pytest # DB-free unit tests; integration auto-skips
INSIDER_RUN_INTEGRATION=1 pytest # full API loop (needs a migrated+seeded Postgres)
pytest tests/test_infra_matrix.py --infra=bare,full # the infra profiles (tests/infra.py); default all
python tests/search_eval.py --profile=all # top-3 table per infra profile
INSIDER_RUN_INTEGRATION=1 INSIDER_INFRA_DB=1 pytest tests/test_infra_matrix.py # profile state in
# Postgres — a THROWAWAY database only (refuses one with acts)
alembic upgrade head --sql # inspect the DDL with no database
python -m dredd_core.managed provision --sql-only --schema insider --app-role insider_app \
--migrator-role insider_migrator --check-file ../db/managed/provision.sql # rendering current?
@@ -227,6 +231,17 @@ frontend/ui/v1/ the family's shared shell (a copy of Atrium's; don't edit loca
never Surya, MinerU, marker, PyMuPDF (the license gate denies them by name). Works with OCR off.
- **Tests never call a real source** — `tests/fakes.py` (httpx MockTransport) only.
`scripts/live_check.py` is the manual live probe (REST's code path, a hard request budget).
- **Test with AND without local infrastructure.** `tests/infra.py` names the box's states as
profiles (`bare` LIVE only · `fresh` · `index_only` · `index_graph` · `full` · `graph_partial` ·
`vectors_partial` · `rebuild_pending` · `upstream_down` · `upstream_timeout`), built from the
search fixture and the fakes; a test takes the `infra` fixture (narrow with
`@pytest.mark.infra(...)`, `--infra=`, `INSIDER_INFRA`). `tests/test_infra_matrix.py` is the
invariants suite (shape, the named code first, `rank_prior` honesty, vectors only when complete,
`index_*` notices exactly when a local source cannot serve, nothing built/downloaded/loaded in a
request, CELEX opens, charset, memory). **Every new feature that depends on local
infrastructure is tested in `bare` and `full`** (CI's `infra-matrix` job), plus the degraded
profile of its component when there is one — and a new component gets its states added to
`Profile` and the invariant it promises added to the matrix.
- **Title search is inflection-aware** (`integrations/plstem.py`, in-house, permissive): ELI gets the
light stem of the longest word and the titles are filtered client-side (`SearchPage.next_offset`
counts ELI's rows); CELLAR gets prefix matches only for stems of 5+ characters (shorter ones as
+41
View File
@@ -619,6 +619,47 @@ node --check ../frontend/app.js # the console has no build step, so this
The API is served under `/api/v1`, with OpenAPI docs at `/api/v1/docs`.
### Testing with and without local infrastructure
Insider answers LIVE by default and leans on whatever local infrastructure the box has — the
tantivy index, the sjp.pl lexicon, the reference graph, its PageRank, the vectors, the CELLAR
tables — each of which can be absent, half-built or stale. `tests/infra.py` names those states of
the whole box as **profiles**, built cheaply from the committed search fixture and the fake
upstreams (tmp dirs, never a network):
| profile | index | lexicon | graph | rank | vectors | CELLAR | live upstreams |
|---|---|---|---|---|---|---|---|
| `bare` | — (LIVE only) | no | — | — | — | empty | up |
| `fresh` | INDEXED on, nothing built | yes | — | — | — | empty | up |
| `index_only` | format 3 | no (plstem) | — | — | — | empty | up |
| `index_graph` | format 3 | yes | complete | — | — | empty | up |
| `full` | format 3 | yes | complete | complete | complete | complete | up |
| `graph_partial` | format 3 | yes | interrupted | stale | complete | partial | up |
| `vectors_partial` | format 3 | yes | complete | complete | no `last_pass` | complete | up |
| `rebuild_pending` | format 2 serving | yes | complete | complete | complete | complete | up |
| `upstream_down` | format 3 | yes | complete | complete | complete | complete | 503 |
| `upstream_timeout` | — | no | — | — | — | empty | hanging |
A test asks for the `infra` fixture and runs once per profile; `@pytest.mark.infra("bare",
"full")` narrows it. `tests/test_infra_matrix.py` holds the invariants every profile keeps: one
response shape, the Civil Code's t.j. first for "Kodeks cywilny" / "k.c.", `rank_prior` = "graph"
only with a complete rank, the vector side only with complete vectors, an `index_*` notice exactly
when a local source cannot serve, nothing built / downloaded / loaded in the request path, every
CELEX returned opens, `charset=utf-8`, and a memory ceiling per request.
```bash
pytest tests/test_infra_matrix.py # every profile, DB-free
pytest tests/test_infra_matrix.py --infra=bare # one profile (or INSIDER_INFRA=bare,full)
python tests/search_eval.py --profile=all # the top-3 table per profile (or --profile full)
INSIDER_RUN_INTEGRATION=1 INSIDER_INFRA_DB=1 pytest tests/test_infra_matrix.py --infra=full
# the profile's state in Postgres: a THROWAWAY
# database only (it refuses one holding acts)
```
**Every new feature that depends on local infrastructure is tested in `bare` and `full`** (CI's
`infra-matrix` job runs both, DB-free and on Postgres) — and in the degraded profile its component
can be in, when it has one.
## Deploying on a managed PostgreSQL
The Dredd family can run in **one shared managed database** (one PostgreSQL 16/17 database at a managed
+42
View File
@@ -100,3 +100,45 @@ def make_user(admin_client):
assert login.status_code == 200, login.text
return {**r.json(), "token": login.json()["token"]}
return _make
# ── the local-infrastructure matrix (`tests/infra.py`) ──────────────────────────────────────────────
def pytest_addoption(parser):
parser.addoption("--infra", default=None,
help="infra profiles to run (comma-separated, or 'all'; default: "
"INSIDER_INFRA or all) — see tests/infra.py")
def pytest_configure(config):
config.addinivalue_line("markers", "infra(*profiles): run this test only in these infra "
"profiles (tests/infra.py); default: every profile")
def pytest_generate_tests(metafunc):
"""A test that asks for `infra` runs once per selected profile (module-scoped: one world per
profile per module), narrowed by its `@pytest.mark.infra(...)`."""
if "_infra_world" not in metafunc.fixturenames:
return
import infra as _infra
names = _infra.selected(metafunc.config.getoption("--infra"))
marker = metafunc.definition.get_closest_marker("infra")
if marker is not None and marker.args:
names = [n for n in names if n in marker.args]
metafunc.parametrize("_infra_world", names, indirect=True, scope="module",
ids=[f"infra={n}" for n in names])
@pytest.fixture(scope="module")
def _infra_world(request, tmp_path_factory):
import infra as _infra
world = _infra.build_world(request.param, tmp_path_factory.mktemp(f"infra-{request.param}"),
db=_infra.INFRA_DB)
yield world
world.close()
@pytest.fixture
def infra(_infra_world):
"""The profile's `infra.World`, its process-wide switches (lexicon, models) put in place."""
_infra_world.activate()
yield _infra_world
+666
View File
@@ -0,0 +1,666 @@
"""The local-infrastructure matrix: named PROFILES of what is on the box, built cheaply for a test.
Insider answers LIVE by default and leans on local infrastructure when it is there — a tantivy
index, the sjp.pl lexicon, the reference graph, its PageRank, the vectors, the CELLAR tables. Every
one of them can be absent, half-built or stale on a real box, and a search must keep its shape and
its promises in each case. A profile names one such state of the whole box:
bare LIVE only — nothing local (INSIDER_INDEX_ENABLED=false)
fresh INDEXED mode switched on, nothing imported yet (a first deploy)
index_only the act index (format 3) and nothing else — no lexicon (plstem fallback),
no graph, no rank, no vectors, no CELLAR rows
index_graph + the lexicon and the reference graph; no PageRank yet
full index, lexicon, graph, PageRank, vectors and CELLAR, all complete
graph_partial full, but the graph build was interrupted (its rank is therefore stale)
vectors_partial full, but the first embedding pass has not finished (no `last_pass`)
rebuild_pending full, but the index on disk is format 2: the old index serves, a rebuild waits
upstream_down full, with every live upstream answering 503
upstream_timeout bare, with every live upstream hanging past the search budget
Every component state (`Profile`'s fields) comes from the committed search fixture
(`fixtures/search_eval.json.gz`, through `search_eval`'s production pipeline) and the fakes —
in tmp dirs, never a network. The expensive parts (the index per analysis and format, the graph,
the vectors) are built ONCE per session and copied per profile.
Use: ask for the `infra` fixture; it runs the test once per profile. `@pytest.mark.infra("bare",
"full")` narrows a test to those; `pytest --infra=bare` (or INSIDER_INFRA=bare,full) narrows the
whole run. A profile with `db=True` state would run on Postgres — see `INFRA_DB` below.
"""
from __future__ import annotations
import asyncio
import copy
import dataclasses
import datetime as dt
import os
import shutil
import tempfile
import uuid
from pathlib import Path
from types import SimpleNamespace
import httpx
from fakes import FakeUpstream
ALL = "all"
@dataclasses.dataclass(frozen=True)
class Profile:
name: str
#: None (LIVE only) · "absent" (INDEXED on, nothing built) · "3" (current) · "2" (format 2 on
#: disk: ready, not current — the old index serves while the rebuild is pending)
index: str | None = None
lexicon: bool = False
#: None · "partial" (interrupted after a finished build) · "complete"
graph: str | None = None
#: None · "stale" (from an older graph build) · "complete"
rank: str | None = None
#: None · "partial" (no `last_pass`) · "complete"
vectors: str | None = None
#: "empty" · "partial" (rows, first import unfinished) · "complete"
cellar: str = "empty"
#: "ok" · "timeout" · "down"
upstream: str = "ok"
def describe(self) -> str:
return (f"index={self.index or '-'} lexicon={'yes' if self.lexicon else 'no'} "
f"graph={self.graph or '-'} rank={self.rank or '-'} vectors={self.vectors or '-'} "
f"cellar={self.cellar} upstream={self.upstream}")
@property
def indexed(self) -> bool:
return self.index is not None
@property
def index_serves(self) -> bool:
return self.index in ("2", "3")
@property
def graph_prior(self) -> bool:
return self.graph == "complete" and self.rank == "complete"
@property
def vectors_used(self) -> bool:
return self.index_serves and self.vectors == "complete"
_FULL = dict(index="3", lexicon=True, graph="complete", rank="complete", vectors="complete",
cellar="complete")
PROFILES: dict[str, Profile] = {p.name: p for p in (
Profile("bare"),
Profile("fresh", index="absent", lexicon=True),
Profile("index_only", index="3"),
Profile("index_graph", index="3", lexicon=True, graph="complete"),
Profile("full", **_FULL),
Profile("graph_partial", **{**_FULL, "graph": "partial", "rank": "stale", "cellar": "partial"}),
Profile("vectors_partial", **{**_FULL, "vectors": "partial"}),
Profile("rebuild_pending", **{**_FULL, "index": "2"}),
Profile("upstream_down", **{**_FULL, "upstream": "down"}),
Profile("upstream_timeout", upstream="timeout"),
)}
#: what CI runs on every push (`.github/workflows/ci.yml`'s matrix) and what search_eval asserts
CORE = ("bare", "full")
#: Postgres-backed state (PgIndexStore instead of MemoryIndexStore). Opt-in TWICE: the integration
#: gating (INSIDER_RUN_INTEGRATION=1) AND INSIDER_INFRA_DB=1, because a profile writes the shared
#: `dataset_sync` names (`dzu_md`, `legal_graph`…) — it refuses a database that holds any act, and
#: deletes everything it wrote afterwards. Throwaway databases only.
INFRA_DB = (os.environ.get("INSIDER_RUN_INTEGRATION") == "1"
and os.environ.get("INSIDER_INFRA_DB") == "1")
def selected(cli: str | None = None) -> list[str]:
"""The profiles this run covers: `--infra=a,b`, else INSIDER_INFRA, else every one."""
raw = cli or os.environ.get("INSIDER_INFRA") or ALL
if raw.strip() == ALL:
return list(PROFILES)
names = [n.strip() for n in raw.split(",") if n.strip()]
unknown = [n for n in names if n not in PROFILES]
if unknown:
raise ValueError(f"unknown infra profile(s) {unknown}; known: {', '.join(PROFILES)}")
return names
# ── the fake live upstreams ─────────────────────────────────────────────────────────────────────────
KC_TJ = "DU/2026/795"
KP_TJ = "DU/2026/1245"
GDPR = "32016R0679"
_OBW = ("Obwieszczenie Marszałka Sejmu Rzeczypospolitej Polskiej z dnia {d} r. w sprawie ogłoszenia "
"jednolitego tekstu ustawy - {name}")
#: ELI's catalogue as the fakes hold it: the codes' base acts, their current t.j., an amending act
ELI_CATALOGUE = [
dict(pub="DU", year=1964, pos=16, title="Ustawa z dnia 23 kwietnia 1964 r. - Kodeks cywilny",
date="1964-04-23"),
dict(pub="DU", year=2025, pos=812, title="Ustawa z dnia 4 czerwca 2025 r. o zmianie ustawy - "
"Kodeks cywilny oraz niektórych innych ustaw", date="2025-06-04"),
dict(pub="DU", year=2026, pos=795, title=_OBW.format(d="2 czerwca 2026", name="Kodeks cywilny"),
date="2026-06-02", type="Obwieszczenie"),
dict(pub="DU", year=2026, pos=1245, title=_OBW.format(d="1 września 2026", name="Kodeks pracy"),
date="2026-09-01", type="Obwieszczenie"),
dict(pub="DU", year=2025, pos=734, title=_OBW.format(d="5 maja 2025", name="Kodeks wykroczeń"),
date="2025-05-05", type="Obwieszczenie"),
dict(pub="DU", year=2024, pos=1251, title=_OBW.format(
d="9 sierpnia 2024", name="Prawo o ruchu drogowym"), date="2024-08-09", type="Obwieszczenie"),
dict(pub="DU", year=2026, pos=91, title="Rozporządzenie Ministra Infrastruktury z dnia 12 "
"stycznia 2026 r. w sprawie kontroli ruchu drogowego", date="2026-01-12",
type="Rozporządzenie"),
dict(pub="DU", year=2019, pos=1781, title=_OBW.format(
d="19 lipca 2019", name="o ochronie danych osobowych").replace("ustawy - o", "ustawy o"),
date="2019-07-19", type="Obwieszczenie"),
]
def _eli_items():
from fakes import eli_item
out = []
for c in ELI_CATALOGUE:
kw = {k: v for k, v in c.items() if k != "type"}
item = eli_item(**kw)
if "type" in c:
item["type"] = c["type"]
out.append(item)
return out
class MatrixUpstream(FakeUpstream):
"""`FakeUpstream` with a state: "ok" routes as usual; "timeout" hangs every request past any
budget; "down" answers every request 503. Every request is recorded either way."""
def __init__(self, mode: str = "ok") -> None:
super().__init__()
self.mode = mode
async def __call__(self, request: httpx.Request) -> httpx.Response:
if self.mode == "ok":
return await super().__call__(request)
self.calls.append(request)
if self.mode == "timeout":
await asyncio.sleep(30) # cancelled by the search budget
return httpx.Response(503, text="down")
def fake_upstream(mode: str = "ok"):
"""ELI, SAOS and CELLAR as the fakes know them: available ("ok"), hanging past every budget
("timeout") or answering 503 ("down"). ELI filters its catalogue by the `title` substring, the
way the real API does, so a code's name finds the code and nothing else."""
from fakes import (
ELI,
EURLEX,
SAOS,
eli_search,
eurlex_row,
eurlex_text,
saos_item,
saos_search,
sparql,
)
up = MatrixUpstream(mode)
items = _eli_items()
def eli_search_handler(request):
t = (request.url.params.get("title") or "").lower()
hit = [i for i in items if t in i["title"].lower()]
off, lim = int(request.url.params.get("offset", 0)), int(request.url.params.get("limit", 50))
return httpx.Response(200, json=eli_search(hit[off:off + lim], total=len(hit)))
up.route(ELI, "/eli/acts/search", eli_search_handler)
for i in items:
up.json(ELI, f"/eli/acts/{i['ELI']}", i)
up.json(SAOS, "/api/search/judgments", saos_search([saos_item()]))
up.json(SAOS, "/api/judgments/554187",
{"links": [], "data": {**saos_item(), "textContent": "<p>Sąd orzeka</p>"}})
def sparql_handler(request):
q = request.url.params.get("query") or ""
if 'IN ("6")' in q or "62018CJ0311" in q:
rows = [eurlex_row(celex="62018CJ0311", ltype="CJ", title="Wyrok w sprawie C-311/18",
ecli="ECLI:EU:C:2020:559", date="2020-07-16")]
else:
rows = [eurlex_row()]
return httpx.Response(200, json=sparql(rows))
up.route(EURLEX, "/webapi/rdf/sparql", sparql_handler)
eurlex_text(up, GDPR, '<?xml version="1.0" encoding="UTF-8"?><html '
'xmlns="http://www.w3.org/1999/xhtml"><body><p>Artykuł 1</p></body></html>')
return up
#: hosts only an IMPORTER may reach (a dataset download); a request never does
DATASET_HOSTS = {"github.com", "raw.githubusercontent.com", "huggingface.co"}
def dataset_calls(up) -> list[str]:
return [str(c.url) for c in up.calls
if c.url.host in DATASET_HOSTS or c.url.path.startswith("/api/dump/")]
# ── the fake embedder (the vectors' model) ──────────────────────────────────────────────────────────
class FakeEmbedder:
"""Words → a bag-of-letters vector: deterministic, offline, never a download. Counts its calls
by kind, so a test can tell whether the vector side was asked."""
name = "fake:embed"
dim = 26
def __init__(self) -> None:
self.calls: dict[str, int] = {}
def embed(self, texts, *, kind="passage"):
import numpy as np
self.calls[kind] = self.calls.get(kind, 0) + 1
out = np.zeros((len(texts), 26), np.float32)
for i, t in enumerate(texts):
for c in t.lower():
if "a" <= c <= "z":
out[i, ord(c) - 97] += 1
return out / np.clip(np.linalg.norm(out, axis=1, keepdims=True), 1e-9, None)
# ── session-wide artifacts (built once, copied per profile) ─────────────────────────────────────────
class _Cache:
def __init__(self) -> None:
self.root = Path(tempfile.mkdtemp(prefix="insider-infra-"))
self.items: dict = {}
def get(self, key, build):
if key not in self.items:
self.items[key] = build()
return self.items[key]
_cache = _Cache()
NOW = dt.datetime.now(dt.UTC)
def _lexicon(on: bool) -> None:
from conftest import TEST_LEXICON_DIR
from app.integrations import analysis
analysis.configure(TEST_LEXICON_DIR if on else None)
def base_store():
"""The fixture's acts, superseded texts reconciled — the production importer's result."""
def build():
import search_eval as se
from app.integrations import dzu_md as dzu
from app.services import indexing
from app.services.indexstore import MemoryIndexStore
store = MemoryIndexStore()
for a in se.load_fixture():
store.upsert_act(dzu.ActRecord(
**{k: v for k, v in a.items() if k != "articles"},
articles=[dzu.Article(x["ord"], x["num"], x["text"]) for x in a["articles"]]))
indexing.reconcile_superseded(store)
return store
return _cache.get("store", build)
def graph_store():
"""`base_store` + the reference graph and its PageRank, as `GraphJob` builds them."""
def build():
from app.services import indexing
store = copy.deepcopy(base_store())
_states(store, ("dzu_md", "eli_inforce"), complete=True)
asyncio.run(indexing.GraphJob(store, on=True, schedule="0 5 * * *").run_once())
return store
return _cache.get("graph", build)
def _states(store, names, *, complete: bool, docs: int | None = None) -> None:
for name in names:
store.set_state(name, doc_count=docs if docs is not None else max(1, len(store.act_heads())),
completed_at=NOW if complete else None, synced_at=NOW)
def rebuild(ix, rows, marker=None) -> None:
"""`TextIndex.rebuild`, tolerating Windows: a scanner may hold the freshly written `.new`
files for a moment, and the swap's rename then fails — retry the rename it was doing."""
import gc
import time
try:
ix.rebuild(rows, marker)
return
except PermissionError:
fresh = ix.path.with_name(ix.path.name + ".new")
for _ in range(50):
gc.collect()
time.sleep(0.1)
try:
fresh.rename(ix.path)
return
except PermissionError:
continue
raise
def index_dir(lexicon: bool, fmt: int) -> Path:
"""The act index over `base_store`, built with (or without) the lexicon, in `fmt`."""
def build():
from app.services import textindex
from app.services.textindex import TextIndex
path = _cache.root / f"dzu_md-{int(lexicon)}-{fmt}"
saved = textindex.FORMAT
try:
_lexicon(lexicon and fmt >= 3) # format 2 = plstem only
textindex.FORMAT = fmt
ix = TextIndex(path)
ix._schema = textindex._schema(fmt)
rebuild(ix, base_store().iter_dzu_rows(), "infra")
ix._index = None
finally:
textindex.FORMAT = saved
_lexicon(True)
return path
return _cache.get(("index", lexicon, fmt), build)
def vector_dir(complete: bool) -> Path:
def build():
from app.services.vectorindex import VectorIndex, embed_pass
path = _cache.root / f"dzu_md-{int(complete)}.vec"
class StopAfterOne:
n = 0
def is_set(self):
self.n += 1
return self.n > 1
embed_pass(VectorIndex(path), base_store().iter_dzu_rows(), FakeEmbedder(), batch=64,
stop=None if complete else StopAfterOne())
return path
return _cache.get(("vec", complete), build)
EU_HTML = ("<html><body><p class='ti-art'>Artykuł 1</p><p class='sti-art'>Przedmiot i cele</p>"
"<p>Niniejsze rozporządzenie ustanawia przepisy o ochronie osób fizycznych w związku z "
"przetwarzaniem danych osobowych.</p><p class='ti-art'>Artykuł 2</p><p>Ochrona danych "
"osobowych przysługuje każdemu.</p></body></html>")
def _eu_records():
from app.integrations import cellar
from app.integrations.base import ACT
from app.integrations.cellar_builder.structure import split_html
parts = split_html(EU_HTML, ACT)[1]
return [cellar.EuRecord(celex=GDPR, kind=ACT, title="Rozporządzenie (UE) 2016/679 w sprawie "
"ochrony osób fizycznych w związku z przetwarzaniem danych osobowych",
type="R", date="2016-04-27", text_celex="02016R0679-20160504",
consolidation_date="2016-05-04", language="pl", fingerprint="f1",
parts=parts),
cellar.EuRecord(celex="32019L0790", kind=ACT, title="Dyrektywa (UE) 2019/790 w sprawie "
"prawa autorskiego na jednolitym rynku cyfrowym", type="L",
date="2019-04-17", language="pl", fingerprint="f2", parts=parts[:1])]
SAOS_ROW = dict(jid=7, case="I C 7/22", court="Sąd Rejonowy w Gdańsku",
text="<p>umowa kredytu frankowego, ochrona danych osobowych kredytobiorcy</p>")
# ── Postgres-backed state (INSIDER_RUN_INTEGRATION=1 + INSIDER_INFRA_DB=1) ───────────────────────
#: every dataset_sync row a profile writes
PG_STATES = ("dzu_md", "eli_inforce", "saos_dump", "cellar", "cellar_caselaw", "legal_graph",
"legal_rank")
def _pg_tables():
from app.models import (
DatasetSync,
DzuAct,
EuDoc,
LegalActRank,
LegalArticleRank,
LegalRef,
LegalRefCount,
SaosJudgment,
)
return (LegalActRank, LegalArticleRank, LegalRefCount, LegalRef, DzuAct, SaosJudgment, EuDoc,
DatasetSync)
def pg_cleanup() -> None:
"""Delete everything a profile wrote (the guard proved the tables were empty before)."""
from sqlalchemy import delete
from app.db import SessionLocal
*tables, sync = _pg_tables()
with SessionLocal() as db:
for t in tables:
db.execute(delete(t))
db.execute(delete(sync).where(sync.name.in_(PG_STATES)))
db.commit()
def pg_store(*, with_graph: bool):
"""The fixture in Postgres, through the runtime role — only on a database that holds no act
and none of the profile's dataset states (a throwaway one: CI's, or a dbprobe_*)."""
from sqlalchemy import func, select
from app.db import SessionLocal
from app.integrations import dzu_md as dzu
from app.services import indexing
from app.services.indexstore import PgIndexStore
*_, sync = _pg_tables()
from app.models import DzuAct
with SessionLocal() as db:
acts = db.scalar(select(func.count()).select_from(DzuAct))
states = db.scalar(select(func.count()).select_from(sync).where(sync.name.in_(PG_STATES)))
if acts or states:
raise RuntimeError(f"INSIDER_INFRA_DB refuses a database holding {acts} acts and {states} "
"dataset states: run it on a throwaway database only")
store = PgIndexStore(SessionLocal)
import search_eval as se
for a in se.load_fixture():
store.upsert_act(dzu.ActRecord(
**{k: v for k, v in a.items() if k != "articles"},
articles=[dzu.Article(x["ord"], x["num"], x["text"]) for x in a["articles"]]))
indexing.reconcile_superseded(store)
if with_graph:
_states(store, ("dzu_md", "eli_inforce"), complete=True)
asyncio.run(indexing.GraphJob(store, on=True, schedule="0 5 * * *").run_once())
return store
# ── one profile's world ─────────────────────────────────────────────────────────────────────────────
def settings(root: Path, p: Profile) -> SimpleNamespace:
base = dict(index_dir=root, insider_contact="ops@example.test",
insider_dzu_md_stale_hours=72, insider_eli_inforce_schedule="0 5 * * *",
insider_saos_index_stale_hours=96, insider_dzu_md_rate=1000.0,
insider_dzu_md_sync=True, insider_dzu_md_schedule="15 7 * * *",
insider_saos_dump_sync=True, insider_saos_dump_first_window="23:00-05:00",
insider_saos_dump_page_size=10, insider_saos_dump_pause_seconds=5,
insider_saos_dump_schedule="0 5 * * *", insider_eli_inforce_rate=1000.0,
insider_eli_inforce_sync=True, eli_inforce_types=["Ustawa"],
insider_cellar_sync=True, insider_cellar_caselaw=False,
insider_cellar_schedule="0 5 * * *", insider_cellar_full_schedule="0 5 * * 0",
insider_cellar_caselaw_schedule="0 5 * * *", insider_schedule_tz="Europe/Warsaw",
insider_index_rebuild_schedule="0 5 * * *", insider_cellar_rate=1000.0,
insider_cellar_stale_hours=96, insider_cellar_caselaw_from="2000-01-01",
insider_legal_graph=True, insider_legal_graph_schedule="0 5 * * *",
insider_legal_graph_prior=0.05, insider_legal_rank_act_prior=0.1,
insider_legal_rank_min_coverage=0.95, insider_legal_rank_damping=0.85,
# production's semantic defaults, with the vectors on the act index only
insider_semantic=True, semantic_datasets=["dzu_md"], insider_rrf_k=60,
insider_vector_weight=1.0, insider_rerank_top=20,
insider_embed_schedule="0 5 * * *", insider_embed_batch=32,
insider_embed_pause_seconds=0.2)
return SimpleNamespace(**base)
class World:
"""One profile, built: the `Legal` facade over fake upstreams + the local state, a TestClient
against the real app with that facade installed, and the spies the invariants read."""
def __init__(self, profile: Profile, root: Path, *, db: bool = False) -> None:
self.profile = profile
self.root = root
#: Postgres-backed state (`PgIndexStore`) instead of the in-memory store
self.db = db and profile.indexed
self.up = fake_upstream(profile.upstream)
self.embedder = FakeEmbedder()
self.legal = self._build()
# ── build ──
def _store(self):
p = self.profile
if self.db:
store = pg_store(with_graph=bool(p.graph or p.rank))
elif p.graph or p.rank:
store = copy.deepcopy(graph_store())
else:
store = copy.deepcopy(base_store())
if p.index_serves:
_states(store, ("dzu_md", "eli_inforce"), complete=True)
if p.rank is None and p.graph is not None: # a graph, no PageRank pass yet
store.replace_ranks({}, {})
store.set_state("legal_rank", completed_at=None, progress={})
if p.graph == "partial": # a run started after the finished build, unfinished
st = store.sync_state("legal_graph")
store.set_state("legal_graph", attempted_at=st["synced_at"] + dt.timedelta(minutes=5))
sources = sorted({h["eli"] for h in store.graph_heads()})
store.drop_refs(sources[::2]) # and it got half-way
store.recount()
if p.rank == "stale" and p.graph == "complete": # the graph moved on since the pass
st = store.sync_state("legal_graph")
later = st["synced_at"] + dt.timedelta(minutes=5)
store.set_state("legal_graph", synced_at=later, attempted_at=later)
if p.index_serves:
from fakes import saos_item
from app.integrations import saos_dump
from app.services.htmltext import html_to_text
store.upsert_judgments([saos_dump.build_record(saos_item(**SAOS_ROW), html_to_text)])
_states(store, ("saos_dump",), complete=True, docs=1)
if p.cellar != "empty":
for rec in _eu_records():
store.upsert_eu(rec)
_states(store, ("cellar",), complete=p.cellar == "complete", docs=2)
return store
def _build(self):
from fakes import _no_sleep
from fakes import settings as live_settings
from app.integrations.registry import build_registry
from app.services import indexing, semantic
from app.services.cache import MemoryStore, SourceCache
from app.services.cursor import CursorCodec
from app.services.doctext import MemoryTextStore
from app.services.legal import Legal
from app.services.textindex import TextIndex
p = self.profile
_lexicon(p.lexicon)
budget = 0.5 if p.upstream == "timeout" else 2.0
reg = build_registry(live_settings(), transport=self.up.transport(), sleep=_no_sleep)
ix = None
if p.indexed:
self.store = self._store()
if p.index_serves:
shutil.copytree(index_dir(p.lexicon, int(p.index)), self.root / "dzu_md")
from app.integrations import saos_dump
rebuild(TextIndex(self.root / saos_dump.DATASET), self.store.iter_saos_rows())
if p.cellar != "empty":
from app.integrations import cellar
rebuild(TextIndex(self.root / cellar.INDEX_DIR, langs=("pl", "en")),
self.store.iter_eu_rows())
if p.vectors:
shutil.copytree(vector_dir(p.vectors == "complete"), self.root / "dzu_md.vec")
semantic.set_models(semantic.Models(self.embedder, None))
ix = indexing.build_indexing(settings(self.root, p), self.store,
transport=self.up.transport(), clock=lambda: NOW,
sleep=_no_sleep)
else:
self.store = None
return Legal(reg, SourceCache(MemoryStore()), MemoryTextStore(), CursorCodec("infra"),
budget=budget, slow_budget=budget, indexing=ix)
def activate(self) -> None:
"""Put the process-wide switches (the analysis registry, the models) where this profile
has them — another profile's world may have moved them."""
from app.services import semantic
_lexicon(self.profile.lexicon)
semantic.set_models(semantic.Models(self.embedder, None) if self.profile.indexed else None)
# ── use ──
def client(self):
"""A TestClient over the real app, this world's facade installed and a stub user (the
real `get_current_user` is the DB suite's). No lifespan: no importer loop starts."""
from fastapi.testclient import TestClient
from app.deps import get_current_user
from app.main import app
from app.services import moderation, runtime, semantic
runtime.set_legal(self.legal)
# the route reads the administrator's AI switches and the moderator tier from Postgres on
# every search; DB-free, each read waits out a connect timeout (~2 s). Their answer with
# no database is "all off" / "not a moderator" — the same, at once.
self._saved = (semantic.ai_flags, moderation.is_moderator)
if INFRA_DB:
self._saved = None
else:
self._stub_db_reads(semantic, moderation)
app.dependency_overrides[get_current_user] = lambda: SimpleNamespace(
id=uuid.uuid4(), is_admin=False)
return self._open(TestClient(app))
@staticmethod
def _stub_db_reads(semantic, moderation) -> None:
semantic.ai_flags = lambda *a, **k: dict.fromkeys(
("ai_query_rewrite", "ai_answers", "ai_external_allowed"), False)
moderation.is_moderator = lambda *a, **k: False
def _open(self, client):
# one event-loop thread for every request of this world (what `with TestClient` gives,
# minus the lifespan): a portal per request costs ~0.2 s on Windows, 20× the search
import contextlib
import anyio.from_thread
self._stack = contextlib.ExitStack()
client.portal = self._stack.enter_context(
anyio.from_thread.start_blocking_portal(**client.async_backend))
return client
def close(self) -> None:
from app.deps import get_current_user
from app.main import app
from app.services import moderation, runtime, semantic
if getattr(self, "_saved", None):
semantic.ai_flags, moderation.is_moderator = self._saved
self._saved = None
if getattr(self, "_stack", None) is not None:
self._stack.close()
self._stack = None
app.dependency_overrides.pop(get_current_user, None)
runtime.set_legal(None)
semantic.set_models(None)
_lexicon(True)
if self.db:
pg_cleanup()
try:
asyncio.run(self.legal.registry.aclose())
except Exception: # noqa: BLE001
pass
def search(self, client, q: str, **params) -> httpx.Response:
return client.get("/api/v1/search", params={"q": q, **params})
# ── what the profile promises ──
def expected_index_notices(self, kind: str, jurisdiction: str) -> set[str]:
"""The `index_*` notices a search must carry here: one per local source that applies to
the query and truly cannot serve it."""
p = self.profile
if not p.indexed:
return set()
out = set()
pl = jurisdiction in ("all", "pl")
eu = jurisdiction in ("all", "eu")
if pl and kind in ("all", "act") and not p.index_serves:
out.add("index_updating:dzu_md")
if pl and kind in ("all", "judgment") and not p.index_serves:
out.add("index_updating:saos_index")
if eu and p.cellar != "complete":
out.add("index_updating:cellar")
return out
def build_world(name: str, tmp: Path, *, db: bool = False) -> World:
return World(PROFILES[name], tmp, db=db)
+70 -2
View File
@@ -155,13 +155,16 @@ def semantic(adapter, tmp: Path, reranker: bool = True):
return adapter
def table(adapter, queries=None) -> str:
def table(adapter, queries=None, *, topper=None, recall: bool = True) -> str:
topper = topper or top
lines = ["| query | #1 | #2 | #3 | ok |", "|---|---|---|---|---|"]
for q, want, depth, arts in queries or REGRESSION:
rows = top(adapter, q)
rows = topper(adapter, q)
cells = [f"{_short(r['title'])} ({r['eli']}) art. {', '.join(str(a) for a in r['articles'][:3])}"
for r in rows] + [""] * (3 - len(rows))
lines.append(f"| {q} | " + " | ".join(cells) + f" | {'yes' if passed(rows, want, depth, arts) else 'NO'} |")
if not recall:
return "\n".join(lines)
lines += ["", "| query (recall) | must be found (top 10) | found | ok |", "|---|---|---|---|"]
for q, want in RECALL:
got = [r["eli"] for r in top(adapter, q, 10)]
@@ -170,6 +173,49 @@ def table(adapter, queries=None) -> str:
return "\n".join(lines)
# ── per infra profile (`tests/infra.py`) ─────────────────────────────────────────────────────────
#: the regression queries a box with NO local index can still answer: each names an act by its
#: title, which is all ELI searches (no full text, no articles). The rest need the index.
NAMED = ("kodeks cywilny", "Kodeks cywilny", "k.c.", "KC", "kodeks pracy", "Kodeks pracy", "k.p.",
"kodeksu pracy", "Kodeks wykroczeń", "Prawo o ruchu drogowym")
def regression_for(profile) -> list[tuple[str, str, int, tuple[str, ...]]]:
"""The regression set a profile must pass: all of it where the act index serves, the
named-act queries where only the live sources can answer, nothing where nothing can."""
if profile.index_serves:
return list(REGRESSION)
if profile.upstream != "ok":
return []
return [r for r in REGRESSION if r[0] in NAMED]
def top_legal(legal, q: str, n: int = 3) -> list[dict]:
"""The top acts of a REAL search (`Legal.search`: the index beside ELI, the live ranking,
dedup) — what a person sees, whatever answered."""
import asyncio
from app.integrations.base import Query
out = asyncio.run(legal.search(Query(q=q, kind="act", jurisdiction="pl"), limit=10))
return [{"eli": (a.get("extra") or {}).get("eli"), "title": a["title"],
"articles": [h.get("num") for h in (a.get("extra") or {}).get("articles") or []]}
for a in out["acts"][:n]]
def profile_table(name: str, tmp: Path) -> tuple[str, list[str]]:
"""One profile's top-3 table over its regression set, and the queries it failed."""
import infra
world = infra.build_world(name, tmp)
try:
world.activate()
queries = regression_for(world.profile)
failed = [q for q, want, depth, arts in queries
if not passed(top_legal(world.legal, q), want, depth, arts)]
return table(world.legal, queries, topper=top_legal, recall=False), failed
finally:
world.close()
def recalled(adapter, q: str, want: tuple[str, ...]) -> bool:
got = {r["eli"] for r in top(adapter, q, 10)}
return all(w in got for w in want)
@@ -199,6 +245,28 @@ if __name__ == "__main__":
import conftest # noqa: F401
elif not os.environ.get("INSIDER_LEXICON_DIR"):
sys.exit("--full-lexicon: set INSIDER_LEXICON_DIR to a built lexicon directory")
profiles = [a.split("=", 1)[1] for a in sys.argv if a.startswith("--profile=")]
if "--profile" in sys.argv:
profiles.append(sys.argv[sys.argv.index("--profile") + 1])
if profiles: # one table per infra profile (tests/infra.py)
import logging
import infra
logging.disable(logging.INFO)
names = infra.selected(",".join(profiles))
bad, summary = {}, []
with tempfile.TemporaryDirectory() as d:
for name in names:
tab, failed = profile_table(name, Path(d) / name)
n = len(regression_for(infra.PROFILES[name]))
summary.append(f"| {name} | {infra.PROFILES[name].describe()} | {n - len(failed)}/{n} |")
print(f"## {name} — {infra.PROFILES[name].describe()}\n\n{tab}\n")
if failed:
bad[name] = failed
print("\n".join(["| profile | state | regression |", "|---|---|---|", *summary, ""]))
for name, failed in bad.items():
print(f"{name}: FAILED {failed}")
sys.exit(1 if any(n in infra.CORE for n in bad) else 0)
if "--no-lexicon" in sys.argv: # plstem only: the table before lemmas
from app.integrations import analysis
analysis.configure(None)
+27 -2
View File
@@ -223,6 +223,18 @@ def test_pagerank_pass_on_postgres_and_the_guard(store):
art = store.article_ranks([(a, 4), (a, 1), (a, 99)])
assert art[(a, 4)] > art[(a, 1)] and (a, 99) not in art
now = dt.datetime.now(dt.UTC)
# the guard reads the REAL state names: put back what was there (nothing, on a fresh database —
# a leftover row made every later run on this database see a half-built graph)
before = {n: store.sync_state(n) for n in ("legal_graph", rank.DATASET)}
try:
_the_guard(store, rank, info, now)
finally:
_restore_states(store, before)
store.replace_ranks({}, {})
store.drop_refs([a, b])
def _the_guard(store, rank, info, now):
store.set_state("legal_graph", synced_at=now, attempted_at=now, running=False)
store.set_state(rank.DATASET, completed_at=now, synced_at=now,
progress=info | {"graph_synced_at": now.isoformat()})
@@ -232,11 +244,24 @@ def test_pagerank_pass_on_postgres_and_the_guard(store):
store.set_state("legal_graph", attempted_at=now + dt.timedelta(seconds=5), running=True)
store._states.clear()
assert rank.RankPrior(store).mode() == "naive"
store.replace_ranks({}, {})
store.drop_refs([a, b])
store.set_state("legal_graph", running=False)
def _restore_states(store, before: dict) -> None:
from sqlalchemy import delete
from app.db import SessionLocal
from app.models import DatasetSync
for name, st in before.items():
if st is None:
with SessionLocal() as db:
db.execute(delete(DatasetSync).where(DatasetSync.name == name))
db.commit()
else:
store.set_state(name, **{k: v for k, v in st.items() if k != "name"})
store._states.clear()
# ── no transaction held across slow work (the deploy of 0008 waited 24 min on two) ─────────────
_OPEN_TXN = ("SELECT pid, state, left(query, 80) FROM pg_stat_activity "
"WHERE datname = current_database() AND usename = current_user "
+206
View File
@@ -0,0 +1,206 @@
"""The invariants every search keeps WHATEVER local infrastructure the box has (`tests/infra.py`).
Each test runs once per profile — bare LIVE, a fresh INDEXED install, an index alone, the graph
without its rank, everything, and the half-built and outage states in between — through the real
REST route, over fake upstreams. What may differ between profiles is WHO answers (and the notices
saying so); what may not differ is the shape, the answer to a named code, the honesty of
`rank_prior`, and that a request never builds, downloads or loads a component that is not there.
Run one profile: `pytest tests/test_infra_matrix.py --infra=bare` (or INSIDER_INFRA=bare,full).
"""
from __future__ import annotations
import gc
import tracemalloc
import pytest
from infra import GDPR, KC_TJ
from app.services import indexing, textindex, vectorindex
pytest.importorskip("tantivy")
pytest.importorskip("numpy")
#: (query, extra params) — acts, judgments and EU, the named codes, a plain phrase
SEARCHES = [
("Kodeks cywilny", {}),
("k.c.", {"kind": "act"}),
("umowa o pracę", {"kind": "act", "jurisdiction": "pl"}),
("kredyt", {"kind": "judgment"}),
("ochrona danych osobowych", {"kind": "act", "jurisdiction": "eu"}),
("ochrona danych osobowych", {"jurisdiction": "eu"}),
]
IDS = [f"{q}|{p.get('kind', 'all')}|{p.get('jurisdiction', 'all')}" for q, p in SEARCHES]
TOP_KEYS = {"acts", "judgments", "sources", "notices", "pending", "next_cursor", "query",
"rank_prior", "filter_scope"}
ITEM_KEYS = {"id", "source", "kind", "title", "official_url", "attribution", "snippet", "extra"}
SOURCE_KEYS = {"name", "status"}
LIVE = {"eli", "saos", "eurlex"}
#: a cheap ceiling for ONE search's Python allocations (tracemalloc peak): the fixture-sized box
#: allocates well under 2 MB; a request that loads the vectors or an index wholesale does not
MEMORY_CEILING = 8 * 1024 * 1024
@pytest.fixture
def api(infra):
c = getattr(infra, "_client", None)
if c is None:
c = infra._client = infra.client()
return c
def _search(infra, api, q, params):
r = infra.search(api, q, **params)
assert r.status_code == 200, r.text
return r.json()
# ── shape ───────────────────────────────────────────────────────────────────────────────────────────
@pytest.mark.parametrize(("q", "params"), SEARCHES, ids=IDS)
def test_search_answers_200_with_one_shape(infra, api, q, params):
body = _search(infra, api, q, params)
assert set(body) == TOP_KEYS, sorted(body)
assert body["rank_prior"] in ("graph", "naive")
for s in body["sources"]:
assert SOURCE_KEYS <= set(s), s
for item in body["acts"] + body["judgments"]:
assert ITEM_KEYS <= set(item), sorted(item)
assert item["official_url"].startswith("https://") and len(item["snippet"]) <= 300
for n in body["notices"]:
assert {"code", "message", "message_en"} <= set(n), n
# ── the named code ──────────────────────────────────────────────────────────────────────────────────
@pytest.mark.parametrize("q", ["Kodeks cywilny", "k.c."])
def test_a_named_code_puts_its_consolidated_text_first(infra, api, q):
"""The Civil Code's current t.j. first — from the index when it serves, from ELI otherwise —
and when nothing can serve, no acts rather than wrong ones."""
body = _search(infra, api, q, {"kind": "act", "jurisdiction": "pl"})
p = infra.profile
if p.index_serves:
want = f"dzu_md:{KC_TJ}"
elif p.upstream == "ok":
want = f"eli:{KC_TJ}"
else:
assert body["acts"] == [], body["acts"]
return
assert body["acts"], body["sources"]
assert body["acts"][0]["id"] == want, [a["id"] for a in body["acts"][:5]]
# ── rank_prior ──────────────────────────────────────────────────────────────────────────────────────
def test_rank_prior_is_graph_only_when_the_rank_is_complete(infra, api):
body = _search(infra, api, "Kodeks cywilny", {})
assert body["rank_prior"] == ("graph" if infra.profile.graph_prior else "naive")
# ── vectors ─────────────────────────────────────────────────────────────────────────────────────────
def test_the_vector_side_is_used_only_when_the_vectors_are_complete(infra, api, monkeypatch):
searched = []
real = vectorindex.VectorIndex.search
monkeypatch.setattr(vectorindex.VectorIndex, "search",
lambda self, *a, **k: searched.append(1) or real(self, *a, **k))
infra.embedder.calls.clear()
_search(infra, api, "rozwiązanie umowy o pracę bez wypowiedzenia",
{"kind": "act", "jurisdiction": "pl"})
used = bool(searched) or bool(infra.embedder.calls.get("query"))
assert used is infra.profile.vectors_used, (infra.embedder.calls, len(searched))
# ── notices ─────────────────────────────────────────────────────────────────────────────────────────
@pytest.mark.parametrize(("q", "params"), SEARCHES, ids=IDS)
def test_notices_appear_exactly_when_a_source_cannot_serve(infra, api, q, params):
body = _search(infra, api, q, params)
got = {n["code"] for n in body["notices"] if n["code"].startswith("index_")}
want = infra.expected_index_notices(params.get("kind", "all"), params.get("jurisdiction", "all"))
assert got == want, body["sources"]
# a live source that was asked answers "ok" exactly when its upstream is up
asked = [s for s in body["sources"] if s["name"] in LIVE and s["status"] not in ("skipped",)]
for s in asked:
if infra.profile.upstream == "ok":
assert s["status"] in ("ok", "pending"), s
else:
assert s["status"] not in ("ok",), s
# ── nothing touches a missing component ─────────────────────────────────────────────────────────────
def test_a_request_never_builds_downloads_or_loads_what_is_missing(infra, api, monkeypatch):
touched: list[str] = []
def refuse(what):
def _f(*a, **k):
touched.append(what)
raise AssertionError(f"{what} in the request path")
return _f
monkeypatch.setattr(textindex.TextIndex, "rebuild", refuse("TextIndex.rebuild"))
monkeypatch.setattr(textindex.TextIndex, "update", refuse("TextIndex.update"))
monkeypatch.setattr(indexing, "ensure_index", refuse("ensure_index"))
monkeypatch.setattr(vectorindex, "embed_pass", refuse("embed_pass"))
loads = []
real_refresh = vectorindex.VectorIndex._refresh
monkeypatch.setattr(vectorindex.VectorIndex, "_refresh",
lambda self: loads.append(1) or real_refresh(self))
infra.embedder.calls.clear()
for q, params in SEARCHES:
_search(infra, api, q, params)
assert touched == []
from infra import dataset_calls
assert dataset_calls(infra.up) == [] # no dataset host, no dump, no model hub
p = infra.profile
if p.vectors != "complete":
assert loads == [], "the vectors were loaded with no finished pass"
assert not infra.embedder.calls, "the embedder ran with no usable vectors"
# ── every CELEX returned opens ──────────────────────────────────────────────────────────────────────
def test_every_celex_returned_opens(infra, api):
seen = set()
for q, params in [("ochrona danych osobowych", {"jurisdiction": "eu"}),
("ochrona danych osobowych", {"kind": "act", "jurisdiction": "eu"})]:
body = _search(infra, api, q, params)
for item in body["acts"] + body["judgments"]:
if not item["id"].startswith("eurlex:"):
continue
celex = item["id"].split(":", 1)[1]
if celex in seen:
continue
seen.add(celex)
path = (f"/api/v1/acts/eu/{celex}" if item["kind"] == "act"
else f"/api/v1/judgments/eurlex/{celex}")
r = api.get(path)
assert r.status_code == 200, (path, r.status_code, r.text[:300])
assert r.json()["id"] == item["id"]
p = infra.profile
if p.cellar == "complete" or p.upstream == "ok":
assert GDPR in seen # somebody could serve it
# ── charset ─────────────────────────────────────────────────────────────────────────────────────────
@pytest.mark.parametrize("path", [
"/api/v1/search?q=Kodeks%20cywilny",
"/api/v1/search?q=ochrona&jurisdiction=eu",
"/api/v1/sources",
"/api/v1/sources/datasets",
"/api/v1/search?cursor=forged.x", # a Problem Details error
])
def test_json_responses_carry_charset_utf8(infra, api, path):
r = api.get(path)
ct = r.headers["content-type"].lower().replace(" ", "")
assert ct.startswith(("application/json", "application/problem+json")), ct
assert "charset=utf-8" in ct, ct
r.json()
# ── memory ──────────────────────────────────────────────────────────────────────────────────────────
@pytest.mark.infra("bare", "full")
def test_one_request_stays_under_a_memory_ceiling(infra, api):
q, params = "rozwiązanie umowy o pracę bez wypowiedzenia", {}
_search(infra, api, q, params) # warm: imports, caches, the index open
gc.collect()
tracemalloc.start()
try:
_search(infra, api, q + " ", params) # not a cached page
_, peak = tracemalloc.get_traced_memory()
finally:
tracemalloc.stop()
assert peak < MEMORY_CEILING, f"{peak / 1e6:.1f} MB"
+12
View File
@@ -56,6 +56,18 @@ def test_regression_query_with_no_graph(naive_adapter, q, want, depth, arts):
assert se.passed(rows, want, depth, arts), se.table(naive_adapter)
@pytest.mark.infra("bare", "full")
def test_regression_set_per_infra_profile(infra):
"""The same regression set through a REAL search (`Legal.search`) with nothing local (the
named acts, from ELI's titles) and with everything local (all of it, vectors fused in) —
`python tests/search_eval.py --profile=all` prints every profile's table."""
queries = se.regression_for(infra.profile)
assert queries
failed = [q for q, want, depth, arts in queries
if not se.passed(se.top_legal(infra.legal, q), want, depth, arts)]
assert not failed, se.table(infra.legal, queries, topper=se.top_legal, recall=False)
def test_the_graph_state_is_complete(adapter):
assert adapter.ranker.mode() == "graph"