diff --git a/.gitattributes b/.gitattributes index 20e7470..daa0d58 100644 --- a/.gitattributes +++ b/.gitattributes @@ -8,3 +8,4 @@ *.md text eol=lf *.yml text eol=lf Dockerfile text eol=lf +*.gz binary diff --git a/CLAUDE.md b/CLAUDE.md index 8299b24..d4ba6db 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -173,7 +173,13 @@ frontend/ui/v1/ the family's shared shell (a copy of Atrium's; don't edit loca query (`covers()`). Every mirror result carries the disclaimer "nieoficjalna konwersja; tekstem wiążącym jest PDF w Dzienniku Ustaw", `source_pdf`, `eli_url`; ELI stays authoritative for status and the current t.j. Old consolidated texts are flagged `superseded` and never searched — don't - index them back. Articles are keyed by POSITION (numbers repeat). tantivy is pinned exactly in + index them back. **One act = one answer:** `indexing.reconcile_superseded` (after every import of + either act dataset and before an index rebuild) groups every text by its NAME (`dzu_md.act_key`: + a t.j.'s notice, the act as published and ELI's title of it meet) and keeps only the newest by + Dz.U. year/position searchable — the dataset holds every t.j. since 2012, and before this a search + listed one act three times. Amending acts and non-t.j. notices are never grouped. The adapter and + `federation.dedup` hold the same line (a live ELI act whose name an indexed answer already + claimed is dropped). Articles are keyed by POSITION (numbers repeat). tantivy is pinned exactly in `requirements.txt` (MIT) and import-guarded. - **EU law in INDEXED mode comes from CELLAR, anonymously** (`cellar` / `cellar_caselaw`, owner- approved 2026-10-21; it replaced the EUR-Lex dump seam, which needed an EU Login account). The @@ -228,6 +234,23 @@ frontend/ui/v1/ the family's shared shell (a copy of Atrium's; don't edit loca alternations (sygnaliści/sygnalista, studenci, autorzy, prawnicy, biolodzy, sędzia/sędziów) are deliberately narrow — `tests/test_plstem.py` pins the look-alikes that must not merge (części, granicy, młodzy, narzędzi, lekarzy, żołnierzy). +- **`textindex.FORMAT` guards what a document holds** the way `plstem.VERSION` guards the stems: + bump it with any change to the fields or their analysis (an index of another format is not + `ready()`, and `ensure_index` rebuilds it from Postgres). Format 2 (2026-10-21): the title is the + act's NAME (`dzu_md.search_title`, no notice boilerplate), plus `head` (a carried chapter heading) + and `lead` (the first sentence) fields, the body keeps function words (positions for the exact + phrase; a query never MATCHES on them), and a stored `prior` (`dzu_md.act_prior`: codes up; + amending acts, notices and acts no longer in force down). Ranking = BM25 title > head > lead > + body, + phrase/pair proximity (slop 2) + the exact phrase as typed, × prior × breadth. The + regression set and the offline evaluation are `tests/search_eval.py` + `tests/test_search_quality.py` + over `tests/fixtures/search_eval.json.gz` (a slice of real acts; `scripts/build_search_fixture.py` + rebuilds it from hand-downloaded files) — run `python tests/search_eval.py` for the top-3 table + after any ranking change. `plstem.STOPWORDS` are true function words only; `eurlex.FTS_COMMON` + ("umowa", "prawo"…) is CELLAR SPARQL's list and never the local index's. +- **An interrupted import resumes in minutes, not an interval later** (`indexing.unfinished`, + `RESUME_AFTER`): the box's first `eli_inforce` pass stopped at 57 of 2 411 acts on a deploy and + `due()` waited 24 h. `eli_inforce` also waits for `dzu_md`'s FIRST full pass (`after=`) and is due + the tick it ends — a text the mirror holds is never fetched from ELI. - **Filters are scoped by kind** (`base.JUDGMENT_FILTERS` / `ACT_FILTERS`): a court never drops acts, a publisher / in-force never drops judgments; `filter_scope` reports where each applied, and a filter outside a source's kind is not "unsupported" there. diff --git a/README.md b/README.md index 8561cb0..af1fbb0 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,7 @@ act's title weighted ×3 and the query words side by side ×2. | Dataset | What | How | |---|---|---| | `dzu_md` | [`PolskiAgentW/dziennik-ustaw-md`](https://github.com/PolskiAgentW/dziennik-ustaw-md) (CC0 data, `eli2md` MIT): Dz.U. from 2025, PDF-only older acts, and **~4,900 consolidated texts (t.j.) 2012–26** | every `INSIDER_DZU_MD_SYNC_INTERVAL_HOURS` (6): one ~1 KB request for the branch head; a new commit fetches `index.csv` and only the acts whose PDF checksum / converter / conversion time changed, pinned to that commit, ≤ `INSIDER_DZU_MD_RATE` req/s, one at a time | -| `eli_inforce` | every act **in force** (`inForce=1`, types `INSIDER_ELI_INFORCE_TYPES`, base acts only) with its **current** consolidated text | daily: ELI's listing, then per act whose `changeDate` moved one metadata request; the text (`text.html`, else the PDF's text layer) only when no dataset has it yet. Older t.j. are flagged **superseded** — kept, never searched | +| `eli_inforce` | every act **in force** (`inForce=1`, types `INSIDER_ELI_INFORCE_TYPES`, base acts only) with its **current** consolidated text | daily: ELI's listing, then per act whose `changeDate` moved one metadata request; the text (`text.html`, else the PDF's text layer) only when no dataset has it yet. Older t.j. are flagged **superseded** — kept, never searched (for every act held in several texts, whichever dataset holds them). Waits for `dzu_md`'s first full pass, then starts; an interrupted pass resumes ~10 min later | | `saos_dump` | SAOS's **dump API** (`/api/dump/judgments`) — metadata + sanitised text in sections | only in the off-peak UTC window `INSIDER_SAOS_DUMP_WINDOW` (23:00–05:00), one request in flight, `INSIDER_SAOS_DUMP_PAUSE_SECONDS` between pages, resumable from the stored cursor; the next pass asks `sinceModificationDate` = when the previous one started | | `cellar` | EU **regulations, directives and decisions in force** (CELEX sector 3, `resource_legal_in-force`), each with the text of its **newest consolidated version** (`0…-YYYYMMDD`), Polish — English when there is no Polish text, the language recorded | the Publications Office's anonymous CELLAR (no EU Login account — it replaced the planned EUR-Lex dump): SPARQL keyset-paged listing, the 303 → `resource/cellar` text fetch, one request in flight at `INSIDER_CELLAR_RATE` (≤ 2/s, every hop counted). A **full** pass weekly (acts it no longer lists are marked out of force — kept, never searched), a **delta** daily (works whose CELLAR `lastModificationDate`, or a consolidated version's, moved since the last pass). Cursor saved after every page | | `cellar_caselaw` | CJEU judgments (CJ, TJ) dated from `INSIDER_CELLAR_CASELAW_FROM` — **off by default** (`INSIDER_CELLAR_CASELAW`) | the same channel and cadence; cut into ~12k-character pieces | diff --git a/backend/app/integrations/dzu_md.py b/backend/app/integrations/dzu_md.py index 0d98056..a5d3f1c 100644 --- a/backend/app/integrations/dzu_md.py +++ b/backend/app/integrations/dzu_md.py @@ -28,6 +28,7 @@ import io import json import re from dataclasses import dataclass, field +from functools import lru_cache from urllib.parse import quote from . import plstem @@ -250,10 +251,114 @@ def art_label(num: str | None) -> str | None: def act_rows(act: dict, articles: list[dict]) -> list[dict]: - """An act's articles as index parts (`TextIndex` rows).""" - return [{"group": act["eli"], "ord": a["ord"], "title": act.get("title") or "", - "text": a["text"], "date": act.get("announcement_date") or act.get("promulgation"), - "tags": ["sup"] if act.get("superseded") else []} for a in articles] + """An act's articles as index parts (`TextIndex` rows): the act's NAME as the title (not the + notice's boilerplate), its static `prior`, and `sup` on a superseded text (never searched).""" + title, prior = search_title(act.get("title") or ""), act_prior(act) + date = act.get("announcement_date") or act.get("promulgation") + tags = ["sup"] if act.get("superseded") else [] + return [{"group": act["eli"], "ord": a["ord"], "title": title, "text": a["text"], + "date": date, "tags": tags, "prior": prior} for a in articles] + + +# ── one act, however many texts of it: identity, supersession, priors ────────────────────────────── +#: "Ustawa z dnia 26 czerwca 1974 r. – Kodeks pracy" → the date phrase goes, the form stays +_DATED = re.compile(r"^(\S+(?:\s+\S+){0,6}?)\s+z\s+dnia\s+\d{1,2}\s+\S+\s+\d{4}\s*r\.\s*", re.I) +#: "Ustawa o zmianie…", "Rozporządzenie Ministra X zmieniające…" — but not "Ustawa o ochronie praw +#: lokatorów… i o zmianie Kodeksu cywilnego": the words before the verb may not open the subject +_AMENDING = re.compile(r"^\S+(?:\s+(?!o\b|w\b)\S+){0,6}?\s+(?:o\s+zmianie|o\s+zmianach|" + r"zmieniając[aey]|uchylając[aey])\b", re.I) +_REPEALED = ("uchylony", "uznany za uchylony", "nieobowiązujący", "wygaśnięcie aktu") +_ONE_OFF = ("akt jednorazowy", "akt indywidualny") +_NOTICE_TYPES = ("obwieszczenie", "komunikat", "oświadczenie rządowe", "informacja", "ogłoszenie", + "sprostowanie", "postanowienie", "uchwała") +#: the static weights `TextIndex` multiplies a group's score by (`act_prior`) +PRIOR_CODE = 1.3 +PRIOR_COVERED = 0.85 +PRIOR_REPEALED = 0.6 +PRIOR_NOTICE = 0.6 +PRIOR_AMENDING = 0.5 + + +@lru_cache(maxsize=16384) +def act_name(title: str) -> str: + """The act a text IS: a consolidated text's notice ("Obwieszczenie … jednolitego tekstu ustawy + – Kodeks pracy"), the act as published ("Ustawa z dnia 26 czerwca 1974 r. – Kodeks pracy") and + ELI's title of it all name "Ustawa – Kodeks pracy".""" + name = display_title(title or "") + if name.endswith(" (tekst jednolity)"): + name = name[: -len(" (tekst jednolity)")] + name = _DATED.sub(lambda m: m.group(1) + " ", name, count=1) + return re.sub(r"\s+", " ", name).strip() + + +def act_key(title: str) -> str: + """`act_name` folded to its words — the key under which every text of ONE act meets.""" + return " ".join(plstem.fold(w) for w in plstem.words(act_name(title))) + + +def search_title(title: str) -> str: + """What the index's title field holds: the act's name, without the notice's boilerplate + ("Obwieszczenie Marszałka Sejmu Rzeczypospolitej Polskiej z dnia … w sprawie ogłoszenia…"), + which diluted every consolidated text's title and matched no question anyone asks.""" + return act_name(title) + + +def is_consolidated(title: str) -> bool: + return _TJ.search(title or "") is not None + + +def is_amending(title: str) -> bool: + return _AMENDING.match(act_name(title)) is not None + + +def is_code(title: str) -> bool: + return re.match(r"^\S+\s*[-–—]?\s*Kodeks\b", act_name(title)) is not None + + +def act_prior(act: dict) -> float: + """A static weight for ranking: a code ("Kodeks …") a little up; an amending act, a one-off + act, a notice that is not a consolidated text and an act no longer in force down — a question + about the law wants the base act's current text.""" + title = act.get("title") or "" + status = (act.get("status") or "").strip().lower() + kind = (act.get("type") or "").strip().lower() + if is_amending(title) or status in _ONE_OFF: + return PRIOR_AMENDING + if kind in _NOTICE_TYPES and not is_consolidated(title): + return PRIOR_NOTICE + if status in _REPEALED: + return PRIOR_REPEALED + prior = PRIOR_CODE if is_code(title) else 1.0 + if status.startswith("akt objęty tekstem jednolitym"): + prior *= PRIOR_COVERED + return prior + + +def supersede_plan(acts: list[dict]) -> tuple[list[str], list[str]]: + """(superseded, current) ELIs: of every act held in more than one text — consolidated texts of + different years, the act as published and a later t.j. of it, the dataset's t.j. and the one + `eli_inforce` filled in — only the NEWEST (by Dz.U. year, position) is searched. Amending acts + and notices that are not consolidated texts are never grouped (their names are their own). Two + acts with one name (a law re-enacted under the same title) keep the newer, the one in force.""" + groups: dict[str, list[dict]] = {} + for a in acts: + title = a.get("title") or "" + if is_amending(title): + continue + if (a.get("type") or "").strip().lower() in _NOTICE_TYPES and not is_consolidated(title): + continue + key = act_key(title) + if key: + groups.setdefault(key, []).append(a) + superseded: list[str] = [] + current: list[str] = [] + for members in groups.values(): + if len(members) < 2: + continue + members.sort(key=lambda a: (int(a.get("year") or 0), int(a.get("pos") or 0)), reverse=True) + current.append(members[0]["eli"]) + superseded += [m["eli"] for m in members[1:]] + return superseded, current # ── links and the document every answer carries ───────────────────────────────────────────────────── @@ -433,10 +538,17 @@ class DzuMdAdapter(LocalAdapter): acts = self.store.get_acts([g["group"] for g in groups]) stems = plstem.query_stems(query.q) docs = [] + names: set[str] = set() for g in groups: act = acts.get(g["group"]) - if act is None: - continue # the index is a step ahead of a deletion + if act is None or act.get("superseded"): + continue # the index is a step ahead of a deletion / a flag + # one answer per act: `reconcile_superseded` keeps one text of it searchable, and this + # holds even while a flag is still on its way into the index + name = act_key(act.get("title") or "") + if name in names: + continue + names.add(name) arts = self.store.get_articles(g["group"], [h["ord"] for h in g["hits"]]) hits = [] for h in g["hits"]: diff --git a/backend/app/integrations/plstem.py b/backend/app/integrations/plstem.py index 7f31ab2..d0ee947 100644 --- a/backend/app/integrations/plstem.py +++ b/backend/app/integrations/plstem.py @@ -119,9 +119,10 @@ def stems(text: str, *, keep_stopwords: bool = False) -> list[str]: if keep_stopwords or w.lower() not in STOPWORDS] -def analyse(text: str) -> str: - """`text` as the space-separated stems the full-text index stores.""" - return " ".join(stems(text)) +def analyse(text: str, *, keep_stopwords: bool = False) -> str: + """`text` as the space-separated stems the full-text index stores (function words kept where + an exact-phrase check needs their positions — the body; a query never MATCHES on them).""" + return " ".join(stems(text, keep_stopwords=keep_stopwords)) _MOBILE_E = re.compile(r"^(.*[^aeiouyąęó])e([^aeiouyąęó])$") diff --git a/backend/app/services/federation.py b/backend/app/services/federation.py index ee4a66d..e0fad26 100644 --- a/backend/app/services/federation.py +++ b/backend/app/services/federation.py @@ -49,14 +49,29 @@ def dedup_key(doc: LegalDoc) -> str: return f"judgment:{case}|{(doc.court_or_publisher or '').lower()}|{doc.date or ''}" +def _name_key(doc: LegalDoc) -> str | None: + """A Polish act's NAME (`dzu_md.act_key`): the local index answers with the act's current + consolidated text (its own ELI, DU/2023/725), live ELI with the act as published (DU/2001/733) + — one act, two ids. Only an indexed answer claims a name, so two live acts that share one (a law + re-enacted under its old title) are both still shown.""" + if doc.kind != ACT or doc.source not in ("dzu_md", "eli") or not doc.title: + return None + from ..integrations.dzu_md import act_key + return "name:" + act_key(str(doc.extra.get("full_title") or doc.title)) + + def dedup(docs: list[LegalDoc]) -> list[LegalDoc]: seen: set[str] = set() out: list[LegalDoc] = [] for d in docs: k = dedup_key(d) - if k not in seen: - seen.add(k) - out.append(d) + name = _name_key(d) + if k in seen or (name is not None and d.source != "dzu_md" and name in seen): + continue + seen.add(k) + if name is not None and d.source == "dzu_md": + seen.add(name) + out.append(d) return out diff --git a/backend/app/services/indexing.py b/backend/app/services/indexing.py index 9b1adf0..cee6366 100644 --- a/backend/app/services/indexing.py +++ b/backend/app/services/indexing.py @@ -50,6 +50,27 @@ STALE_HEARTBEAT = dt.timedelta(minutes=15) #: the next SAOS pass asks for modifications since its predecessor's start, minus this margin SINCE_MARGIN = dt.timedelta(hours=1) SAVE_EVERY = 50 +#: a run that did not finish (a deploy, a restart, a crash) is resumed this soon — not a whole +#: `interval` later, which is how the box's first `eli_inforce` pass stopped at 57 of 2 411 acts +#: and would have waited a day (2026-10-21) +RESUME_AFTER = dt.timedelta(minutes=10) + + +def unfinished(st: dict) -> bool: + """The last run was attempted after the last completed one (or none ever completed).""" + attempted, synced = st.get("attempted_at"), st.get("synced_at") + return attempted is not None and (synced is None or synced < attempted) + + +def reconcile_superseded(store) -> list[str]: + """Flag every older text of an act the index holds in several (`dzu_md.supersede_plan`) as + superseded — never searched — and the newest as not; returns the ELIs whose flag changed (their + index parts must be redone). Why: the dataset carries every t.j. since 2012 (thirteen of the + Labour Code), and only `eli_inforce` used to flag the old ones, per act, once it had reached it + — so a search listed one act three times (2026-10-21). Runs after every import of either act + dataset and before an index rebuild; no request, one query of the acts' titles.""" + superseded, current = dzu.supersede_plan(store.act_heads()) + return store.mark_superseded(superseded, current) class DatasetImporter(Protocol): @@ -141,8 +162,12 @@ class DzuMdImporter(_Base): def due(self, now: dt.datetime) -> bool: st = self.state() last = st.get("attempted_at") - return last is None or now - last >= self.interval or bool( - (st.get("cursor") or {}).get("failed")) and now - last >= dt.timedelta(minutes=30) + if last is None or now - last >= self.interval: + return True + if unfinished(st) and now - last >= RESUME_AFTER: + return True + return bool((st.get("cursor") or {}).get("failed")) and \ + now - last >= dt.timedelta(minutes=30) async def run_once(self, stop: asyncio.Event | None = None) -> dict: st = self.state() @@ -150,8 +175,13 @@ class DzuMdImporter(_Base): failed_before = list((st.get("cursor") or {}).get("failed") or []) index_ok = self.index.ready() if head == st.get("commit_sha") and not failed_before and index_ok: - await self._save_async(synced_at=self._clock(), error=None, changed=0) - return {"head": head, "changed": 0, "removed": 0, "failed": 0, "unchanged": True} + flags = await asyncio.to_thread(reconcile_superseded, self.store) + if flags: + await asyncio.to_thread( + lambda: self.index.update(self.store.iter_dzu_rows(flags), flags, head)) + await self._save_async(synced_at=self._clock(), error=None, changed=len(flags)) + return {"head": head, "changed": 0, "removed": 0, "failed": 0, "unchanged": True, + "superseded_flags": len(flags)} rows = await self.upstream.index(head) stored = await asyncio.to_thread(self.store.dzu_fingerprints) @@ -177,14 +207,17 @@ class DzuMdImporter(_Base): interrupted = len(done) + len(failed) < len(todo) if removed: await asyncio.to_thread(self.store.delete_acts, removed) + # a new t.j. supersedes the older ones (a removed one may un-supersede its predecessor) + flags = await asyncio.to_thread(reconcile_superseded, self.store) + redo = sorted(set(done) | set(flags)) # the index: a full rebuild when there is none, else only what changed await self._save_async(heartbeat_at=self._clock(), progress={"phase": "index"}) if not index_ok: await asyncio.to_thread(self.index.rebuild, self.store.iter_dzu_rows(), head) - elif done or removed: + elif redo or removed: await asyncio.to_thread( - lambda: self.index.update(self.store.iter_dzu_rows(done), [*done, *removed], head)) + lambda: self.index.update(self.store.iter_dzu_rows(redo), [*redo, *removed], head)) acts, arts = await asyncio.to_thread(self.store.dzu_counts) now = self._clock() fields = {"doc_count": acts, "part_count": arts, "changed": len(done) + len(removed), @@ -199,7 +232,7 @@ class DzuMdImporter(_Base): fields["completed_at"] = now await self._save_async(**fields) return {"head": head, "changed": len(done), "removed": len(removed), - "failed": len(failed), "interrupted": interrupted} + "failed": len(failed), "interrupted": interrupted, "superseded_flags": len(flags)} # ── SAOS dump ─────────────────────────────────────────────────────────────────────────────────────── @@ -325,17 +358,28 @@ class EliInForceImporter(_Base): off_reason = "INSIDER_ELI_INFORCE_SYNC=false" def __init__(self, store, index, client, *, on: bool, interval_hours: float, types: list[str], - max_acts: int | None = None, clock=utcnow) -> None: + max_acts: int | None = None, after: str | None = None, clock=utcnow) -> None: super().__init__(store, index, on=on, clock=clock) self.client = client self.upstream = client # closed with the other upstreams self.interval = dt.timedelta(hours=interval_hours) self.types = types self.max_acts = max_acts + #: the dataset whose FIRST full import this one waits for (`dzu_md`, when its sync is on): + #: a text the dataset holds is never fetched from ELI, so running first would fetch + #: thousands of texts the mirror is about to bring — and it is due the moment that ends + self.after = after def due(self, now: dt.datetime) -> bool: - last = self.state().get("attempted_at") - return last is None or now - last >= self.interval + if self.after and (self.store.sync_state(self.after) or {}).get("completed_at") is None: + return False + st = self.state() + last = st.get("attempted_at") + if last is None or now - last >= self.interval: + return True + # an interrupted pass (a deploy mid-run) carries on soon: its `seen` cursor keeps the acts + # already done, so the rest is what is fetched + return unfinished(st) and now - last >= RESUME_AFTER def status(self) -> dict: out = super().status() @@ -446,6 +490,7 @@ class EliInForceImporter(_Base): seen.pop(base) if gone: await asyncio.to_thread(self.store.delete_acts, gone, "eli") + flags += await asyncio.to_thread(reconcile_superseded, self.store) redo = sorted(set(changed) | set(flags) | set(gone)) await self._save_async(heartbeat_at=self._clock(), progress={"phase": "index"}) if not self.index.ready(): @@ -737,6 +782,9 @@ async def ensure_index(importer) -> None: if handle is None: return try: + if importer.name in (dzu.DATASET, EliInForceImporter.name): + # the flags first, so the rebuilt index never holds an older t.j. as searchable + await asyncio.to_thread(reconcile_superseded, importer.store) n = await asyncio.to_thread(importer.index.rebuild, rows, st.get("commit_sha")) log.info("%s index rebuilt from Postgres: %d parts", importer.name, n) finally: @@ -823,7 +871,8 @@ def build_indexing(settings, store, *, transport=None, clock=utcnow, **client_kw timeout=httpx.Timeout(connect=5.0, read=60.0, write=10.0, pool=5.0)), on=settings.insider_eli_inforce_sync, interval_hours=settings.insider_eli_inforce_interval_hours, - types=settings.eli_inforce_types, clock=clock), + types=settings.eli_inforce_types, + after=dzu.DATASET if settings.insider_dzu_md_sync else None, clock=clock), ] # CELLAR: one client (one in flight, the importer's rate; redirects only to its own host) # shared by the two kinds, which never run at once (one lock key, one index writer) diff --git a/backend/app/services/indexstore.py b/backend/app/services/indexstore.py index 699eb5f..b5d2568 100644 --- a/backend/app/services/indexstore.py +++ b/backend/app/services/indexstore.py @@ -33,6 +33,8 @@ _ACT_COLS = ("eli", "year", "pos", "title", "type", "announcement_date", "promul "base_eli") #: what a read returns: the written columns plus the flag only `mark_superseded` sets _ACT_READ = (*_ACT_COLS, "superseded") +#: what the supersede reconciliation reads of every act (`dzu_md.supersede_plan`) +_HEAD_COLS = ("eli", "title", "year", "pos", "type", "origin", "superseded") STATE_COLS = ("name", "commit_sha", "cursor", "running", "heartbeat_at", "attempted_at", "synced_at", "completed_at", "doc_count", "part_count", "changed", "progress", "error") @@ -124,6 +126,9 @@ class MemoryIndexStore: changed.append(e) return changed + def act_heads(self) -> list[dict]: + return [{k: a.get(k) for k in _HEAD_COLS} for a in self.acts.values()] + def dzu_counts(self) -> tuple[int, int]: return len(self.acts), sum(len(v) for v in self.articles.values()) @@ -342,6 +347,15 @@ class PgIndexStore: db.commit() return changed + def act_heads(self) -> list[dict]: + """Every act's identity columns (no texts) — a few hundred KB for the whole dataset.""" + from sqlalchemy import select + + from ..models import DzuAct + cols = [getattr(DzuAct, c) for c in _HEAD_COLS] + with self._factory() as db: + return [dict(zip(_HEAD_COLS, r, strict=True)) for r in db.execute(select(*cols))] + def dzu_counts(self) -> tuple[int, int]: from sqlalchemy import func, select @@ -356,7 +370,8 @@ class PgIndexStore: from ..models import DzuAct, DzuArticle stmt = (select(DzuArticle.eli, DzuArticle.ord, DzuArticle.text, DzuAct.title, - DzuAct.announcement_date, DzuAct.promulgation, DzuAct.superseded) + DzuAct.announcement_date, DzuAct.promulgation, DzuAct.superseded, + DzuAct.type, DzuAct.status) .join(DzuAct, DzuAct.eli == DzuArticle.eli) .order_by(DzuArticle.eli, DzuArticle.ord)) if elis is not None: @@ -364,10 +379,13 @@ class PgIndexStore: return stmt = stmt.where(DzuArticle.eli.in_(elis)) with self._factory() as db: - for eli, o, text, title, ann, prom, sup in db.execute(stmt.execution_options( - yield_per=2000)): - yield {"group": eli, "ord": o, "title": title or "", "text": text, - "date": ann or prom, "tags": ["sup"] if sup else []} + act: dict = {} + for eli, o, text, title, ann, prom, sup, typ, status in db.execute( + stmt.execution_options(yield_per=2000)): + if act.get("eli") != eli: # the act's part of the row, as `act_rows` reads it + act = {"eli": eli, "title": title, "announcement_date": ann, + "promulgation": prom, "superseded": sup, "type": typ, "status": status} + yield from act_rows(act, [{"ord": o, "text": text}]) # ── dziennik-ustaw-md: writes (the importer) ── def upsert_act(self, rec: ActRecord) -> None: diff --git a/backend/app/services/textindex.py b/backend/app/services/textindex.py index 2a77802..a2f6645 100644 --- a/backend/app/services/textindex.py +++ b/backend/app/services/textindex.py @@ -8,11 +8,20 @@ tokenizer then only splits and lower-cases them. Query words go through the same "ochrona danych osobowych" and "ochronie danych osobowych" are one query. One tantivy document per PART (an act's article, a judgment's section): `group` (the act's ELI, the -judgment's id), `ord` (the part's position), the group's title stems (weighted ×3), the part's -stems, `day` (yyyymmdd, for date filters) and raw `tag`s (exact filters: a court type, a case -number). A search asks for the parts that contain every query stem — in the body or the title — -takes the best few hundred by BM25 and groups them: a group ranks by its best part (plus a little -for how many matched), and carries its three best. +judgment's id), `ord` (the part's position), the group's title stems, the part's HEAD (a chapter +heading carried in front of it: "Tytuł IV Zachowek" before art. 991), its LEAD (the first sentence) +and its body stems, `day` (yyyymmdd, for date filters), raw `tag`s (exact filters: a court type, a case number) +and a stored `prior` (the group's static weight — a code over an amending act; 1.0 by default). + +Matching and ranking (format 2, 2026-10-21): + * every CONTENT word of the query must be in the part (body, lead or title) — function words + (`plstem.STOPWORDS`: o, w, z, na…) never decide a match; + * BM25 field weights title > head > lead > body (`TITLE_BOOST`, `HEAD_BOOST`, `LEAD_BOOST`); + * proximity: the content stems adjacent and in order (a phrase, slop `SLOP`) weigh more, each + adjacent pair of them a little, and the WHOLE phrase as typed — function words included, which + is why the body keeps them in the index — most ("umowa o pracę", "bez wypowiedzenia"); + * the parts are grouped by `group`: a group ranks by its best part times its `prior` and a little + for how many parts matched (`BREADTH`), and carries its best `HITS_PER_GROUP`. The index is DISPOSABLE. Postgres is the source of truth: `rebuild()` recreates it from the rows (built aside, then swapped in), `update()` re-indexes the groups an import changed. `index.json` @@ -26,6 +35,7 @@ import datetime as dt import json import logging import math +import re import shutil import threading from collections.abc import Iterable @@ -41,10 +51,23 @@ except ImportError: # pragma: no cover — exercised only wh tantivy = None META = "index.json" +#: bumped when what a document holds changes (fields, analysis); an index of another format is +#: not `ready()` and `indexing.ensure_index` rebuilds it from Postgres — like `plstem.VERSION` +FORMAT = 2 TITLE_BOOST = 3.0 -PHRASE_BOOST = 2.0 -TOP_PARTS = 600 +HEAD_BOOST = 4.0 +LEAD_BOOST = 1.5 +FIELDS = (("body", 1.0), ("lead", LEAD_BOOST), ("head", HEAD_BOOST), ("title", TITLE_BOOST)) +#: how much the number of an act's matching parts adds (×(1 + BREADTH·ln(1+n))): the act that +#: deals with a subject throughout over the one with a single article on it +BREADTH = 0.05 +PHRASE_BOOST = 3.0 +PAIR_BOOST = 1.0 +EXACT_BOOST = 4.0 +SLOP = 2 +TOP_PARTS = 800 HITS_PER_GROUP = 3 +LEAD_CHARS = 300 WRITER_HEAP = 64_000_000 @@ -56,14 +79,35 @@ def day(value: str | None) -> int: return 0 +_ARTICLE = re.compile(r"^[#\s]*Art\.\s*[^\s.]+\.", re.M) +_MARKER = re.compile(r"^\s*(?:§\s*\d+\w*\.|\d+[a-z]*[.)])\s*") +_SENTENCE = re.compile(r"[.;:](?=\s|$)") +HEAD_CHARS = 200 + + +def split_lead(text: str) -> tuple[str, str]: + """(heading, first sentence) of a part: the structural heading carried in front of an article + ("Tytuł IV / Zachowek", "Rozdział 2a / Najem okazjonalny lokalu") — what the article is ABOUT, + in a word — and its first sentence, the article and paragraph numbers skipped.""" + text = text or "" + m = _ARTICLE.search(text, 0, LEAD_CHARS) + heading = text[: m.start()].strip()[:HEAD_CHARS] if m else "" + rest = _MARKER.sub("", text[m.end():] if m else text, count=1)[:LEAD_CHARS] + end = _SENTENCE.search(rest, 20) + return heading, (rest[: end.start()] if end else rest) + + def _schema(): sb = tantivy.SchemaBuilder() sb.add_text_field("key", stored=True, tokenizer_name="raw") sb.add_text_field("group", stored=False, tokenizer_name="raw") sb.add_text_field("tag", stored=False, tokenizer_name="raw") sb.add_text_field("title", stored=False) + sb.add_text_field("head", stored=False) + sb.add_text_field("lead", stored=False) sb.add_text_field("body", stored=False) sb.add_integer_field("day", stored=False, indexed=True, fast=True) + sb.add_float_field("prior", stored=True) return sb.build() @@ -89,12 +133,15 @@ class TextIndex: holds stems no query produces any more, so it is not ready — `indexing.ensure_index` rebuilds it from Postgres (no download).""" meta = self.meta() - return self.available and bool(meta.get("docs")) and meta.get("stemmer") == plstem.VERSION + return self.available and bool(meta.get("docs")) and \ + meta.get("stemmer") == plstem.VERSION and meta.get("format") == FORMAT def stale_stemmer(self) -> bool: - """An index exists but was built with another `plstem.VERSION` (or before it was recorded).""" + """An index exists but was built with another `plstem.VERSION` or document `FORMAT` (or + before they were recorded): its terms must never be mixed with today's.""" meta = self.meta() - return bool(meta) and meta.get("stemmer") != plstem.VERSION + return bool(meta) and (meta.get("stemmer") != plstem.VERSION + or meta.get("format") != FORMAT) def size_bytes(self) -> int: try: @@ -113,17 +160,22 @@ class TextIndex: def _write_meta(self, path: Path, marker, docs: int) -> None: (path / META).write_text(json.dumps({ - "marker": marker, "docs": docs, "stemmer": plstem.VERSION, + "marker": marker, "docs": docs, "stemmer": plstem.VERSION, "format": FORMAT, "built_at": dt.datetime.now(dt.UTC).isoformat(timespec="microseconds")}), encoding="utf-8") @staticmethod def _doc(row: dict): + text = row.get("text") or "" + heading, first = split_lead(text) return tantivy.Document(key=f"{row['group']}#{row['ord']}", group=str(row["group"]), tag=list(row.get("tags") or []), - title=plstem.analyse(row.get("title") or ""), - body=plstem.analyse(row.get("text") or ""), - day=day(row.get("date"))) + title=plstem.analyse(row.get("title") or "", keep_stopwords=True), + head=plstem.analyse(heading), lead=plstem.analyse(first), + # function words stay in the body: the exact-phrase check needs + # their positions ("umowa o pracę"); matching never asks for them + body=plstem.analyse(text, keep_stopwords=True), + day=day(row.get("date")), prior=float(row.get("prior") or 1.0)) # ── building ── def rebuild(self, rows: Iterable[dict], marker=None) -> int: @@ -201,17 +253,15 @@ class TextIndex: s = self._schema musts = [] for term in terms: - alts = [] - for v in term: - alts.append((T.Occur.Should, T.Query.term_query(s, "body", v))) - alts.append((T.Occur.Should, T.Query.boost_query( - T.Query.term_query(s, "title", v), TITLE_BOOST))) - musts.append((T.Occur.Must, T.Query.boolean_query(alts))) - if len(stems) > 1: - # the words next to each other ("umowa o pracę" → `umow prac`; stop words are not - # indexed) weigh more than the same words scattered over an article - musts.append((T.Occur.Should, T.Query.boost_query( - T.Query.phrase_query(s, "body", stems), PHRASE_BOOST))) + # per field the BEST of the word's stems ("zachowek" | "zachowk": one word, counted + # once), then the fields add up + fields = [] + for field, boost in FIELDS: + one = [T.Query.term_query(s, field, v) for v in term] + q_ = one[0] if len(one) == 1 else T.Query.disjunction_max_query(one) + fields.append((T.Occur.Should, q_ if boost == 1.0 else T.Query.boost_query(q_, boost))) + musts.append((T.Occur.Must, T.Query.boolean_query(fields))) + musts += [(T.Occur.Should, q_) for q_ in self._proximity(q, terms)] for tag in tags: musts.append((T.Occur.Must, T.Query.term_query(s, "tag", tag))) for tag in exclude_tags: # "sup" = a consolidated text a newer one replaced @@ -224,16 +274,47 @@ class TextIndex: index.reload() searcher = index.searcher() result = searcher.search(T.Query.boolean_query(musts), TOP_PARTS) - found = [(score, searcher.doc(addr)["key"][0]) for score, addr in result.hits] + found = [] + for score, addr in result.hits: + doc = searcher.doc(addr) + found.append((score, doc["key"][0], (doc.get_all("prior") or [1.0])[0])) groups: dict[str, dict] = {} - for score, key in found: + for score, key, prior in found: g, _, o = key.rpartition("#") - grp = groups.setdefault(g, {"group": g, "score": 0.0, "n": 0, "hits": []}) + grp = groups.setdefault(g, {"group": g, "score": 0.0, "n": 0, "hits": [], + "prior": prior}) grp["n"] += 1 grp["score"] = max(grp["score"], score) if len(grp["hits"]) < HITS_PER_GROUP: grp["hits"].append({"ord": int(o), "score": score}) ranked = sorted(groups.values(), - key=lambda g: (g["score"] + 0.25 * math.log1p(g["n"]), g["group"]), + key=lambda g: (g["score"] * (1 + BREADTH * math.log1p(g["n"])) + * g["prior"], g["group"]), reverse=True) return ranked[offset:offset + limit], len(ranked) + + def _proximity(self, q: str, terms: list[list[str]]) -> list: + """The SHOULD clauses that reward words found together: the content stems as a phrase + (slop `SLOP`, in the body and the title), each adjacent pair of them, and the whole query + as typed — function words included — word for word in the body.""" + T = tantivy + s = self._schema + out = [] + if len(terms) > 1: + # every combination of the words' alternatives ("najem" → naj | najm), capped + combos: list[list[str]] = [[]] + for term in terms: + combos = [c + [v] for c in combos for v in term][:8] + for combo in combos: + out.append(T.Query.boost_query( + T.Query.phrase_query(s, "body", combo, SLOP), PHRASE_BOOST)) + out.append(T.Query.boost_query( + T.Query.phrase_query(s, "title", combo, SLOP), PHRASE_BOOST)) + if len(terms) > 2: + for a, b in zip(terms, terms[1:], strict=False): + out.append(T.Query.boost_query( + T.Query.phrase_query(s, "body", [a[0], b[0]], SLOP), PAIR_BOOST)) + exact = plstem.stems(q, keep_stopwords=True) + if len(exact) > len(terms) and len(exact) > 1: + out.append(T.Query.boost_query(T.Query.phrase_query(s, "body", exact), EXACT_BOOST)) + return out diff --git a/backend/scripts/build_search_fixture.py b/backend/scripts/build_search_fixture.py new file mode 100644 index 0000000..88acd56 --- /dev/null +++ b/backend/scripts/build_search_fixture.py @@ -0,0 +1,100 @@ +"""Build `tests/fixtures/search_eval.json.gz` — the offline search evaluation's slice of real acts. + +A developer tool, never run by the app or CI. Download the inputs politely by hand first (one +request each, a second apart, an identifying User-Agent) into a directory of their own: + + * `index.csv` and `DU--.md` for every ELI in `DZU_ACTS`, from + https://raw.githubusercontent.com/PolskiAgentW/dziennik-ustaw-md/main/ (CC0 data, eli2md MIT); + * `eli--.json` + `eli--.html` for every ELI in `ELI_ACTS`, from + https://api.sejm.gov.pl/eli/acts/DU// and its `/text.html`; + +then `python scripts/build_search_fixture.py `. The acts are parsed with the +production parsers (`dzu_md.build_record`, `html_to_text` + `split_plain_articles`) and SLICED: the +head, the first `FIRST` articles, every article that holds the stems of a regression query and +the articles a query must find — each cut to `MAX_CHARS`, so the file stays small while the +competition between acts stays real. +""" +from __future__ import annotations + +import gzip +import io +import json +import sys +from dataclasses import asdict +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "tests")) + +from search_eval import FIXTURE, REGRESSION # noqa: E402 + +from app.integrations import dzu_md as dzu # noqa: E402 +from app.integrations import plstem # noqa: E402 +from app.services.htmltext import html_to_text # noqa: E402 + +#: current t.j. the queries must find, older t.j. of the same acts, and the past wrong winners +DZU_ACTS = ("DU/2023/725", "DU/2022/172", "DU/2019/1781", "DU/2016/922", "DU/2023/1206", + "DU/2024/1251", "DU/2026/1245", "DU/2025/277", "DU/2025/807", "DU/2025/1688", + "DU/2026/44", "DU/2026/795", "DU/2026/1342", "DU/2025/734", "DU/2026/1244", + "DU/2025/1714") +#: acts with no consolidated text in the dataset: ELI's text, as `eli_inforce` stores it +ELI_ACTS = ("DU/2024/928",) +FIRST = 8 +MAX_CHARS = 2500 +#: the articles a regression query must list, per act (`num` as printed) +MUST = {"DU/2023/725": {"19a"}, "DU/2026/1245": {"22", "25", "29", "30", "52"}, + "DU/2026/795": {"1", "117", "991"}, "DU/2026/1342": {"178a"}, "DU/2025/734": {"87"}} + + +def _wanted(num: str | None, text: str, eli: str, ordinal: int) -> bool: + if ordinal <= FIRST or (num and dzu.art_label(num) in MUST.get(eli, ())): + return True + have = set(plstem.stems(text)) + for q, *_ in REGRESSION: + want = [t[0] for t in plstem.query_terms(q)] + # every stem of a multi-word query (prefix match: "najm" for najem), or a one-word query + if want and all(any(h.startswith(w) for h in have) for w in want): + return True + return False + + +def _slice(rec: dzu.ActRecord) -> dict: + out = asdict(rec) + out["articles"] = [{"ord": a.ord, "num": a.num, "text": a.text[:MAX_CHARS]} + for a in rec.articles if _wanted(a.num, a.text, rec.eli, a.ord)] + return out + + +def main(src: Path) -> None: + rows = {r["eli"]: r for r in dzu.parse_index((src / "index.csv").read_text(encoding="utf-8"))} + acts = [] + for eli in DZU_ACTS: + _pub, y, p = eli.split("/") + md = (src / f"DU-{y}-{p}.md").read_text(encoding="utf-8") + acts.append(_slice(dzu.build_record(rows[eli], md))) + for eli in ELI_ACTS: + _pub, y, p = eli.split("/") + meta = json.loads((src / f"eli-{y}-{p}.json").read_text(encoding="utf-8")) + text = html_to_text((src / f"eli-{y}-{p}.html").read_text(encoding="utf-8")) + fp = f"{eli}|{meta.get('changeDate')}" + acts.append(_slice(dzu.ActRecord( + eli=eli, title=meta["title"], year=int(y), pos=int(p), type=meta.get("type"), + announcement_date=meta.get("announcementDate"), promulgation=meta.get("promulgation"), + change_date=meta.get("changeDate"), status=meta.get("status"), + display_address=f"Dz.U. {y} poz. {p}", source_pdf=dzu.default_pdf(eli), + converter="html", fingerprint=fp, articles=dzu.split_plain_articles(text), + origin="eli", base_eli=eli))) + FIXTURE.parent.mkdir(parents=True, exist_ok=True) + buf = io.BytesIO() + with gzip.GzipFile(fileobj=buf, mode="wb", mtime=0) as gz: + gz.write(json.dumps(acts, ensure_ascii=False, indent=0).encode("utf-8")) + FIXTURE.write_bytes(buf.getvalue()) + n = sum(len(a["articles"]) for a in acts) + print(f"{FIXTURE}: {len(acts)} acts, {n} articles, {len(buf.getvalue()) // 1024} KiB") + + +if __name__ == "__main__": + if len(sys.argv) != 2: + sys.exit(__doc__) + main(Path(sys.argv[1])) diff --git a/backend/tests/fixtures/search_eval.json.gz b/backend/tests/fixtures/search_eval.json.gz new file mode 100644 index 0000000..690ebd2 Binary files /dev/null and b/backend/tests/fixtures/search_eval.json.gz differ diff --git a/backend/tests/search_eval.py b/backend/tests/search_eval.py new file mode 100644 index 0000000..72a1ac0 --- /dev/null +++ b/backend/tests/search_eval.py @@ -0,0 +1,117 @@ +"""The offline search-quality evaluation: real-shaped acts, the regression queries, the top-3 table. + +`tests/fixtures/search_eval.json.gz` is a SLICE of real acts — dziennik-ustaw-md's Markdown (CC0, +eli2md MIT) and, for the act no consolidated text covers yet (ustawa o ochronie sygnalistów, +Dz.U. 2024 poz. 928), ELI's HTML as the `eli_inforce` gap-filler stores it — cut down by +`scripts/build_search_fixture.py`. It holds the current consolidated texts the queries should find, +OLDER t.j. of the same acts (the "same act 3× in the top 3" bug), and the acts that won the +queries wrongly before (ustawa o umowie koncesji, ustawa o nieodpłatnej pomocy prawnej, an +amending act of the Labour Code). + +The pipeline is the production one, DB-free: `MemoryIndexStore.upsert_act` → the supersede +reconciliation → `TextIndex.rebuild(store.iter_dzu_rows())` → `DzuMdAdapter._search`. Nothing here +reaches a network. `python tests/search_eval.py` prints the table (`test_search_quality.py` asserts it). +""" +from __future__ import annotations + +import datetime as dt +import gzip +import json +import sys +import tempfile +from pathlib import Path + +FIXTURE = Path(__file__).parent / "fixtures" / "search_eval.json.gz" + +#: (query, the act that must win, how deep it may be (1 = top-1), articles expected among its hits). +#: The act is the ELI of its CURRENT text (an older t.j. of it is not the answer), or a title regex +#: where several acts are right +REGRESSION: list[tuple[str, str, int, tuple[str, ...]]] = [ + ("najem okazjonalny", "DU/2023/725", 1, ("19a",)), + ("ochrona danych osobowych", "DU/2019/1781", 1, ()), + ("przekroczenie prędkości", "DU/2024/1251", 3, ()), + ("umowa o pracę", "DU/2026/1245", 1, ()), + ("sygnaliści", "DU/2024/928", 1, ()), + ("kodeks cywilny", "DU/2026/795", 1, ()), + ("rozwiązanie umowy o pracę bez wypowiedzenia", "DU/2026/1245", 1, ("52",)), + ("zachowek", "DU/2026/795", 1, ("991",)), + ("przedawnienie roszczeń", "DU/2026/795", 1, ("117",)), + ("jazda po alkoholu", "Kodeks (karny|wykroczeń)", 3, ()), + ("ochrona konsumenta", "konsument", 3, ()), +] + + +def load_fixture(path: Path = FIXTURE) -> list[dict]: + with gzip.open(path, "rt", encoding="utf-8") as fh: + return json.load(fh) + + +def build(tmp: Path, acts: list[dict] | None = None): + """The adapter over a fresh in-memory store + tantivy index holding the fixture.""" + from app.integrations import dzu_md as dzu + from app.services import indexing + from app.services.indexstore import MemoryIndexStore + from app.services.textindex import TextIndex + + store = MemoryIndexStore() + for a in acts if acts is not None else load_fixture(): + rec = 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"]]) + store.upsert_act(rec) + reconcile = getattr(indexing, "reconcile_superseded", None) + if reconcile is not None: + reconcile(store) + index = TextIndex(tmp / "dzu_md") + index.rebuild(store.iter_dzu_rows(), "fixture") + now = dt.datetime.now(dt.UTC) + for name in ("dzu_md", "eli_inforce"): + store.set_state(name, doc_count=len(store.acts), completed_at=now, synced_at=now) + return dzu.DzuMdAdapter(store, index, stale_hours=24) + + +def top(adapter, q: str, n: int = 3) -> list[dict]: + from app.integrations.base import Query + page = adapter._search(Query(q=q, kind="act"), 0, 10) + return [{"eli": d.extra.get("eli"), "title": d.title, + "articles": [h.get("num") for h in d.extra.get("articles") or []]} + for d in page.docs[:n]] + + +def matches(row: dict, want: str) -> bool: + import re + if want.startswith("DU/"): + return row["eli"] == want + return re.search(want, row["title"] or "", re.I) is not None + + +def table(adapter) -> str: + lines = ["| query | #1 | #2 | #3 | ok |", "|---|---|---|---|---|"] + for q, want, depth, arts in REGRESSION: + rows = top(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'} |") + return "\n".join(lines) + + +def passed(rows: list[dict], want: str, depth: int, arts: tuple[str, ...]) -> bool: + hit = next((r for r in rows[:depth] if matches(r, want)), None) + if hit is None: + return False + # every act at most once: an older t.j. of the same act is not a second answer + titles = [r["title"] for r in rows] + if len(set(titles)) != len(titles): + return False + return all(a in hit["articles"] for a in arts) + + +def _short(title: str) -> str: + title = (title or "").replace("Ustawa ", "").replace(" (tekst jednolity)", " (t.j.)") + return title[:48] + ("…" if len(title) > 48 else "") + + +if __name__ == "__main__": + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + with tempfile.TemporaryDirectory() as d: + print(table(build(Path(d)))) diff --git a/backend/tests/test_indexed_db.py b/backend/tests/test_indexed_db.py index b318764..3c2cee4 100644 --- a/backend/tests/test_indexed_db.py +++ b/backend/tests/test_indexed_db.py @@ -62,6 +62,29 @@ def test_acts_round_trip_by_origin_and_superseded(store): assert store.get_act(f"DU/{YEAR}/2") is None and store.get_articles(f"DU/{YEAR}/2") == {} +def test_act_heads_rows_and_the_reconciliation(store): + """The supersede reconciliation over the real table: of two texts of one act only the newer is + searched, and the index rows carry the act's name and prior (not the notice's boilerplate).""" + from app.services import indexing + tj = ("Obwieszczenie Marszałka Sejmu Rzeczypospolitej Polskiej z dnia 1 marca {y} r. w sprawie " + "ogłoszenia jednolitego tekstu ustawy - Kodeks testowy") + for pos in (11, 12): + store.upsert_act(dzu.ActRecord( + eli=f"DU/{YEAR}/{pos}", title=tj.format(y=YEAR), year=YEAR, pos=pos, fingerprint="f", + type="Obwieszczenie", status="obowiązujący", + articles=dzu.split_articles("##### Art. 1.\n\nKodeks testowy."))) + heads = {h["eli"]: h for h in store.act_heads()} + assert heads[f"DU/{YEAR}/11"]["title"] == tj.format(y=YEAR) + assert {f"DU/{YEAR}/11", f"DU/{YEAR}/12"} <= set(heads) + changed = indexing.reconcile_superseded(store) + assert f"DU/{YEAR}/11" in changed + assert store.get_act(f"DU/{YEAR}/11")["superseded"] is True + assert store.get_act(f"DU/{YEAR}/12")["superseded"] is False + row = next(iter(store.iter_dzu_rows([f"DU/{YEAR}/12"]))) + assert row["title"] == "Ustawa - Kodeks testowy" and row["prior"] == dzu.PRIOR_CODE + assert row["tags"] == [] + + def test_judgments_round_trip(store): items = [{"id": JID + i, "courtType": "COMMON", "courtCases": [{"caseNumber": f"I C {i}/22"}], "judgmentType": "SENTENCE", "judgmentDate": "2023-05-30", diff --git a/backend/tests/test_search_quality.py b/backend/tests/test_search_quality.py new file mode 100644 index 0000000..6a11336 --- /dev/null +++ b/backend/tests/test_search_quality.py @@ -0,0 +1,228 @@ +"""Search QUALITY in INDEXED mode, DB-free: one answer per act, the ranking, and the offline +evaluation over real-shaped acts (`tests/search_eval.py`, `tests/fixtures/search_eval.json.gz`). + +The regression set is the box's own (2026-10-21): "umowa o pracę" answered with the act on +works-concession contracts, "najem okazjonalny" listed the tenants' act three times (three +consolidated texts of it), "sygnaliści" found the free-legal-aid act. Nothing here reaches a host. +""" +from __future__ import annotations + +import datetime as dt +from pathlib import Path + +import pytest +import search_eval as se + +from app.integrations import dzu_md as dzu +from app.integrations import plstem +from app.integrations.base import ACT, LegalDoc +from app.services import federation, indexing, textindex +from app.services.indexstore import MemoryIndexStore +from app.services.textindex import TextIndex + +pytestmark = pytest.mark.skipif(not TextIndex.available, reason="tantivy is not installed") + +KP_TJ = ("Obwieszczenie Marszałka Sejmu Rzeczypospolitej Polskiej z dnia 1 września 2026 r. w " + "sprawie ogłoszenia jednolitego tekstu ustawy - Kodeks pracy") + + +@pytest.fixture(scope="module") +def adapter(tmp_path_factory): + return se.build(Path(tmp_path_factory.mktemp("eval"))) + + +# ── the offline evaluation ────────────────────────────────────────────────────────────────────────── +@pytest.mark.parametrize(("q", "want", "depth", "arts"), se.REGRESSION, + ids=[r[0] for r in se.REGRESSION]) +def test_regression_query(adapter, q, want, depth, arts): + rows = se.top(adapter, q) + assert se.passed(rows, want, depth, arts), se.table(adapter) + + +def test_one_answer_per_act(adapter): + """Thirteen texts of the Labour Code, three of the tenants' act: each answers ONCE, as its newest.""" + for q, *_ in se.REGRESSION: + rows = se.top(adapter, q, n=10) + names = [dzu.act_key(adapter.store.get_act(r["eli"])["title"]) for r in rows] + assert len(names) == len(set(names)), (q, rows) + for old in ("DU/2022/172", "DU/2025/277", "DU/2016/922"): + assert adapter.store.get_act(old)["superseded"] is True + assert old not in [r["eli"] for q, *_ in se.REGRESSION for r in se.top(adapter, q, 10)] + + +def test_the_wrong_winners_of_before_lose(adapter): + """`umowa o pracę` → the Labour Code, not ustawa o umowie koncesji (its title held "umowie"); + the amending act of the Labour Code ranks under the code itself.""" + rows = se.top(adapter, "umowa o pracę", n=10) + elis = [r["eli"] for r in rows] + assert elis[0] == "DU/2026/1245" + if "DU/2025/807" in elis: + assert elis.index("DU/2025/807") > elis.index("DU/2026/1245") + + +# ── one act, many texts ───────────────────────────────────────────────────────────────────────────── +def test_act_key_meets_every_text_of_one_act(): + published = "Ustawa z dnia 26 czerwca 1974 r. - Kodeks pracy" + assert dzu.act_key(KP_TJ) == dzu.act_key(published) == "ustawa kodeks pracy" + assert dzu.act_name(KP_TJ) == "Ustawa - Kodeks pracy" + assert dzu.act_key("Ustawa z dnia 4 czerwca 2025 r. o zmianie ustawy - Kodeks pracy") != \ + dzu.act_key(published) + + +def test_amending_codes_and_priors(): + assert dzu.is_amending("Ustawa z dnia 4 czerwca 2025 r. o zmianie ustawy - Kodeks pracy") + assert dzu.is_amending("Rozporządzenie Ministra Sprawiedliwości z dnia 12 lutego 2026 r. " + "zmieniające rozporządzenie w sprawie wniosku") + # "… i o zmianie Kodeksu cywilnego" names the act; it does not make it an amending act + assert not dzu.is_amending("Ustawa z dnia 21 czerwca 2001 r. o ochronie praw lokatorów, " + "mieszkaniowym zasobie gminy i o zmianie Kodeksu cywilnego") + assert dzu.is_code(KP_TJ) and dzu.is_code("Ustawa z dnia 23 kwietnia 1964 r. Kodeks cywilny") + assert dzu.act_prior({"title": KP_TJ, "type": "Obwieszczenie"}) == dzu.PRIOR_CODE + assert dzu.act_prior({"title": "Ustawa z dnia 4 czerwca 2025 r. o zmianie ustawy - Kodeks " + "pracy", "type": "Ustawa"}) == dzu.PRIOR_AMENDING + assert dzu.act_prior({"title": "Obwieszczenie Prezesa X w sprawie wysokości stawek", + "type": "Obwieszczenie"}) == dzu.PRIOR_NOTICE + assert dzu.act_prior({"title": "Ustawa o czymś", "status": "uchylony"}) == dzu.PRIOR_REPEALED + assert dzu.act_prior({"title": "Ustawa z dnia 14 czerwca 2024 r. o ochronie sygnalistów", + "status": "obowiązujący"}) == 1.0 + + +def test_supersede_plan_keeps_the_newest_text(): + acts = [{"eli": "DU/2025/277", "title": KP_TJ, "year": 2025, "pos": 277}, + {"eli": "DU/2026/1245", "title": KP_TJ, "year": 2026, "pos": 1245}, + {"eli": "DU/1974/141", "title": "Ustawa z dnia 26 czerwca 1974 r. - Kodeks pracy", + "year": 1974, "pos": 141}, + {"eli": "DU/2025/807", "title": "Ustawa z dnia 4 czerwca 2025 r. o zmianie ustawy - " + "Kodeks pracy", "year": 2025, "pos": 807}, + {"eli": "DU/2025/900", "type": "Obwieszczenie", "year": 2025, "pos": 900, + "title": "Obwieszczenie Prezesa X w sprawie stawek"}, + {"eli": "DU/2026/900", "type": "Obwieszczenie", "year": 2026, "pos": 900, + "title": "Obwieszczenie Prezesa X w sprawie stawek"}] + sup, cur = dzu.supersede_plan(acts) + assert cur == ["DU/2026/1245"] and sorted(sup) == ["DU/1974/141", "DU/2025/277"] + + +def test_reconcile_flags_and_unflags(): + store = MemoryIndexStore() + for eli, y, p in (("DU/2025/277", 2025, 277), ("DU/2026/1245", 2026, 1245)): + store.upsert_act(dzu.ActRecord(eli=eli, title=KP_TJ, year=y, pos=p, fingerprint="f", + articles=[dzu.Article(1, "1", "Art. 1. Kodeks pracy.")])) + assert sorted(indexing.reconcile_superseded(store)) == ["DU/2025/277"] + assert indexing.reconcile_superseded(store) == [] # idempotent + store.delete_acts(["DU/2026/1245"]) # the newest one leaves + assert indexing.reconcile_superseded(store) == [] # alone: nothing to compare + store.mark_superseded([], ["DU/2025/277"]) + assert store.get_act("DU/2025/277")["superseded"] is False + + +# ── matching and ranking ──────────────────────────────────────────────────────────────────────────── +def test_function_words_never_match_but_content_words_do(): + """"umowa" is a content word here (the EUR-Lex SPARQL list of common words is NOT the local + index's stoplist); "o" is a function word: never required, but kept for the exact phrase.""" + assert [t[0] for t in plstem.query_terms("umowa o pracę")] == ["umow", "prac"] + assert plstem.stems("umowa o pracę", keep_stopwords=True) == ["umow", "o", "prac"] + + +def _ix(tmp_path, rows): + ix = TextIndex(tmp_path / "ix") + ix.rebuild(rows, "m") + return ix + + +def test_exact_phrase_and_proximity_outrank_scattered_words(tmp_path): + rows = [{"group": "scattered", "ord": 1, "title": "Ustawa o czymś", + "text": "Art. 1. Strony zawierają umowę najmu lokalu, a wynajmujący nie świadczy " + "żadnej pracy."}, + {"group": "near", "ord": 1, "title": "Ustawa o czymś", + "text": "Art. 1. Pracodawca zawiera umowę na pracę zdalną."}, + {"group": "exact", "ord": 1, "title": "Ustawa o czymś", + "text": "Art. 1. Pracodawca zawiera umowę o pracę z pracownikiem."}] + groups, _ = _ix(tmp_path, rows).search("umowa o pracę") + assert [g["group"] for g in groups] == ["exact", "near", "scattered"] + + +def test_title_heading_and_prior_weigh(tmp_path): + rows = [{"group": "body-only", "ord": 1, "title": "Ustawa o spadkach", + "text": "Art. 5. Zachowek należy się zstępnym. Zachowek, zachowek."}, + {"group": "heading", "ord": 1, "title": "Ustawa o spadkach", + "text": "Tytuł IV\nZachowek\n##### Art. 991.\n§ 1. Zstępnym należy się zachowek."}, + {"group": "amending", "ord": 1, "title": "Ustawa o zmianie ustawy o spadkach", + "text": "Tytuł IV\nZachowek\n##### Art. 991.\n§ 1. Zstępnym należy się zachowek.", + "prior": dzu.PRIOR_AMENDING}] + groups, _ = _ix(tmp_path, rows).search("zachowek") + order = [g["group"] for g in groups] + # the heading names what the article is about; the same text in an amending act ranks lower + assert order[0] == "heading" and order.index("amending") > order.index("heading") + + +def test_split_lead(): + head, first = textindex.split_lead("\nTYTUŁ IV\n\nZachowek\n\n##### Art. 991.\n\n§ 1. " + "Zstępnym, małżonkowi oraz rodzicom spadkodawcy. Dalej.") + assert head == "TYTUŁ IV\n\nZachowek" and first == "Zstępnym, małżonkowi oraz rodzicom spadkodawcy" + + +def test_format_bump_makes_an_index_stale(tmp_path): + ix = _ix(tmp_path, [{"group": "g", "ord": 0, "title": "t", "text": "sygnaliści"}]) + assert ix.ready() and ix.meta()["format"] == textindex.FORMAT + meta_path = ix.path / textindex.META + import json + meta_path.write_text(json.dumps(ix.meta() | {"format": textindex.FORMAT - 1}), encoding="utf-8") + assert not ix.ready() and ix.stale_stemmer() # → `ensure_index` rebuilds it + + +def test_federation_drops_the_live_twin_of_an_indexed_act(): + local = LegalDoc(id="dzu_md:DU/2023/725", source="dzu_md", kind=ACT, + title="Ustawa o ochronie praw lokatorów (tekst jednolity)", + extra={"eli": "DU/2023/725", "full_title": "Obwieszczenie Marszałka Sejmu " + "z dnia 10 marca 2023 r. w sprawie ogłoszenia jednolitego tekstu ustawy " + "o ochronie praw lokatorów"}) + live = LegalDoc(id="eli:DU/2001/733", source="eli", kind=ACT, + title="Ustawa z dnia 21 czerwca 2001 r. o ochronie praw lokatorów", + extra={"eli": "DU/2001/733"}) + other = LegalDoc(id="eli:DU/2026/5", source="eli", kind=ACT, + title="Ustawa z dnia 1 maja 2026 r. o zmianie ustawy o ochronie praw lokatorów", + extra={"eli": "DU/2026/5"}) + assert [d.id for d in federation.dedup([local, live, other])] == [local.id, other.id] + # two LIVE acts sharing a name are both shown + assert len(federation.dedup([live, LegalDoc(id="eli:DU/1990/1", source="eli", kind=ACT, + title=live.title, extra={"eli": "DU/1990/1"})])) == 2 + + +# ── the gap-filler's schedule ─────────────────────────────────────────────────────────────────────── +T0 = dt.datetime(2026, 10, 21, 12, 0, tzinfo=dt.UTC) + + +def _eli_importer(store, after="dzu_md"): + return indexing.EliInForceImporter(store, None, None, on=True, interval_hours=24, + types=["Ustawa"], after=after, clock=lambda: T0) + + +def test_eli_inforce_waits_for_the_mirror_then_starts_at_once(): + store = MemoryIndexStore() + imp = _eli_importer(store) + assert not imp.due(T0) # dzu_md has not finished its first pass + store.set_state("dzu_md", completed_at=T0) + assert imp.due(T0) # …and now it is due, the same tick + assert _eli_importer(MemoryIndexStore(), after=None).due(T0) # the mirror off: no wait + + +def test_an_interrupted_pass_resumes_soon_not_a_day_later(): + """The box, 2026-10-21: the first pass stopped at 57 of 2 411 acts (a deploy), with no + `synced_at` — and `due()` asked only for `attempted_at` + 24 h.""" + store = MemoryIndexStore() + store.set_state("dzu_md", completed_at=T0) + store.set_state("eli_inforce", attempted_at=T0, synced_at=None) + imp = _eli_importer(store) + assert not imp.due(T0 + dt.timedelta(minutes=5)) + assert imp.due(T0 + indexing.RESUME_AFTER) + store.set_state("eli_inforce", synced_at=T0 + dt.timedelta(hours=1)) # it finished + assert not imp.due(T0 + dt.timedelta(hours=2)) + + +def test_dzu_md_resumes_an_interrupted_run(): + store = MemoryIndexStore() + imp = indexing.DzuMdImporter(store, None, None, on=True, interval_hours=6, clock=lambda: T0) + store.set_state("dzu_md", attempted_at=T0, synced_at=T0 - dt.timedelta(hours=7)) + assert imp.due(T0 + indexing.RESUME_AFTER) + store.set_state("dzu_md", synced_at=T0 + dt.timedelta(minutes=1)) + assert not imp.due(T0 + indexing.RESUME_AFTER)