EU acts in the local index (a CELLAR importer), stemmer v2

- A CELLAR importer instead of the EUR-Lex data dump (no EU Login): SPARQL
  lists the ~35k EU acts in force (R/L/D) with each one's newest
  consolidated version; the Polish text (English fallback, language
  recorded) comes through the allowlisted 303 -> cellar path at 1 req/s,
  one in flight, resumable. A full pass weekly, a delta daily (works whose
  own or consolidated modification date moved); acts that left force are
  kept but excluded. CJEU judgments behind INSIDER_CELLAR_CASELAW (off).
  Query and HTML-structure rules vendored from tseidl/eurlex-builder (MIT,
  4d61904) in integrations/cellar_builder/, adapted: in-force filter,
  consolidated versions, the delta, Polish headings, stdlib parsing.
  Tables eu_doc / eu_part (0007); the index stands in for live EUR-Lex per
  kind, with attribution, the conversion note and the official link.
- plstem v2: consonant alternations at the stem end (sygnalisci /
  sygnalista, studenci / student, autorzy / autor, sedziow / sedzia,
  prawnicy / prawnik), look-alikes pinned by tests. Each index records the
  stemmer version; a mismatch makes it not-ready and rebuilds it from
  Postgres on the next scheduler tick, with no re-download.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 13:28:14 +02:00
co-authored by Claude Opus 5.5
parent 084b4b0f03
commit cc3c3ee12b
25 changed files with 2027 additions and 89 deletions
+14 -2
View File
@@ -135,8 +135,20 @@ INSIDER_SAOS_DUMP_PAGE_SIZE=100
INSIDER_SAOS_DUMP_PAUSE_SECONDS=5
INSIDER_SAOS_DUMP_INTERVAL_HOURS=20
INSIDER_SAOS_INDEX_STALE_HOURS=96
# EUR-Lex's data dump: NOT implemented yet (needs an EU Login account). Keep false.
INSIDER_EURLEX_DUMP_SYNC=false
# CELLAR (EU law, anonymous — no EU Login account): every regulation, directive and decision IN
# FORCE with the text of its newest consolidated version (Polish, else English), from the
# Publications Office's SPARQL endpoint + the 303 text fetch. A full listing pass weekly, a delta
# (CELLAR's modification dates) every interval; one request in flight, every redirect hop counted
# against the rate (≤ 2). First import ~35k acts ≈ 20 h at 1 req/s; ~1 GB Postgres + ~0.3 GB index.
# (Replaces INSIDER_EURLEX_DUMP_SYNC, which is gone; a leftover value is ignored.)
INSIDER_CELLAR_SYNC=true
INSIDER_CELLAR_INTERVAL_HOURS=24
INSIDER_CELLAR_RATE=1
INSIDER_CELLAR_STALE_HOURS=96
# CJEU judgments (Court of Justice + General Court) from this date on — off by default
# (~25k judgments with a Polish version since 2000: roughly another day of importing).
INSIDER_CELLAR_CASELAW=false
INSIDER_CELLAR_CASELAW_FROM=2000-01-01
# ── OCR (acts published only as PDF) ────────────────────────────────────────
# auto | paddle_vl | paddle | tesseract | off. The core image has the PDF text layer only; the
+32 -4
View File
@@ -100,6 +100,8 @@ backend/alembic/ env + 0001_initial (pgcrypto, create_enum_types, create_all)
scaffold's `record`; re-runs the runtime grants)
+ 0006_indexed_mode (dzu_act, dzu_article, saos_judgment, saos_section,
dataset_sync IF NOT EXISTS; re-runs the runtime grants)
+ 0007_cellar_index (eu_doc, eu_part IF NOT EXISTS; drops the retired
`eurlex_dump` state row; re-runs the runtime grants)
backend/scripts/ license_gate · deploy_check
frontend/ index.html · app.css · app.js · ui/v1/ (the family shell) (no build step)
Tabler icon path data vendored into app.js's ICN map (CREDITS.md)
@@ -135,10 +137,12 @@ backend/app/
· politeness (TokenBucket, CircuitBreaker) · eli · saos · eurlex · registry
· local (LocalAdapter: INDEXED sources, no client) · dzu_md (mirror parsers,
upstream, adapter) · saos_dump (DUMP upstream + SaosIndexAdapter)
· cellar (CELLAR listing rows, records, CellarUpstream, CellarIndexAdapter)
· cellar_builder/ (VENDORED from tseidl/eurlex-builder, MIT: queries, structure)
services/ legal (THE facade REST + MCP call) · federation (fan-out, statuses, dedup)
· cursor (HMAC) · citations (regexes) · cache (LRU + source_cache, single-flight)
· doctext (doc_text + ocr_job queue) · htmltext (sanitise, chunk) · runtime (singleton)
· indexing (importers: dzu_md, eli_inforce, saos_dump, eurlex_dump seam; run_loop)
· indexing (importers: dzu_md, eli_inforce, saos_dump, cellar ×2; run_loop)
· indexstore (Pg + Memory; run lock) · textindex (tantivy) · window (UTC window)
ocr/ engines (text layer, PaddleOCR, PaddleOCR-VL, Tesseract — import-guarded)
· pipeline (tier selection, per-page escalation) · worker (queue; in-process or
@@ -147,6 +151,7 @@ backend/app/
routers/legal.py /search /acts/... /judgments/... /resolve /sources /sources/datasets
models/legal.py source_cache · doc_text · ocr_job (alembic 0005, idempotent)
models/index.py dzu_act · dzu_article · saos_judgment · saos_section · dataset_sync (0006)
· eu_doc · eu_part (0007)
backend/requirements-ocr.txt + Dockerfile.ocr the OPTIONAL OCR image (compose profile `ocr`)
frontend/ui/v1/ the family's shared shell (a copy of Atrium's; don't edit locally)
```
@@ -169,8 +174,22 @@ frontend/ui/v1/ the family's shared shell (a copy of Atrium's; don't edit loca
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
`requirements.txt` (MIT) and import-guarded; the EUR-Lex dump is a seam (`EurlexDumpImporter`),
not implemented until the owner has an EU Login account.
`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
importer uses ONLY the two channels the live adapter uses — SPARQL and the 303 text fetch, on a
`SourceClient` of its own based at `publications.europa.eu`, redirects allowlisted to that host
(`CellarUpstream` refuses any other base) — one request in flight at `INSIDER_CELLAR_RATE` ≤ 2
(every hop counted). Acts IN FORCE only, keyed by the BASE CELEX, holding the text of the NEWEST
consolidated version (`text_celex`); Polish, else English with `language` recorded. A full pass
weekly marks the acts it no longer lists `in_force=false` (tag `nf`: kept, never searched); daily
passes are deltas on `cmr:lastModificationDate`. `CellarIndexAdapter.replaces = "eurlex"` PER
KIND (`covered_kinds`, `federation.plan` narrows live CELLAR to the kinds left), so case law off
never hides CJEU judgments. A CELEX / case-number lookup stays live. Every item keeps the EUR-Lex
`ATTRIBUTION`, `TEXT_NOTE` and the official link; ids stay `eurlex:<CELEX>`. Tables of its own
(`eu_doc`/`eu_part`), not `dzu_act`: an EU act must never be served beside ELI. `cellar_builder/`
is VENDORED (MIT header kept, CREDITS.md): adapt it there, never add eurlex-builder as a
dependency (duckdb/polars/pyarrow/requests, and its HTTP would bypass `SourceClient`).
- **SAOS: two channels, never mixed.** (1) The LIVE search API (`/api/search/...`, robots.txt
disallows `/api/` for crawlers): user-initiated queries only — one request at a time, ≤ 2 req/s
(default 1), no retry of a slow query, identifying User-Agent, behind `INSIDER_SOURCE_SAOS`; never
@@ -202,6 +221,13 @@ frontend/ui/v1/ the family's shared shell (a copy of Atrium's; don't edit loca
spelled-out case forms), drops the commonest legal words, and runs the text match first in a
sub-select capped at `FTS_CANDIDATES` — a short prefix on a frequent stem timed CELLAR out. Don't send the query verbatim again — that is the
"ochrona danych osobowych finds nothing" bug.
- **The index stores Python stems, so `plstem.VERSION` guards it.** Bump it with ANY change to
`stem()`'s output: an index records the version it was built with, one from another version is
not `ready()` (search goes live), `update()` refuses to mix stems, and `indexing.ensure_index`
(every scheduler tick) rebuilds it from Postgres, with no download. The masculine-personal plural
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).
- **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.
@@ -405,4 +431,6 @@ published on **8101** (family scheme: Galena 8021, Sygna 8041, Compass 8061, Cou
8101; on the platform the modules publish nothing).
INDEXED mode (Phase 2, 2026-10-21, branch `indeks`): dziennik-ustaw-md + ELI in-force gap-filler +
SAOS dump into tantivy, off by default (`INSIDER_INDEX_ENABLED`); EUR-Lex dump is a seam only.
SAOS dump into tantivy, off by default (`INSIDER_INDEX_ENABLED`). CELLAR importer (branch
`cellar-import`, 2026-10-21): EU acts in force + optional CJEU case law, replacing the EUR-Lex dump
seam.
+6
View File
@@ -33,6 +33,12 @@ gate (`backend/scripts/license_gate.py`) fails the build on GPL, AGPL or SSPL.
Deliberately **not** used: Surya (GPL + restricted weights), MinerU (AGPL), marker (GPL), PyMuPDF (AGPL)
— the licence gate denies them by name.
## Vendored code
| Project | License | What Insider took |
|---|---|---|
| [eurlex-builder](https://github.com/tseidl/eurlex-builder) (Timo Seidl), commit `4d61904`, 0.3.0 | MIT | the CELLAR SPARQL shapes (type/sector filters, corrigendum and consolidated-CELEX exclusions) and the EUR-Lex XHTML structure pass (`ti-art` / `oj-ti-art` / `title-article-norm` headings, `sti-art` subtitles, annex and stop classes, consolidation markers) — vendored and adapted in `backend/app/integrations/cellar_builder/` (licence header kept). Not a dependency: its closure (duckdb, polars, pyarrow, lxml, SPARQLWrapper, requests…) is far heavier than what Insider uses, and its HTTP would bypass `SourceClient` |
## Data sources
| Source | Terms | Attribution Insider carries |
+22 -5
View File
@@ -83,7 +83,8 @@ act's title weighted ×3 and the query words side by side ×2.
| `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 |
| `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 |
| `eurlex_dump` | **not implemented** — EUR-Lex's bulk data needs an EU Login account | the importer class, switch and status row exist (`services/indexing.EurlexDumpImporter`) |
| `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 |
**How search uses it.** A local source answers only when its index is built and its dataset has
finished a first full import and synced within the staleness threshold (`INSIDER_DZU_MD_STALE_HOURS`,
@@ -101,21 +102,37 @@ live sources answer exactly as before.
number; a court *type*, not a court's name — the dump has no common-court names) — then the
30-second live call is not made, and a judgment opened is read from the dump copy. Otherwise live
SAOS answers, progressively, as before. The Supreme Court notice stays.
* EU law: `cellar` stands **in** for live CELLAR's title search for the kinds it holds ready and
fresh (`INSIDER_CELLAR_STALE_HOURS`) — acts, and judgments when `cellar_caselaw` is on. An
all-kinds search with case law off asks live CELLAR for the judgments only. Hits are full text at
article level ("Artykuł N", annexes), with the attribution "© European Union,
https://eur-lex.europa.eu …", the conversion note (`text_note`), the EUR-Lex link of the act and
of the consolidated text indexed (`extra.text_celex`, `text_url`); opening the act or its text
reads the local copy. A CELEX or case-number lookup, an `in_force=false` filter and a stale index
go live as before. The SPARQL shapes and the HTML structure pass are **vendored from
[tseidl/eurlex-builder](https://github.com/tseidl/eurlex-builder) (MIT)** into
`app/integrations/cellar_builder/` and adapted (Polish headings, the in-force filter, keyset
paging, the delta, stdlib parsing through `SourceClient`) — see CREDITS.md.
* `sources[]` says which source answered (`served_by: index | live`) and each dataset's freshness;
`GET /sources/datasets` (the console's "Źródła" panel) shows per dataset the last sync, commit or
cursor, document count, last error, and `running | idle | off`.
**Off switches**: `INSIDER_INDEX_ENABLED=false` (the default) is LIVE only — nothing downloaded,
nothing opened. With it on, each importer has its own switch (`INSIDER_DZU_MD_SYNC`,
`INSIDER_ELI_INFORCE_SYNC`, `INSIDER_SAOS_DUMP_SYNC`, `INSIDER_EURLEX_DUMP_SYNC`). Importers run as
lifespan tasks that wait first (start-up never imports) and take a per-dataset Postgres advisory
lock (the two act datasets share one: they write one index), so several workers never import the
`INSIDER_ELI_INFORCE_SYNC`, `INSIDER_SAOS_DUMP_SYNC`, `INSIDER_CELLAR_SYNC`,
`INSIDER_CELLAR_CASELAW`). Importers run as lifespan tasks that wait first (start-up never imports)
and take a per-dataset Postgres advisory lock (the two Polish act datasets share one, and so do the
two CELLAR ones: each pair writes one index), so several workers never import the
same dataset twice. The index is disposable: lost with its volume, it is rebuilt from Postgres.
**Disk** (measured on a 30-act / 20-judgment sample, 2026-10-21, then scaled): acts ≈ 0.6 GB in
Postgres + 0.1–0.3 GB of index; the full SAOS dump (~450k judgments) ≈ 10–14 GB in Postgres + 4–6 GB
of index. First imports: `dzu_md` ~7.2k files ≈ 30–60 min; `eli_inforce` ≈ 2–3k acts in force, ~20–40
min; `saos_dump` ≈ 4.6k pages of 100 → about 8–12 nights in the default 6-hour window.
min; `saos_dump` ≈ 4.6k pages of 100 → about 8–12 nights in the default 6-hour window. `cellar`
(counted live 2026-10-21): 35.1k R/L/D works in force (30.4k with a Polish expression; 5.4k have a
consolidated version) → ~76k requests ≈ 21 h at 1 req/s (≈ 11 h at 2); measured on 9 large acts
(GDPR, DSA, AI Act…) 1.16 M characters → 0.9 MB of Postgres and 0.39 MB of index, so ≈ 0.6–1 GB +
0.2–0.4 GB for the whole set. Case law since 2000: ~25.5k CJ/TJ judgments with a Polish version.
### SAOS: user-initiated live queries only
@@ -0,0 +1,47 @@
"""INDEXED mode, CELLAR: `eu_doc`, `eu_part`; and the retired EUR-Lex dump seam's state row.
Idempotent, per the family rule: `0001` builds from the live metadata, so on a fresh database these
tables already exist — hence `CREATE TABLE/INDEX IF NOT EXISTS`, which also renders in `alembic
upgrade head --sql`. A database migrated before this revision gets the real change.
`dataset_sync` may hold an `eurlex_dump` row from the seam this importer replaces (it only ever
reported "not available"); it is deleted so the "Źródła" panel does not show a dataset that no
longer exists.
Ends with the runtime grants: `GRANT ... ON ALL TABLES` only covers the tables that exist when it
runs. Neither table is evidence — the importer replaces rows as CELLAR changes — so the
append-only / no-delete lists are unchanged.
"""
from __future__ import annotations
from dredd_core.schema import runtime_grants_sql
from sqlalchemy.schema import CreateIndex, CreateTable
from alembic import op
from app.config import get_settings
from app.models import APPEND_ONLY_TABLES, NO_DELETE_TABLES, Base
revision = "0007"
down_revision = "0006"
branch_labels = None
depends_on = None
#: parents before children (the foreign key), reversed on the way down
TABLES = ("eu_doc", "eu_part")
def upgrade() -> None:
for name in TABLES:
table = Base.metadata.tables[name]
op.execute(CreateTable(table, if_not_exists=True))
for index in table.indexes:
op.execute(CreateIndex(index, if_not_exists=True))
op.execute("DELETE FROM dataset_sync WHERE name = 'eurlex_dump'")
op.execute(runtime_grants_sql(get_settings().db_app_role,
append_only=APPEND_ONLY_TABLES, no_delete=NO_DELETE_TABLES))
def downgrade() -> None:
op.execute("DELETE FROM dataset_sync WHERE name IN ('cellar', 'cellar_caselaw')")
for name in reversed(TABLES):
op.execute(f"DROP TABLE IF EXISTS {name}")
+20 -3
View File
@@ -161,9 +161,19 @@ class Settings(BaseSettings):
# An incremental pass (sinceModificationDate) is due this long after the previous one finished.
insider_saos_dump_interval_hours: float = Field(default=20.0, ge=1, le=720)
insider_saos_index_stale_hours: float = Field(default=96.0, ge=1)
# The EUR-Lex data-dump importer is NOT implemented yet (it needs an EU Login account): the seam
# (`services/indexing.py`, `EurlexDumpImporter`) exists; on, it only reports "not available".
insider_eurlex_dump_sync: bool = False
# CELLAR (EU law, no account — it replaced the EUR-Lex dump seam, which needed EU Login): the
# regulations, directives and decisions IN FORCE with their newest consolidated text (Polish,
# else English), from the Publications Office's SPARQL endpoint + 303 text fetch. A full pass
# weekly, a delta (CELLAR's modification dates) every interval; one request in flight.
insider_cellar_sync: bool = True
insider_cellar_interval_hours: float = Field(default=24.0, ge=1, le=720)
# requests per second, every redirect hop counted (a text = 2): ≤ 2 by the owner's rule
insider_cellar_rate: float = Field(default=1.0, gt=0, le=2)
# How old the last pass may be before search stops trusting the EU index (→ live CELLAR).
insider_cellar_stale_hours: float = Field(default=96.0, ge=1)
# CJEU judgments (CJ, TJ) dated from INSIDER_CELLAR_CASELAW_FROM on — OFF by default.
insider_cellar_caselaw: bool = False
insider_cellar_caselaw_from: str = "2000-01-01"
# ── OCR (PDF-only acts) ───────────────────────────────────────────────────────
# auto: text layer → PaddleOCR-VL (GPU only) → PaddleOCR PP-OCRv5 (CPU) → Tesseract, escalating
@@ -175,6 +185,13 @@ class Settings(BaseSettings):
# (`python -m app.ocr.worker`, the `ocr` compose profile) does; off = jobs wait.
ocr_worker: str = "inprocess"
@field_validator("insider_cellar_caselaw_from")
@classmethod
def _an_iso_date(cls, v: str) -> str:
import datetime as _dt
_dt.date.fromisoformat(v.strip()) # raises ValueError with the reason
return v.strip()
@field_validator("insider_saos_dump_window")
@classmethod
def _a_utc_window(cls, v: str) -> str:
+330
View File
@@ -0,0 +1,330 @@
"""`cellar` — EU law in force (and, optionally, CJEU case law) as a LOCAL full-text index, built from
the Publications Office's public CELLAR with no account.
Why: EUR-Lex's bulk data dump needs an EU Login account; CELLAR does not. The same two anonymous
channels the live `eurlex` adapter uses are enough to build a corpus, slowly:
* the SPARQL endpoint (`webapi/rdf/sparql`) for the LISTING — every sector-3 regulation (R),
directive (L) and decision (D) with `cdm:resource_legal_in-force` = true, each with its newest
consolidated version (`cdm:act_consolidated_based_on_resource_legal` → the base work; the
consolidated CELEX `0<year><type><number>-<YYYYMMDD>` sorts by date, so MAX is the latest) and
the CELLAR `cmr:lastModificationDate` of both — and for the DAILY DELTA (works, base or
consolidated, whose `lastModificationDate` moved since the last pass);
* content negotiation on `resource/celex/{CELEX}` (303 → `resource/cellar/...`, same host) for
the TEXT — Polish first, English as the fallback, the language recorded.
Predicates confirmed against the live endpoint on 2026-10-21: `resource_legal_in-force` ("1" on
32016R0679), `cmr:lastModificationDate` (on base AND consolidated works), `act_consolidated_based_on
_resource_legal` (02022R2065-20221027 → the DSA's work), `act_consolidated_date`. The SPARQL shapes
and the HTML structure pass are VENDORED from tseidl/eurlex-builder (MIT) into `cellar_builder/`
and adapted there (Polish headings, keyset paging, the in-force filter, the daily delta).
This module holds the fixed host's queries, the parsers, the upstream (`CellarUpstream` — the
importer's ONLY way out; it reuses the live adapter's SPARQL call and 303 text fetch, so the
redirect allowlist is the same one host) and the search ADAPTER, which never goes upstream at all.
"""
from __future__ import annotations
import asyncio
import re
from dataclasses import dataclass, field
from . import plstem
from .base import ACT, EU_COURTS, JUDGMENT, LegalDoc, Query, SearchPage, SourceNotFound, Translation
from .cellar_builder.structure import Part, split_html
from .eurlex import (
_TYPE_NAMES,
ATTRIBUTION,
BASE_URL,
TEXT_NOTE,
EurlexAdapter,
eurlex_url,
valid_celex,
)
from .local import LocalAdapter
DATASET = "cellar" # acts in force
CASELAW = "cellar_caselaw" # CJEU judgments (optional)
INDEX_DIR = "cellar" # one tantivy index for both (one writer: one lock key)
#: a base act this importer indexes: sector 3, a regulation, directive or decision, no suffix
BASE_ACT = re.compile(r"^3\d{4}[RLD]\d{4}$")
#: a judgment of the Court of Justice (CJ) or the General Court (TJ)
JUDGMENT_CELEX = re.compile(r"^6\d{4}(CJ|TJ)\d{4}$")
CONSOLIDATED = re.compile(r"^0\d{4}[RLD]\d{4}-(\d{8})$")
# ── rows → plan ────────────────────────────────────────────────────────────────────────────────────
@dataclass
class Listed:
"""One work as the listing describes it, and which text represents it."""
celex: str
kind: str
type: str | None
date: str | None
in_force: bool
text_celex: str # the newest consolidated version when there is one, else the act
consolidation_date: str | None
modified: str | None # the max of the base's and the text's lastModificationDate
ecli: str | None = None
@property
def fingerprint(self) -> str:
return f"{self.text_celex}|{self.modified or ''}"
def _force(v) -> bool:
return str(v).strip().lower() in ("1", "true")
def listed_act(row: dict) -> Listed | None:
"""A listing row → the act to keep, or None (a corrigendum, an odd CELEX, another type)."""
celex = str(row.get("celex") or "").strip().upper()
if not BASE_ACT.match(celex):
return None
cons = str(row.get("cons") or "").strip().upper()
m = CONSOLIDATED.match(cons) if cons else None
# a consolidated version must be OF this act: 0 + the base's body (never another number)
if m and cons[1:10] != celex[1:]:
m = None
d = m.group(1) if m else None
mods = [x for x in (row.get("mod"), row.get("consmod") if m else None) if x]
return Listed(celex=celex, kind=ACT, type=row.get("type") or celex[5],
date=(row.get("date") or "")[:10] or None, in_force=_force(row.get("force")),
text_celex=cons if m else celex,
consolidation_date=f"{d[:4]}-{d[4:6]}-{d[6:]}" if d else None,
modified=max(mods) if mods else None)
def listed_judgment(row: dict) -> Listed | None:
celex = str(row.get("celex") or "").strip().upper()
if not JUDGMENT_CELEX.match(celex):
return None
return Listed(celex=celex, kind=JUDGMENT, type=row.get("type"),
date=(row.get("date") or "")[:10] or None, in_force=True, text_celex=celex,
consolidation_date=None, modified=row.get("mod"), ecli=row.get("ecli"))
def pick_titles(rows: list[dict]) -> dict[str, str]:
"""{celex: title}, Polish when there is one, else English."""
out: dict[str, tuple[int, str]] = {}
for r in rows:
c = str(r.get("celex") or "").upper()
t = re.sub(r"\s+", " ", str(r.get("title") or "")).strip()
if not c or not t:
continue
rank = 0 if str(r.get("lang", "")).endswith("POL") else 1
if c not in out or rank < out[c][0]:
out[c] = (rank, t)
return {c: t for c, (_r, t) in out.items()}
@dataclass
class EuRecord:
celex: str
kind: str
title: str
type: str | None = None
date: str | None = None
in_force: bool = True
text_celex: str | None = None
consolidation_date: str | None = None
language: str | None = None
ecli: str | None = None
fingerprint: str = ""
parts: list[Part] = field(default_factory=list)
def build_record(item: Listed, title: str | None, html: str | None, language: str | None,
text_celex: str | None = None) -> EuRecord:
"""A listed work and its fetched HTML (or None: no text in Polish or English) → the record."""
parts = split_html(html, item.kind)[1] if html else []
return EuRecord(celex=item.celex, kind=item.kind, title=title or item.celex, type=item.type,
date=item.date, in_force=item.in_force,
text_celex=text_celex or item.text_celex,
consolidation_date=(item.consolidation_date
if (text_celex or item.text_celex) != item.celex else None),
language=language, ecli=item.ecli, fingerprint=item.fingerprint,
parts=parts)
def doc_rows(doc: dict, parts: list[dict]) -> list[dict]:
"""A stored work's parts as index rows: its kind, type and in-force state as exact tags."""
tags = [f"k:{doc['kind']}"]
if doc.get("type"):
tags.append(f"t:{doc['type']}")
if not doc.get("in_force", True):
tags.append("nf")
return [{"group": doc["celex"], "ord": p["ord"], "title": doc.get("title") or "",
"text": p["text"], "date": doc.get("date"), "tags": tags} for p in parts]
# ── the answer ─────────────────────────────────────────────────────────────────────────────────────
def part_label(num: str | None) -> str | None:
if not num:
return None
return num if not num[0].isdigit() else f"Art. {num}"
def to_doc(d: dict, *, snippet: str = "", hits: list[dict] | None = None) -> LegalDoc:
"""A stored work → the normalised `LegalDoc`: the same id as the live `eurlex` source
(`eurlex:<CELEX>`, so the detail routes and dedup are unchanged), the attribution, the
conversion note and the official EUR-Lex link — for the act and for the text actually indexed."""
celex = d["celex"]
kind = d["kind"]
text_celex = d.get("text_celex") or celex
status = None
if kind == ACT:
status = "obowiązujący" if d.get("in_force", True) else "nieobowiązujący"
extra = {"celex": celex, "legal_type": d.get("type"), "ecli": d.get("ecli"),
"language": d.get("language"), "text_celex": text_celex,
"consolidation_date": d.get("consolidation_date"),
"text_url": eurlex_url(text_celex), "text_note": TEXT_NOTE,
"status_source": "cellar", "text_origin": "cellar"}
if text_celex != celex:
extra["current_consolidated"] = text_celex
extra["current_consolidated_url"] = eurlex_url(text_celex)
if d.get("language") and d["language"] != "pl":
extra["language_note"] = f"Brak tekstu po polsku — zindeksowano wersję '{d['language']}'."
if hits is not None:
extra["articles"] = hits
return LegalDoc(
id=f"eurlex:{celex}", source=DATASET, kind=kind, title=d.get("title") or celex,
date=d.get("date"), court_or_publisher="TSUE" if kind == JUDGMENT else "Dziennik Urzędowy UE",
signature=d.get("ecli") or celex, status=status, official_url=eurlex_url(celex),
snippet=snippet or _TYPE_NAMES.get(d.get("type") or "", d.get("type") or ""),
attribution=ATTRIBUTION, extra=extra)
# ── upstream (the importer only) ───────────────────────────────────────────────────────────────────
class CellarUpstream:
"""The importer's only way out: the SPARQL endpoint and the 303 text fetch, through the live
adapter's own code on a client of its own (one in flight, the importer's rate). Its client is
based at the CELLAR host and follows redirects only there (`eurlex.REDIRECT_HOSTS`)."""
def __init__(self, client) -> None:
if client.base_url != BASE_URL:
raise ValueError("the CELLAR client must be based at the Publications Office host")
self.client = client
self._eurlex = EurlexAdapter(client)
async def select(self, sparql: str) -> list[dict]:
return await self._eurlex._select(sparql, retry=True)
async def text_html(self, celex: str) -> tuple[str, str]:
"""(html, language) — Polish, else English; SourceNotFound when neither exists."""
return await self._eurlex.text_html(celex)
async def aclose(self) -> None:
await self.client.aclose()
# ── the adapter (search side: local only) ──────────────────────────────────────────────────────────
class CellarIndexAdapter(LocalAdapter):
"""EU acts in force (and CJEU judgments when that import is on) from the local CELLAR index:
full text, article level, Polish-stemmed. Stands IN for the live `eurlex` title search for the
kinds it covers (`covered_kinds`); live CELLAR answers the rest, and everything when the index
is not ready or stale."""
name = DATASET
datasets = (DATASET, CASELAW)
replaces = "eurlex"
jurisdiction = "eu"
kinds = frozenset({ACT, JUDGMENT})
attribution = ATTRIBUTION
def capabilities(self) -> dict:
return {"kinds": [ACT, JUDGMENT], "full_text": True, "jurisdiction": "eu",
"stemming": "pl (light)", "fallback": "eurlex (live)",
"filters": ["q (full text, article level)", "date_from", "date_to",
"in_force (acts: the index holds acts in force)"],
"coverage": "regulations, directives and decisions in force (newest consolidated "
"text); CJEU judgments when INSIDER_CELLAR_CASELAW is on",
"policy": "built only by the scheduled CELLAR importer", "text_note": TEXT_NOTE}
def _kind_ready(self, kind: str) -> str | None:
if self.index is None or not self.index.ready():
return "the full-text index is not built"
ds = DATASET if kind == ACT else CASELAW
return self._why_not(self.store.sync_state(ds) or {})
def _wanted(self, query: Query) -> set[str]:
kinds = {ACT, JUDGMENT} if query.kind == "all" else {query.kind}
out = set()
if ACT in kinds and query.publisher in (None, "", "EU"):
out.add(ACT)
court = (query.court or "").strip().upper()
if JUDGMENT in kinds and (not court or court in EU_COURTS):
out.add(JUDGMENT)
return out
def covered_kinds(self, query: Query) -> frozenset[str]:
"""The kinds of THIS query the index answers in full (the live source keeps the others)."""
if not self.applies_to(query) or query.act_ref is not None or query.celex \
or query.case_number or not plstem.query_stems(query.q):
return frozenset()
out = set()
for k in self._wanted(query):
if k == ACT and query.in_force is False:
continue # the index holds acts in force; live lists the rest
if self._kind_ready(k) is None:
out.add(k)
return frozenset(out)
def skip_reason(self, query: Query) -> str | None:
if self.covered_kinds(query):
return None
if not plstem.query_stems(query.q) or query.celex or query.case_number:
return "no words to look up (a CELEX or case lookup is live)"
reasons = {k: self._kind_ready(k) for k in sorted(self._wanted(query))}
return "; ".join(f"{k}: {r}" for k, r in reasons.items() if r) or "not an EU query"
def translate(self, query: Query) -> Translation:
kinds = self.covered_kinds(query)
return Translation({"kinds": sorted(kinds)} if kinds else {}, [], skip=not kinds)
async def search(self, query: Query, offset: int, limit: int) -> SearchPage:
return await asyncio.to_thread(self._search, query, offset, limit)
def _search(self, query: Query, offset: int, limit: int) -> SearchPage:
kinds = self.covered_kinds(query)
if not kinds:
return SearchPage([], 0, True)
tags = [f"k:{next(iter(kinds))}"] if len(kinds) == 1 else []
groups, total = self.index.search(query.q, offset=offset, limit=limit,
date_from=query.date_from, date_to=query.date_to,
tags=tags, exclude_tags=("nf",))
found = self.store.get_eu_docs([g["group"] for g in groups])
stems = plstem.query_stems(query.q)
from .dzu_md import make_snippet
docs = []
for g in groups:
d = found.get(g["group"])
if d is None:
continue
parts = self.store.get_eu_parts(d["celex"], [h["ord"] for h in g["hits"]])
hits = [{"ord": h["ord"], "num": parts[h["ord"]]["num"],
"label": part_label(parts[h["ord"]]["num"]), "score": round(h["score"], 3),
"snippet": make_snippet(parts[h["ord"]]["text"], stems)}
for h in g["hits"] if h["ord"] in parts]
snippet = ((f"{hits[0]['label']}: " if hits[0]["label"] else "") + hits[0]["snippet"]
if hits else "")
docs.append(to_doc(d, snippet=snippet, hits=hits))
return SearchPage(docs, total, offset + len(groups) >= total)
async def fetch(self, native_id: str) -> LegalDoc:
found = await asyncio.to_thread(self.local_doc, native_id)
if found is None:
raise SourceNotFound("cellar: not in the local index")
return found[0]
def local_doc(self, celex: str) -> tuple[LegalDoc, str] | None:
"""(document, its indexed plain text) when the index holds this CELEX, else None. No
request. Only while the dataset is ready and fresh: a stale copy is not served."""
try:
celex = valid_celex(celex)
except ValueError:
return None
d = self.store.get_eu_doc(celex)
if d is None or self._kind_ready(d["kind"]) is not None:
return None
parts = self.store.get_eu_parts(celex)
return to_doc(d), "".join(p["text"] for _o, p in sorted(parts.items()))
@@ -0,0 +1,45 @@
# Portions of this package are adapted from eurlex-builder
# (https://github.com/tseidl/eurlex-builder, commit 4d619043d476d8677f17b120fa212cb2a63ca120,
# release 0.3.0), which is distributed under the MIT License:
#
# MIT License
#
# Copyright (c) 2026 Timo Seidl
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software
# and associated documentation files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""The parts of eurlex-builder Insider needs, VENDORED and adapted (not a dependency).
Why vendored: eurlex-builder 0.3.0 is on PyPI and MIT, but it is a research CLI whose closure
(duckdb, polars, pyarrow, lxml, SPARQLWrapper, requests, tqdm, pydantic, pyyaml) is far heavier
than the two things Insider takes from it, and its HTTP goes through its own `requests` session —
around `SourceClient`'s fixed host, redirect allowlist, `trust_env=False`, rate and breaker.
What was taken, and what changed (see each module's docstring):
* `queries` — the SPARQL shape of `sources/cellar.py::_build_descriptive_query` (type + sector
filters, the corrigendum and consolidated-CELEX exclusions). Changed: the in-force filter, keyset
paging on CELEX instead of one unbounded SELECT, each base act's newest consolidated version and
`cmr:lastModificationDate` in the same query, and the DAILY DELTA query (`modified_sparql`) —
eurlex-builder rebuilds by date range and has no incremental mode.
* `structure` — `extractors/html.py`'s structure detection: articles at `ti-art` / `oj-ti-art`
(OJ) and `title-article-norm` (consolidated) paragraphs, the `sti-art` subtitle, the stop classes,
`ti-grseq-1` annex headings, the consolidation markers (▼B ►M1 ◄). Changed: stdlib `html.parser`
instead of lxml, POLISH headings ("Artykuł N", "ZAŁĄCZNIK") as well as English — eurlex-builder
fetches English first and parses English only — and Insider's part shape (position-keyed, cut to
a maximum size), with a plain-text fallback for unstructured HTML.
Not taken: the CLI, DuckDB storage, PDF/Docling extraction, translation, EuroVoc enrichment,
validation, the sub-article splitter and the `requests` session.
"""
UPSTREAM = "tseidl/eurlex-builder@4d619043d476d8677f17b120fa212cb2a63ca120 (0.3.0, MIT)"
@@ -0,0 +1,112 @@
# Adapted from eurlex-builder (MIT, Copyright (c) 2026 Timo Seidl) — see __init__.py for the licence.
"""CELLAR SPARQL for the importer: listing, delta, titles.
From eurlex-builder's `_build_descriptive_query`: sector + `resource_legal_type` filters, the
corrigendum exclusion (a CELEX ending `R(nn)`) and the suffixed CELEX exclusion. Insider's changes:
`resource_legal_in-force`, KEYSET paging on CELEX (never OFFSET — a 35 000-row listing with OFFSET
makes every page cost the whole scan), the newest consolidated version + both
`cmr:lastModificationDate`s in the same page, the VALUES detail form, and `modified_sparql` (the
daily delta). Only validated CELEX numbers and fixed-format dates reach a query — no user text.
"""
from __future__ import annotations
import re
from ..eurlex import _LANG, valid_celex
ACT_TYPES = ("R", "L", "D")
CASE_TYPES = ("CJ", "TJ")
PAGE = 500 # listing rows per SPARQL page
VALUES_BATCH = 100 # CELEX numbers per VALUES detail query
_PREFIX = ("PREFIX cdm: <http://publications.europa.eu/ontology/cdm#>\n"
"PREFIX cmr: <http://publications.europa.eu/ontology/cdm/cmr#>\n"
"PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n")
_ISO_TS = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$")
_DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
#: eurlex-builder's corrigendum filter, and its "no suffixed CELEX" rule (summaries, `_RES`)
_NOT_CORRIGENDUM = 'FILTER(!REGEX(STR(?celex), "R\\\\([0-9]+\\\\)$"))'
_NO_SUFFIX = 'FILTER(!CONTAINS(STR(?celex), "_"))'
def _values(celexes: list[str]) -> str:
return " ".join(f'"{valid_celex(c)}"' for c in celexes)
def _after(after: str | None) -> str:
return f'FILTER(STR(?celex) > "{valid_celex(after)}")' if after else ""
def _since(since: str) -> str:
if not _ISO_TS.match(since or ""):
raise ValueError("since is YYYY-MM-DDTHH:MM:SSZ")
return f'"{since}"^^xsd:dateTime'
def _pick(sector: str, after: str | None, celexes: list[str] | None) -> str:
if celexes:
return (f"VALUES ?cx {{ {_values(celexes)} }} ?w cdm:resource_legal_id_celex ?celex . "
"FILTER(STR(?celex) = ?cx)")
return (f'?w cdm:resource_legal_id_sector ?s . FILTER(STR(?s) = "{sector}")\n'
f" ?w cdm:resource_legal_id_celex ?celex . {_NO_SUFFIX} {_NOT_CORRIGENDUM}\n "
+ _after(after))
def acts_listing_sparql(after: str | None = None, limit: int = PAGE,
celexes: list[str] | None = None) -> str:
"""One page of base acts IN FORCE (keyset on CELEX), each with its newest consolidated version
(`act_consolidated_based_on_resource_legal`; the CELEX `0…-YYYYMMDD` sorts by date, so MAX is
the latest) and both modification dates. With `celexes`: those works, in force or not."""
force = ("OPTIONAL { ?w cdm:resource_legal_in-force ?force }" if celexes else
'?w cdm:resource_legal_in-force ?force . FILTER(STR(?force) IN ("1", "true"))')
types = ", ".join(f'"{t}"' for t in ACT_TYPES)
return (_PREFIX + "SELECT ?celex ?type ?date ?force ?mod (MAX(STR(?cc)) AS ?cons) "
"(MAX(STR(?cmod)) AS ?consmod) WHERE {\n"
" { SELECT ?w ?celex ?type ?date ?force ?mod WHERE {\n "
f"{_pick('3', after, celexes)}\n {force}\n"
f" ?w cdm:resource_legal_type ?type . FILTER(STR(?type) IN ({types}))\n"
" OPTIONAL { ?w cdm:work_date_document ?date }\n"
" OPTIONAL { ?w cmr:lastModificationDate ?mod }\n"
f" }} ORDER BY ?celex LIMIT {int(limit)} }}\n"
" OPTIONAL { ?c cdm:act_consolidated_based_on_resource_legal ?w ; "
"cdm:resource_legal_id_celex ?cc . OPTIONAL { ?c cmr:lastModificationDate ?cmod } }\n"
"} GROUP BY ?celex ?type ?date ?force ?mod ORDER BY ?celex")
def caselaw_listing_sparql(date_from: str, after: str | None = None, limit: int = PAGE,
celexes: list[str] | None = None) -> str:
"""One page of CJ/TJ judgments dated `date_from` or later (keyset on CELEX), ECLI and dates."""
if not _DATE.match(date_from or ""):
raise ValueError("date_from is YYYY-MM-DD")
types = ", ".join(f'"{t}"' for t in CASE_TYPES)
return (_PREFIX + "SELECT ?celex ?type ?date ?mod ?ecli WHERE {\n "
f"{_pick('6', after, celexes)}\n"
f" ?w cdm:resource_legal_type ?type . FILTER(STR(?type) IN ({types}))\n"
f' ?w cdm:work_date_document ?date . FILTER(?date >= "{date_from}"^^xsd:date)\n'
" OPTIONAL { ?w cmr:lastModificationDate ?mod }\n"
" OPTIONAL { ?w cdm:case-law_ecli ?ecli }\n"
f"}} ORDER BY ?celex LIMIT {int(limit)}")
def modified_sparql(sector: str, since: str, after: str | None = None, limit: int = PAGE) -> str:
"""The DELTA (Insider's addition): works of the sector whose `cmr:lastModificationDate` — or,
for acts, that of one of their consolidated versions — is at or after `since`, in force or
not. Seen live (2026-10-21): three days of changes = 40 works, answered in 1.5 s."""
if sector not in ("3", "6"):
raise ValueError("sector 3 or 6")
cons = (" UNION { ?c cmr:lastModificationDate ?m . FILTER(?m >= " + _since(since) + ") "
"?c cdm:act_consolidated_based_on_resource_legal ?w . }" if sector == "3" else "")
return (_PREFIX + "SELECT DISTINCT ?celex WHERE {\n"
f" {{ ?w cmr:lastModificationDate ?m . FILTER(?m >= {_since(since)}) }}{cons}\n"
f' ?w cdm:resource_legal_id_sector ?s . FILTER(STR(?s) = "{sector}")\n'
f" ?w cdm:resource_legal_id_celex ?celex . {_NO_SUFFIX}\n "
f"{_after(after)}\n}} ORDER BY ?celex LIMIT {int(limit)}")
def titles_sparql(celexes: list[str]) -> str:
"""The Polish and English titles of these works (the expressions' `expression_title`)."""
return (_PREFIX + "SELECT ?celex ?lang ?title WHERE {\n"
f" VALUES ?cx {{ {_values(celexes)} }} ?w cdm:resource_legal_id_celex ?celex . "
"FILTER(STR(?celex) = ?cx)\n"
" ?e cdm:expression_belongs_to_work ?w ; cdm:expression_uses_language ?lang ; "
"cdm:expression_title ?title .\n"
f" FILTER(?lang IN (<{_LANG}POL>, <{_LANG}ENG>))\n}}")
@@ -0,0 +1,158 @@
# Adapted from eurlex-builder (MIT, Copyright (c) 2026 Timo Seidl) — see __init__.py for the licence.
"""An EU text's HTML → Insider's position-keyed parts (preamble, articles, annexes).
From eurlex-builder's `extractors/html.py`: the structure classes of the Publications Office's
XHTML — article headings `ti-art` / `oj-ti-art` (Official Journal) and `title-article-norm`
(consolidated texts), subtitles `sti-art` / `oj-sti-art` / `stitle-article-norm` (kept in the
article's body), annex headings `ti-grseq-1` / `oj-ti-grseq-1` / `title-annex-1` that read "ANNEX",
the stop classes (signatory, final, doc-end…) and the consolidation markers (▼B ►M1 ◄).
Insider's changes: the stdlib parser of `services/htmltext.py` (no lxml — the same sanitiser every
other text goes through, so no markup survives), POLISH headings ("Artykuł N", "ZAŁĄCZNIK") as well
as English, and the part shape — ord = position (numbers can repeat), oversized pieces cut at line
boundaries, nothing dropped (joined in order the parts give the whole text back). An HTML with none
of those classes (older texts, plain `text/html`) falls back to "Artykuł N" / "Article N" alone on
a line.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from ...services.htmltext import _Extractor, html_to_text
ACT = "act"
_MARK = "" # a private-use character: never in a source text
ART_CLASSES = frozenset({"ti-art", "oj-ti-art", "title-article-norm"})
ANNEX_CLASSES = frozenset({"ti-grseq-1", "oj-ti-grseq-1", "title-annex-1"})
STOP_CLASSES = frozenset({"signatory", "oj-signatory", "final", "oj-final", "doc-end", "doc-sep"})
_HEAD_NUM = re.compile(r"^(?:Artykuł|Article)\s+(\d+[a-z]{0,3})\b")
_SOLE = re.compile(r"^(?:Artykuł jedyny|Sole Article)", re.I)
_ANNEX_HEAD = re.compile(r"^(?:ZAŁĄCZNIK|ANNEX)\b", re.I)
#: the plain-text fallback: a heading alone on its line
_ART_LINE = re.compile(r"^(?:Artykuł|Article)\s+(\d+[a-z]{0,3})\s*$")
_ANNEX_LINE = re.compile(r"^(?:ZAŁĄCZNIK|ANNEX)(?:\s+[IVXLC\d]+[a-z]?)?\s*$")
#: consolidation markers (eurlex-builder's `_CONSOLIDATED_MARKER_RE`, plus the inline forms)
_MARKER_LINE = re.compile(r"^[▼►▲◄]\s*[A-Z]{0,2}\d*\s*$", re.M)
_MARKER_INLINE = re.compile(r"[►▼▲]\s*[A-Z]{1,2}\d*\s*|◄")
#: a part larger than this is cut further at line boundaries (a preamble of 173 recitals, an annex)
PART_MAX = 12_000
@dataclass
class Part:
ord: int
num: str | None # "5", "17a", "ZAŁĄCZNIK I"; None for the preamble and the tail
text: str
class _Structured(_Extractor):
"""The sanitiser, plus a marker line before every structural paragraph."""
def handle_starttag(self, tag, attrs):
if not self._drop:
classes = set((dict(attrs).get("class") or "").split())
if classes & ART_CLASSES:
self.parts.append(f"\n{_MARK}A\n")
elif classes & ANNEX_CLASSES:
self.parts.append(f"\n{_MARK}X\n")
elif classes & STOP_CLASSES:
self.parts.append(f"\n{_MARK}S\n")
super().handle_starttag(tag, attrs)
def clean(text: str) -> str:
text = _MARKER_LINE.sub("", text)
text = _MARKER_INLINE.sub("", text)
return re.sub(r"\n{3,}", "\n\n", text).strip() + "\n"
def _cut(text: str, limit: int = PART_MAX) -> list[str]:
if len(text) <= limit:
return [text]
out, cur = [], ""
lines = [ln[i:i + limit] for ln in text.splitlines(keepends=True)
for i in range(0, len(ln), limit)] # a single huge line is cut too
for line in lines:
if cur and len(cur) + len(line) > limit:
out.append(cur)
cur = ""
cur += line
if cur:
out.append(cur)
return out
def _next_line(lines: list[str], i: int) -> str:
for line in lines[i + 1:]:
if line.strip() and not line.startswith(_MARK):
return line.strip()
return ""
def _pieces_structured(lines: list[str]) -> list[tuple[str | None, list[str]]] | None:
"""Cut at the marker lines; None when the HTML had no article markers at all."""
if not any(line == f"{_MARK}A" for line in lines):
return None
pieces: list[tuple[str | None, list[str]]] = [(None, [])]
for i, line in enumerate(lines):
if line.startswith(_MARK):
kind = line[1:]
head = _next_line(lines, i)
if kind == "A":
m = _HEAD_NUM.match(head)
num = m.group(1) if m else ("jedyny" if _SOLE.match(head) else None)
pieces.append((num, []))
elif kind == "X" and _ANNEX_HEAD.match(head):
pieces.append((head[:40], []))
elif kind == "S":
pieces.append((None, []))
continue
pieces[-1][1].append(line)
return pieces
def _pieces_plain(lines: list[str]) -> list[tuple[str | None, list[str]]]:
pieces: list[tuple[str | None, list[str]]] = [(None, [])]
seen_article = False
for line in lines:
m = _ART_LINE.match(line.strip())
if m:
seen_article = True
pieces.append((m.group(1), []))
elif seen_article and _ANNEX_LINE.match(line.strip()):
pieces.append((line.strip()[:40], []))
pieces[-1][1].append(line)
return pieces
def split_text(text: str, kind: str = ACT) -> list[Part]:
"""Plain text → parts ("Artykuł N" / "Article N" lines). A judgment: by size only."""
lines = clean(text).splitlines(keepends=False)
pieces = _pieces_plain(lines) if kind == ACT else [(None, lines)]
return _parts(pieces)
def split_html(html: str, kind: str = ACT) -> tuple[str, list[Part]]:
"""(plain text, parts) of an EU HTML text: the structure classes first, the plain-text
headings when there are none. A judgment has no articles: cut by size only."""
if kind != ACT:
text = clean(html_to_text(html))
return text, _parts([(None, text.splitlines())])
marked = clean(html_to_text(html, _Structured))
lines = marked.splitlines()
pieces = _pieces_structured(lines) or _pieces_plain(
[ln for ln in lines if not ln.startswith(_MARK)])
parts = _parts(pieces)
return "".join(p.text for p in parts), parts
def _parts(pieces: list[tuple[str | None, list[str]]]) -> list[Part]:
out: list[Part] = []
for num, lines in pieces:
body = "\n".join(ln for ln in lines if not ln.startswith(_MARK)).strip("\n")
if not body.strip():
continue
for piece in _cut(body + "\n\n"):
out.append(Part(len(out), num, piece))
return out
+44 -5
View File
@@ -11,8 +11,16 @@ What it does — on purpose, nothing clever:
leaving a stem shorter than `MIN_STEM` characters;
* fold the diacritics of the stem (ą→a, ć→c, ę→e, ł→l, ń→n, ó→o, ś→s, ź/ż→z), so "ochronie",
"ochrona", "ochroną" and "ochrony" all become `ochron`, and "osobowych"/"osobowe" `osob`.
It does not handle stem alternations (ręka/ręce, Polska/polski): an under-stemmed query finds less,
it never finds nonsense. `light_stem` strips only the case ending and keeps the diacritics — it is what
Consonant alternations are handled only where they are regular and safe (`_alternate`, 2026-10-21):
the masculine-personal plurals get the singular's stem — sygnaliści/sygnalista `sygnalist`,
studenci/student, autorzy/autor, prawnicy/prawnik, biolodzy/biolog — while words that merely end
the same way keep theirs (części, granicy, młodzy, narzędzi, lekarzy, żołnierzy). Other alternations
(ręka/ręce, Polska/polski) are not handled: an under-stemmed query finds less, it never finds
nonsense. si↔s needs no rule (prezesi → `prezes` by the -i ending), and a soft dzi is one stem
(sędzia/sędziów/sędziego → `sedz`).
`VERSION` changes whenever the stems change: an index records the version it was built with, and
one built with another is not "ready" — it is rebuilt from Postgres (`textindex`, `indexing`). `light_stem` strips only the case ending and keeps the diacritics — it is what
goes to ELI's title filter, which matches substrings of the original title.
"""
from __future__ import annotations
@@ -20,6 +28,8 @@ from __future__ import annotations
import re
MIN_STEM = 3
#: bumped when `stem()` changes its output: every tantivy index is rebuilt from Postgres
VERSION = 2
_FOLD = str.maketrans("ąćęłńóśźż", "acelnoszz")
_WORD = re.compile(r"[0-9a-ząćęłńóśźż]+", re.IGNORECASE)
@@ -64,12 +74,39 @@ def light_stem(word: str) -> str:
return _strip(w, _INFLECTION, MIN_STEM + 1)
#: masculine-personal plural endings → the singular's stem end (raw word, before folding). Each one
#: is narrow on purpose: "-ści" alone would turn części into `czest` (= częsty), "-nicy" granicy
#: into `granik`, "-odzy" młodzy into `młog`, "-arzy"/"-erzy" the genitive lekarzy/żołnierzy.
_PLURAL = (("iści", "ist"), ("yści", "yst"), ("enci", "ent"), ("anci", "ant"), ("aci", "at"),
("olodzy", "olog"), ("orzy", "or"))
#: k ↔ c before -y/-i (prawnik / prawnicy, polityk / politycy): every form of such a word is
#: folded onto the c-stem, so singular and plural meet whichever one is asked
_K_TO_C = (("nik", "nic"), ("yk", "yc"), ("ik", "ic"))
def _alternate(w: str) -> str | None:
for end, sing in _PLURAL:
# "bi"-olodzy is two letters before the ending; every other rule wants MIN_STEM
if w.endswith(end) and len(w) - len(end) >= (2 if end == "olodzy" else MIN_STEM):
return w[: -len(end)] + sing
return None
def stem(word: str) -> str:
"""The index/query stem: one ending off (inflectional or adjectival), then folded."""
"""The index/query stem: one ending off (inflectional or adjectival), consonant alternations of
the masculine-personal plural normalised, then folded."""
w = word.lower()
if w.isdigit() or len(w) <= MIN_STEM:
return fold(w)
return fold(_strip(w, _ALL, MIN_STEM))
s = _alternate(w) or _strip(w, _ALL, MIN_STEM)
if s.endswith("dzi") and len(s) >= 5:
s = s[:-1] # the soft dz: sędzia, sędziów, sędziego → `sedz`
if len(s) >= 5:
for end, to in _K_TO_C:
if s.endswith(end):
s = s[: -len(end)] + to
break
return fold(s)
def words(text: str) -> list[str]:
@@ -129,5 +166,7 @@ def title_matches(title: str, q: str) -> bool:
"""True when every query stem starts a word of the (folded) title — the client-side filter
that makes ELI's substring title search inflection-aware."""
want = query_stems(q)
have = [fold(w) for w in words(title)]
# the folded word itself, and its stem (a normalised alternation — `prawnic` for "prawnik" —
# is not a prefix of the word as written)
have = [form for w in words(title) for form in (fold(w), stem(w))]
return all(any(h.startswith(s) for h in have) for s in want)
+2 -2
View File
@@ -13,8 +13,8 @@ from .base import SourceAdapter
from .http import SourceClient
#: the order of `sources[]`; a local (INDEXED) source sits just before the live one it stands
#: beside (dzu_md → eli) or in for (saos_index → saos)
ORDER = ("dzu_md", "eli", "saos_index", "saos", "eurlex")
#: beside (dzu_md → eli) or in for (saos_index → saos; cellar → eurlex, per kind)
ORDER = ("dzu_md", "eli", "saos_index", "saos", "cellar", "eurlex")
class Registry:
+3 -3
View File
@@ -23,7 +23,7 @@ Leave them alone rather than trying to drop them — a later move to tree tenanc
using them.
Insider's own models are in `.legal` (source_cache, doc_text, ocr_job) and `.index` (INDEXED mode:
dzu_act, dzu_article, saos_judgment, saos_section, dataset_sync).
dzu_act, dzu_article, saos_judgment, saos_section, dataset_sync; 0007: eu_doc, eu_part).
"""
from dredd_core import (
AppSetting,
@@ -38,7 +38,7 @@ from dredd_core import (
pg_enum,
)
from .index import DatasetSync, DzuAct, DzuArticle, SaosJudgment, SaosSection
from .index import DatasetSync, DzuAct, DzuArticle, EuDoc, EuPart, SaosJudgment, SaosSection
from .legal import DocText, OcrJob, SourceCacheEntry
# ── evidence tables: what the runtime role may never rewrite ──────────────────────────────────────
@@ -62,6 +62,6 @@ __all__ = [
# shared=SHARED_IDENTITY_TABLES)` would be excluding a name this app never imported.
"AppUser", "Session", "ModulePermission", "AppSetting", "AuditLog",
"SourceCacheEntry", "DocText", "OcrJob",
"DzuAct", "DzuArticle", "SaosJudgment", "SaosSection", "DatasetSync",
"DzuAct", "DzuArticle", "SaosJudgment", "SaosSection", "DatasetSync", "EuDoc", "EuPart",
"APPEND_ONLY_TABLES", "NO_DELETE_TABLES",
]
+44 -1
View File
@@ -11,7 +11,13 @@ only by the scheduled importers (`services/indexing.py`), never by a request:
* `saos_judgment` / `saos_section` — the SAOS DUMP API (`/api/dump/judgments`), which SAOS offers
for bulk download; the judgment's metadata, and its sanitised plain text cut into sections
(sentence, reasons, ~6 000-character pieces). Never the live search API's answers, never HTML.
* `dataset_sync` — one row per dataset (`dzu_md`, `saos_dump`, later `eurlex_dump`): the commit
* `eu_doc` / `eu_part` — CELLAR (alembic 0007): EU acts in force with the text of their newest
consolidated version, and optionally CJEU judgments, cut into articles / pieces. Tables of their
own rather than `dzu_act` with an origin: the key is a CELEX, not an ELI (`year`/`pos` are
NOT NULL there), the dzu_md adapter must never serve an EU act beside ELI, and the EU index is a
separate tantivy directory with its own lock-free rebuild.
* `dataset_sync` — one row per dataset (`dzu_md`, `eli_inforce`, `saos_dump`, `cellar`,
`cellar_caselaw`): the commit
or cursor reached, counts, the last error, a heartbeat. What the "Źródła" panel shows.
Postgres is the source of truth; the tantivy indexes under `INSIDER_INDEX_DIR` are disposable and
@@ -123,3 +129,40 @@ class DatasetSync(Base):
changed: Mapped[int] = mapped_column(Integer, nullable=False, server_default="0")
progress: Mapped[dict | None] = mapped_column(JSONB)
error: Mapped[str | None] = mapped_column(Text)
class EuDoc(Base):
"""`cellar`: one EU act in force (keyed by its BASE CELEX, holding the text of its newest
consolidated version — `text_celex`) or one CJEU judgment, from CELLAR (alembic 0007)."""
__tablename__ = "eu_doc"
celex: Mapped[str] = mapped_column(Text, primary_key=True) # 32016R0679
kind: Mapped[str] = mapped_column(Text, nullable=False) # act | judgment
type: Mapped[str | None] = mapped_column(Text) # R L D | CJ TJ
title: Mapped[str] = mapped_column(Text, nullable=False)
date: Mapped[str | None] = mapped_column(Text) # work_date_document
in_force: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default="true")
#: the CELEX whose text is stored: the newest consolidated version (0…-YYYYMMDD) or the act
text_celex: Mapped[str | None] = mapped_column(Text)
consolidation_date: Mapped[str | None] = mapped_column(Text)
#: the language of the stored text: pl, else en (the fallback); None = no text in either
language: Mapped[str | None] = mapped_column(Text)
ecli: Mapped[str | None] = mapped_column(Text)
#: text_celex|lastModificationDate — a different value means "fetch this work again"
fingerprint: Mapped[str] = mapped_column(Text, nullable=False)
#: the full listing pass that last saw this act in force (a pass that misses it marks it)
pass_id: Mapped[str | None] = mapped_column(Text)
updated_at: Mapped[dt.datetime] = mapped_column(DateTime(timezone=True), nullable=False,
server_default=func.now())
__table_args__ = (Index("ix_eu_doc_kind", "kind", "in_force"),)
class EuPart(Base):
__tablename__ = "eu_part"
celex: Mapped[str] = mapped_column(Text, ForeignKey("eu_doc.celex", ondelete="CASCADE"),
primary_key=True)
ord: Mapped[int] = mapped_column(Integer, primary_key=True)
num: Mapped[str | None] = mapped_column(Text) # "5", "ZAŁĄCZNIK I"
text: Mapped[str] = mapped_column(Text, nullable=False)
+46 -11
View File
@@ -75,17 +75,47 @@ async def _page(cache: SourceCache, adapter, query: Query, offset: int, limit: i
return await cache.get_or_fetch(key, TTL_SEARCH, fetch)
def standby(registry, query: Query) -> dict[str, str]:
"""The live sources a local (INDEXED) source stands in for on THIS query: {live name: why}.
`saos_index` replaces `saos` when its dump index is ready, fresh and covers the whole query —
then the slow live call is not made at all. Otherwise nothing is replaced."""
out: dict[str, str] = {}
def _covered(adapter, query: Query) -> frozenset[str]:
"""The kinds of this query a local source answers in full (all of its kinds, or none, unless
it says otherwise with `covered_kinds` — the CELLAR index covers acts and judgments apart)."""
if hasattr(adapter, "covered_kinds"):
return frozenset(adapter.covered_kinds(query))
return frozenset() if adapter.translate(query).skip else frozenset(adapter.kinds)
def _requested(adapter, query: Query) -> frozenset[str]:
return frozenset(adapter.kinds) if query.kind == "all" else frozenset({query.kind}) & adapter.kinds
def plan(registry, query: Query) -> tuple[dict[str, str], dict[str, Query]]:
"""What the local (INDEXED) sources take over on THIS query: ({live name: why} for a live
source not asked at all, {live name: narrowed query} for one asked only for the kinds the index
does not cover). `saos_index` replaces `saos` when its dump index is ready, fresh and covers
the whole query; `cellar` replaces `eurlex` for acts, judgments or both — whichever kinds its
datasets hold ready and fresh — and live CELLAR keeps the rest."""
replaced: dict[str, str] = {}
narrowed: dict[str, Query] = {}
for name in registry.names():
a = registry.get(name)
target = getattr(a, "replaces", "") if a is not None else ""
if target and not a.translate(query).skip:
out[target] = f"answered by the local index ({name})"
return out
live = registry.get(target) if target else None
if not target:
continue
covered = _covered(a, query)
if not covered:
continue
need = _requested(live, query) if live is not None else covered
if need <= covered:
replaced[target] = f"answered by the local index ({name})"
elif need & covered:
from dataclasses import replace
narrowed[target] = replace(query, kind=sorted(need - covered)[0])
return replaced, narrowed
def standby(registry, query: Query) -> dict[str, str]:
"""The live sources a local (INDEXED) source stands in for on THIS query: {live name: why}."""
return plan(registry, query)[0]
def slow_sources(registry, query: Query) -> list[str]:
@@ -124,13 +154,15 @@ async def search(registry, cache: SourceCache, codec: CursorCodec, query: Query,
tasks: dict[asyncio.Task, tuple[str, float]] = {}
translations = {}
deferred: list[dict] = []
replaced = standby(registry, query)
replaced, narrowed = plan(registry, query)
asked: dict[str, Query] = {}
for name in registry.names():
adapter = registry.get(name)
if adapter is None:
statuses[name] = SourceStatus(name, "disabled")
continue
t = adapter.translate(query)
asked[name] = narrowed.get(name, query) # a live source keeps what the index does not
t = adapter.translate(asked[name])
translations[name] = t
offset = offsets.get(name, 0) if cursor else 0
if name in replaced:
@@ -151,7 +183,7 @@ async def search(registry, cache: SourceCache, codec: CursorCodec, query: Query,
detail="slow source: its results follow")
deferred.append({"source": name, "offset": offset})
continue
task = asyncio.create_task(_page(cache, adapter, query, offset, limit))
task = asyncio.create_task(_page(cache, adapter, asked[name], offset, limit))
tasks[task] = (name, time.monotonic())
next_offsets: dict[str, int | None] = {n: None for n in statuses}
@@ -182,6 +214,9 @@ async def search(registry, cache: SourceCache, codec: CursorCodec, query: Query,
found = [LegalDoc.from_dict(d) for d in page["docs"]]
(ranked if getattr(registry.get(name), "ranked", False) else docs).extend(found)
statuses[name] = SourceStatus(name, "ok", latency, page.get("total"), unsupported,
detail=(f"only {narrowed[name].kind}s: the local "
"index answers the rest")
if name in narrowed else None,
served_by=_served(registry.get(name)),
freshness=_freshness(registry.get(name)))
next_offsets[name] = (None if page.get("exhausted")
+3 -2
View File
@@ -52,8 +52,9 @@ _LINES = re.compile(r"\n\s*\n\s*\n+")
_CTRL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
def html_to_text(html: str) -> str:
parser = _Extractor()
def html_to_text(html: str, parser_cls: type[_Extractor] = _Extractor) -> str:
"""`parser_cls`: a subclass that adds markers of its own (the CELLAR structure pass)."""
parser = parser_cls()
parser.feed(html or "")
parser.close()
text = _CTRL.sub("", "".join(parser.parts))
+262 -30
View File
@@ -17,9 +17,10 @@ advisory lock), so with several workers exactly one imports and the others skip
saved after every page, so a restart, a closed window or a crash resumes where it stopped. A
pass ends when the dump has no `next` page; the next pass asks `sinceModificationDate` = when
this one STARTED (minus a margin), so nothing modified during a pass is missed.
* `EurlexDumpImporter` — the SEAM. EUR-Lex's data dump needs an EU Login account the owner has not
created yet; the class, its config switch and its status row exist so the real importer is a
drop-in (fill `run_once` + an `EurlexIndexAdapter`, register both) — today it only reports.
* `CellarImporter` — EU law from CELLAR, no account (it replaced the EUR-Lex dump seam, which
needed an EU Login account): acts in force with their newest consolidated text and, behind its
own switch, CJEU judgments; a FULL pass weekly, a DELTA (CELLAR's modification dates) daily,
the cursor saved after every page, one request in flight at `INSIDER_CELLAR_RATE`.
Nothing here is reachable from a request: no route starts an import, and no search waits for one.
"""
@@ -31,9 +32,11 @@ import logging
import re
from typing import Protocol
from ..integrations import cellar as cellar_mod
from ..integrations import dzu_md as dzu
from ..integrations import saos_dump
from ..integrations.base import SourceError
from ..integrations.base import ACT, SourceError
from ..integrations.cellar_builder import queries as cellar_q
from .htmltext import html_to_text
from .indexstore import utcnow
from .window import in_window
@@ -467,26 +470,219 @@ class EliInForceImporter(_Base):
"removed": len(gone), "failed": failed, "without_text": missing_text}
# ── EUR-Lex dump: the seam ──────────────────────────────────────────────────────────────────────────
class EurlexDumpImporter(_Base):
"""Not implemented: EUR-Lex's bulk data needs an EU Login account. On, it reports so; the real
importer replaces `run_once` (and adds an `EurlexIndexAdapter` with `replaces = "eurlex"` or
beside it) without touching the scheduler, the store's state table or the panel."""
name = "eurlex_dump"
label = "EUR-Lex (zrzut danych — wymaga konta EU Login)"
off_reason = "INSIDER_EURLEX_DUMP_SYNC=false (importer not available yet)"
# ── CELLAR (EU acts in force; CJEU case law) ───────────────────────────────────────────────────────
#: a full listing pass (which also finds acts that left force) at least this often; daily passes
#: in between are DELTAS (works CELLAR modified since the last pass)
FULL_EVERY = dt.timedelta(days=7)
def _ts(t: dt.datetime) -> str:
return t.astimezone(dt.UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
def _parse_ts(v: str | None) -> dt.datetime | None:
try:
return dt.datetime.strptime(v, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=dt.UTC) if v else None
except ValueError:
return None
class CellarImporter(_Base):
"""EU law from CELLAR, no account: SPARQL for the listing and the delta, the 303 text fetch for
the texts (Polish, else English — the language recorded). One instance per kind:
* `act` (`cellar`): every regulation, directive and decision IN FORCE, each with the text of
its NEWEST consolidated version when there is one (else the act as published);
* `judgment` (`cellar_caselaw`, off by default): CJ/TJ judgments from `date_from` on.
A pass is FULL (the whole listing, keyset-paged by CELEX; acts the listing no longer returns are
marked out of force) on the first run and every `FULL_EVERY`, otherwise a DELTA (the works whose
— or whose consolidated versions' — `cmr:lastModificationDate` moved since the previous pass
STARTED, minus a margin; one detail query per 100 of them; acts now out of force are marked).
Only a work whose fingerprint (text CELEX | modification date) changed is fetched. The cursor
is saved after every page, so a restart resumes where it stopped; one request in flight at the
client's rate (`INSIDER_CELLAR_RATE`, ≤ 2 req/s, every redirect hop counted)."""
def __init__(self, store, index, upstream, *, kind: str, on: bool, interval_hours: float,
date_from: str = "2000-01-01", max_docs: int | None = None,
clock=utcnow) -> None:
self.kind = kind
self.name = cellar_mod.DATASET if kind == ACT else cellar_mod.CASELAW
self.label = ("EUR-Lex — akty obowiązujące (CELLAR, teksty skonsolidowane)" if kind == ACT
else f"EUR-Lex — orzecznictwo TSUE od {date_from[:4]} (CELLAR)")
self.off_reason = ("INSIDER_CELLAR_SYNC=false" if kind == ACT
else "INSIDER_CELLAR_CASELAW=false")
super().__init__(store, index, on=on, clock=clock)
self.upstream = upstream
self.interval = dt.timedelta(hours=interval_hours)
self.date_from = date_from
self.max_docs = max_docs
def due(self, now: dt.datetime) -> bool:
return False
st = self.state()
if (st.get("cursor") or {}).get("mode"): # a pass in progress: carry on
return True
last = st.get("synced_at")
return last is None or now - last >= self.interval
# ── upstream steps ──
def _parse(self, row: dict):
return (cellar_mod.listed_act if self.kind == ACT else cellar_mod.listed_judgment)(row)
def _listing(self, after: str | None = None, celexes: list[str] | None = None) -> str:
from ..integrations.cellar_builder import queries as q
if self.kind == ACT:
return q.acts_listing_sparql(after, celexes=celexes)
return q.caselaw_listing_sparql(self.date_from, after, celexes=celexes)
async def _page_full(self, after: str | None) -> tuple[list, int, str | None]:
rows = await self.upstream.select(self._listing(after))
last = max((str(r.get("celex") or "") for r in rows), default=None)
return [x for r in rows if (x := self._parse(r)) is not None], len(rows), last
async def _page_delta(self, since: str, after: str | None) -> tuple[list, int, str | None]:
from ..integrations.cellar_builder import queries as q
rows = await self.upstream.select(
q.modified_sparql("3" if self.kind == ACT else "6", since, after))
raw = [str(r.get("celex") or "").upper() for r in rows]
keep = cellar_mod.BASE_ACT if self.kind == ACT else cellar_mod.JUDGMENT_CELEX
wanted = [c for c in raw if keep.match(c)]
items: list = []
for i in range(0, len(wanted), q.VALUES_BATCH):
batch = wanted[i:i + q.VALUES_BATCH]
items += [x for r in await self.upstream.select(self._listing(celexes=batch))
if (x := self._parse(r)) is not None]
return items, len(rows), max(raw, default=None)
async def _titles(self, celexes: list[str]) -> dict[str, str]:
from ..integrations.cellar_builder import queries as q
out: dict[str, str] = {}
for i in range(0, len(celexes), q.VALUES_BATCH):
out |= cellar_mod.pick_titles(
await self.upstream.select(q.titles_sparql(celexes[i:i + q.VALUES_BATCH])))
return out
async def _text(self, item) -> tuple[str | None, str | None, str | None]:
"""(html, language, the CELEX it is the text of): the consolidated version first, the act
as published when that has no Polish or English text; (None, None, None) when neither."""
from ..integrations.base import SourceNotFound
for celex in dict.fromkeys((item.text_celex, item.celex)):
try:
html, lang = await self.upstream.text_html(celex)
return html, lang, celex
except SourceNotFound:
continue
return None, None, None
# ── one page of works ──
async def _process(self, items: list, pass_id: str | None, stored: dict, stats: dict,
stop: asyncio.Event | None) -> tuple[list[str], bool]:
"""Store what changed; returns (celexes whose index parts must be redone, interrupted)."""
live = [x for x in items if x.in_force]
changed: list[str] = []
if pass_id:
changed += await asyncio.to_thread(
self.store.touch_eu, [x.celex for x in live if x.celex in stored], pass_id)
todo = [x for x in live if stored.get(x.celex) != x.fingerprint]
interrupted = False
if self.max_docs is not None:
room = max(0, self.max_docs - stats["fetched"])
interrupted = len(todo) > room
todo = todo[:room]
titles = await self._titles([x.celex for x in todo]) if todo else {}
for x in todo:
if stop is not None and stop.is_set():
interrupted = True
break
try:
html, lang, celex = await self._text(x)
except (SourceError, ValueError) as exc:
log.warning("cellar: %s: %s", x.celex, exc)
stats["failed"] += 1 # not stored: asked again next pass
continue
rec = cellar_mod.build_record(x, titles.get(x.celex), html, lang, celex)
await asyncio.to_thread(self.store.upsert_eu, rec, pass_id)
stored[x.celex] = x.fingerprint
stats["fetched"] += 1
stats["without_text"] += html is None
stats["english"] += lang not in (None, "pl")
changed.append(x.celex)
gone = [x.celex for x in items if not x.in_force and x.celex in stored]
if gone:
out = await asyncio.to_thread(self.store.mark_eu_out_of_force, gone)
stats["out_of_force"] += len(out)
changed += out
return list(dict.fromkeys(changed)), interrupted
async def _reindex(self, celexes: list[str], marker) -> None:
if celexes:
await asyncio.to_thread(lambda: self.index.update(
self.store.iter_eu_rows(celexes), celexes, marker))
async def run_once(self, stop: asyncio.Event | None = None) -> dict:
raise NotImplementedError("the EUR-Lex dump importer is not implemented yet")
def status(self) -> dict:
out = super().status()
if self.enabled():
out.update(state="idle", error="not available yet: needs an EU Login account")
return out
st = self.state()
cur = dict(st.get("cursor") or {})
now = self._clock()
if not cur.get("mode"): # a new pass
last_full = _parse_ts(cur.get("full_at"))
full = (st.get("completed_at") is None or not cur.get("next_since")
or last_full is None or now - last_full >= FULL_EVERY)
cur = {"mode": "full" if full else "delta", "after": None,
"since": cur.get("next_since"), "pass_started": _ts(now - SINCE_MARGIN),
"pass_id": _ts(now), "full_at": cur.get("full_at"),
"full_id": cur.get("full_id")}
await self._save_async(cursor=cur)
full = cur["mode"] == "full"
touch_id = cur["pass_id"] if full else cur.get("full_id")
stored = await asyncio.to_thread(self.store.eu_fingerprints, self.kind)
stats = {"pages": 0, "fetched": 0, "failed": 0, "without_text": 0, "english": 0,
"out_of_force": 0}
finished = False
while True:
if stop is not None and stop.is_set():
break
if full:
items, n, last = await self._page_full(cur["after"])
else:
items, n, last = await self._page_delta(cur["since"], cur["after"])
stats["pages"] += 1
changed, interrupted = await self._process(items, touch_id, stored, stats, stop)
await self._reindex(changed, {"pass": cur["pass_id"]})
if interrupted:
break # this page again next run (done ones skip)
cur["after"] = last
if n < cellar_q.PAGE or last is None:
finished = True
n_docs, _parts = await asyncio.to_thread(self.store.eu_counts, self.kind)
await self._save_async(cursor=cur, heartbeat_at=self._clock(), doc_count=n_docs,
progress={"phase": cur["mode"], "after": cur["after"],
**stats})
if finished:
break
if finished and full and self.kind == ACT:
# acts the full listing no longer returns have left force: marked, kept, not searched
gone = await asyncio.to_thread(self.store.unlisted_eu, ACT, cur["pass_id"])
out = await asyncio.to_thread(self.store.mark_eu_out_of_force, gone)
stats["out_of_force"] += len(out)
await self._reindex(out, {"pass": cur["pass_id"]})
n_docs, parts = await asyncio.to_thread(self.store.eu_counts, self.kind)
now = self._clock()
fields = {"doc_count": n_docs, "part_count": parts, "heartbeat_at": now,
"changed": stats["fetched"] + stats["out_of_force"],
"error": (f"{stats['failed']} work(s) failed; retried on the next pass"
if stats["failed"] else None)}
if finished:
fields |= {"cursor": {"next_since": cur["pass_started"],
"full_at": cur["pass_id"] if full else cur.get("full_at"),
"full_id": cur["pass_id"] if full else cur.get("full_id")},
"synced_at": now, "progress": {"last_pass": cur["mode"], **stats}}
if full and st.get("completed_at") is None:
fields["completed_at"] = now # the first FULL pass is done
else:
fields |= {"cursor": cur, "progress": {"phase": cur["mode"], "after": cur["after"],
**stats}}
await self._save_async(**fields)
return {"mode": cur["mode"], "finished": finished, **stats}
# ── the scheduler ───────────────────────────────────────────────────────────────────────────────────
@@ -501,11 +697,10 @@ async def run_loop(importer, stop: asyncio.Event, *, tick: float = TICK,
return
except TimeoutError:
pass
if delay == start_delay:
try: # once: an index lost with its volume comes back
await ensure_index(importer)
except Exception: # noqa: BLE001
log.exception("%s index rebuild failed", importer.name)
try: # cheap when the index is ready (one small JSON read); rebuilds a lost one, or
await ensure_index(importer) # one built with another stemmer, from Postgres
except Exception: # noqa: BLE001
log.exception("%s index rebuild failed", importer.name)
delay = tick
if not importer.enabled():
continue
@@ -524,14 +719,20 @@ async def run_loop(importer, stop: asyncio.Event, *, tick: float = TICK,
async def ensure_index(importer) -> None:
"""Rebuild a dataset's index from Postgres when it is missing (a fresh volume, a deleted
directory) while rows exist — the index is disposable, the rows are not."""
directory) or was built with another stemmer (`plstem.VERSION` — a deploy that changes the
stems rebuilds every index on the next tick, without downloading anything) while rows exist —
the index is disposable, the rows are not."""
if importer.index is None or not importer.index.available or importer.index.ready():
return
st = await asyncio.to_thread(importer.store.sync_state, importer.name)
if not st or not st.get("doc_count"):
return
rows = (importer.store.iter_saos_rows() if importer.name == saos_dump.DATASET
else importer.store.iter_dzu_rows())
if importer.name == saos_dump.DATASET:
rows = importer.store.iter_saos_rows()
elif importer.name in (cellar_mod.DATASET, cellar_mod.CASELAW):
rows = importer.store.iter_eu_rows() # one index: both kinds
else:
rows = importer.store.iter_dzu_rows()
handle = await asyncio.to_thread(importer.store.acquire, importer.name)
if handle is None:
return
@@ -542,7 +743,20 @@ async def ensure_index(importer) -> None:
await asyncio.to_thread(importer.store.release, handle)
# ── wiring ──────────────────────────────────────────────────────────────────────────────────────────
# ── wiring ────────────────────────────────────────────────────────────────────────────────────────
class _Shared:
"""An upstream two importers share: closed once, by its first owner (`Indexing.aclose`)."""
def __init__(self, inner) -> None:
self._inner = inner
def __getattr__(self, name):
return getattr(self._inner, name)
async def aclose(self) -> None:
return None
class Indexing:
"""INDEXED mode's parts in one process: the store, the local adapters, the importers."""
@@ -573,6 +787,7 @@ def build_indexing(settings, store, *, transport=None, clock=utcnow, **client_kw
root = settings.index_dir
dzu_index = TextIndex(root / dzu.DATASET)
saos_index = TextIndex(root / saos_dump.DATASET)
eu_index = TextIndex(root / cellar_mod.INDEX_DIR)
adapters = {
dzu.DATASET: dzu.DzuMdAdapter(store, dzu_index,
stale_hours=max(settings.insider_dzu_md_stale_hours,
@@ -581,6 +796,9 @@ def build_indexing(settings, store, *, transport=None, clock=utcnow, **client_kw
"saos_index": saos_dump.SaosIndexAdapter(
store, saos_index, stale_hours=settings.insider_saos_index_stale_hours, clock=clock),
}
if settings.insider_cellar_sync or settings.insider_cellar_caselaw:
adapters[cellar_mod.DATASET] = cellar_mod.CellarIndexAdapter(
store, eu_index, stale_hours=settings.insider_cellar_stale_hours, clock=clock)
def client(name, base, rate, **kw):
return SourceClient(name, base, rate=rate, concurrency=1, contact=settings.insider_contact,
@@ -606,6 +824,20 @@ def build_indexing(settings, store, *, transport=None, clock=utcnow, **client_kw
on=settings.insider_eli_inforce_sync,
interval_hours=settings.insider_eli_inforce_interval_hours,
types=settings.eli_inforce_types, clock=clock),
EurlexDumpImporter(store, None, on=settings.insider_eurlex_dump_sync, 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)
from ..integrations import eurlex as eurlex_mod
cellar_up = cellar_mod.CellarUpstream(client(
"cellar", eurlex_mod.BASE_URL, settings.insider_cellar_rate, retries=1,
redirect_hosts=eurlex_mod.REDIRECT_HOSTS,
timeout=httpx.Timeout(connect=5.0, read=90.0, write=10.0, pool=5.0)))
importers += [
CellarImporter(store, eu_index, cellar_up, kind=ACT, on=settings.insider_cellar_sync,
interval_hours=settings.insider_cellar_interval_hours, clock=clock),
CellarImporter(store, eu_index, _Shared(cellar_up), kind="judgment",
on=settings.insider_cellar_caselaw,
interval_hours=settings.insider_cellar_interval_hours,
date_from=settings.insider_cellar_caselaw_from, clock=clock),
]
return Indexing(store, adapters, importers)
+192 -2
View File
@@ -1,4 +1,4 @@
"""The INDEXED-mode store: the datasets' rows (`dzu_*`, `saos_*`), their sync state and the run lock.
"""The INDEXED-mode store: the datasets' rows (`dzu_*`, `saos_*`, `eu_*`), their sync state and the run lock.
Synchronous on purpose: the importers call it through `asyncio.to_thread`, the local adapters
likewise, and an index rebuild streams it. `sync_state()` is read on every search (the adapters'
@@ -16,6 +16,7 @@ import threading
import time
from collections.abc import Iterator
from ..integrations.cellar import EuRecord, doc_rows
from ..integrations.dzu_md import ActRecord, act_rows
from ..integrations.saos_dump import JudgmentRecord, judgment_rows
@@ -23,7 +24,8 @@ STATE_TTL = 30.0
#: the advisory-lock key per dataset (second int; the first is the cache's 0x1A51DE)
#: the two act datasets share ONE key: they write the same tantivy index, and tantivy allows one
#: writer per index directory
LOCK_KEYS = {"dzu_md": 11, "eli_inforce": 11, "saos_dump": 12, "eurlex_dump": 13}
#: likewise the two CELLAR datasets (acts, case law): one `cellar` index
LOCK_KEYS = {"dzu_md": 11, "eli_inforce": 11, "saos_dump": 12, "cellar": 13, "cellar_caselaw": 13}
LOCK_SPACE = 0x1A51DE
_ACT_COLS = ("eli", "year", "pos", "title", "type", "announcement_date", "promulgation",
"change_date", "status", "keywords", "display_address", "internal_address",
@@ -35,6 +37,9 @@ STATE_COLS = ("name", "commit_sha", "cursor", "running", "heartbeat_at", "attemp
"synced_at", "completed_at", "doc_count", "part_count", "changed", "progress",
"error")
_J_COLS = ("id", "court_type", "judgment_type", "judgment_date", "case_numbers", "meta")
_EU_COLS = ("celex", "kind", "type", "title", "date", "in_force", "text_celex",
"consolidation_date", "language", "ecli", "fingerprint")
_EU_READ = (*_EU_COLS, "pass_id")
def utcnow() -> dt.datetime:
@@ -49,6 +54,10 @@ def _j_dict(rec: JudgmentRecord) -> dict:
return {k: getattr(rec, k) for k in _J_COLS}
def _eu_dict(rec: EuRecord) -> dict:
return {k: getattr(rec, k) for k in _EU_COLS}
class MemoryIndexStore:
def __init__(self) -> None:
self.states: dict[str, dict] = {}
@@ -56,6 +65,8 @@ class MemoryIndexStore:
self.articles: dict[str, dict[int, dict]] = {}
self.judgments: dict[int, dict] = {}
self.sections: dict[int, dict[int, dict]] = {}
self.eu: dict[str, dict] = {}
self.eu_parts: dict[str, dict[int, dict]] = {}
self._locks: dict[str, threading.Lock] = {}
# ── state + lock ──
@@ -151,6 +162,61 @@ class MemoryIndexStore:
sorted(self.sections.get(jid, {}).items())])
# ── CELLAR ──
def get_eu_doc(self, celex: str) -> dict | None:
d = self.eu.get(celex)
return dict(d) if d else None
def get_eu_docs(self, celexes: list[str]) -> dict[str, dict]:
return {c: dict(self.eu[c]) for c in celexes if c in self.eu}
def get_eu_parts(self, celex: str, ords: list[int] | None = None) -> dict[int, dict]:
parts = self.eu_parts.get(celex, {})
return {o: parts[o] for o in (ords if ords is not None else sorted(parts)) if o in parts}
def eu_fingerprints(self, kind: str) -> dict[str, str]:
return {c: d["fingerprint"] for c, d in self.eu.items() if d["kind"] == kind}
def upsert_eu(self, rec: EuRecord, pass_id: str | None = None) -> None:
self.eu[rec.celex] = _eu_dict(rec) | {"pass_id": pass_id}
self.eu_parts[rec.celex] = {p.ord: {"num": p.num, "text": p.text} for p in rec.parts}
def touch_eu(self, celexes: list[str], pass_id: str) -> list[str]:
"""Seen in force by this pass; returns those that were marked out of force before."""
back = []
for c in celexes:
d = self.eu.get(c)
if d is not None:
if not d["in_force"]:
back.append(c)
d.update(pass_id=pass_id, in_force=True)
return back
def unlisted_eu(self, kind: str, pass_id: str) -> list[str]:
return sorted(c for c, d in self.eu.items()
if d["kind"] == kind and d["in_force"] and d.get("pass_id") != pass_id)
def mark_eu_out_of_force(self, celexes: list[str]) -> list[str]:
out = []
for c in celexes:
d = self.eu.get(c)
if d is not None and d["in_force"]:
d["in_force"] = False
out.append(c)
return out
def eu_counts(self, kind: str) -> tuple[int, int]:
cs = [c for c, d in self.eu.items() if d["kind"] == kind]
return len(cs), sum(len(self.eu_parts.get(c, {})) for c in cs)
def iter_eu_rows(self, celexes: list[str] | None = None) -> Iterator[dict]:
for c in (celexes if celexes is not None else sorted(self.eu)):
d = self.eu.get(c)
if d is not None:
yield from doc_rows(d, [{"ord": o, **p} for o, p in
sorted(self.eu_parts.get(c, {}).items())])
class _PgLock:
def __init__(self, db, key: tuple[int, int]) -> None:
self.db = db
@@ -415,3 +481,127 @@ class PgIndexStore:
yield from judgment_rows({"id": jid, "court_type": ct, "judgment_date": date,
"case_numbers": cases, "meta": meta},
[{"ord": o, "text": text}])
# ── CELLAR ──
def get_eu_doc(self, celex: str) -> dict | None:
from ..models import EuDoc
with self._factory() as db:
row = db.get(EuDoc, celex)
return None if row is None else {k: getattr(row, k) for k in _EU_READ}
def get_eu_docs(self, celexes: list[str]) -> dict[str, dict]:
if not celexes:
return {}
from sqlalchemy import select
from ..models import EuDoc
with self._factory() as db:
rows = db.scalars(select(EuDoc).where(EuDoc.celex.in_(celexes))).all()
return {r.celex: {k: getattr(r, k) for k in _EU_READ} for r in rows}
def get_eu_parts(self, celex: str, ords: list[int] | None = None) -> dict[int, dict]:
from sqlalchemy import select
from ..models import EuPart
stmt = select(EuPart.ord, EuPart.num, EuPart.text).where(EuPart.celex == celex)
if ords is not None:
if not ords:
return {}
stmt = stmt.where(EuPart.ord.in_(ords))
with self._factory() as db:
return {o: {"num": n, "text": t} for o, n, t in db.execute(stmt.order_by(EuPart.ord))}
def eu_fingerprints(self, kind: str) -> dict[str, str]:
from sqlalchemy import select
from ..models import EuDoc
with self._factory() as db:
return dict(db.execute(select(EuDoc.celex, EuDoc.fingerprint)
.where(EuDoc.kind == kind)).all())
def upsert_eu(self, rec: EuRecord, pass_id: str | None = None) -> None:
"""One work and its parts in one transaction: the old parts go, the new ones come."""
from sqlalchemy import delete, func, insert
from sqlalchemy.dialects.postgresql import insert as pg_insert
from ..models import EuDoc, EuPart
values = _eu_dict(rec) | {"pass_id": pass_id}
with self._factory() as db:
stmt = pg_insert(EuDoc).values(**values)
db.execute(stmt.on_conflict_do_update(
index_elements=["celex"],
set_={**{k: stmt.excluded[k] for k in values if k != "celex"},
"updated_at": func.now()}))
db.execute(delete(EuPart).where(EuPart.celex == rec.celex))
if rec.parts:
db.execute(insert(EuPart), [{"celex": rec.celex, "ord": p.ord, "num": p.num,
"text": p.text} for p in rec.parts])
db.commit()
def touch_eu(self, celexes: list[str], pass_id: str) -> list[str]:
"""Seen in force by this pass; returns those that were marked out of force before."""
if not celexes:
return []
from sqlalchemy import update
from ..models import EuDoc
with self._factory() as db:
back = db.scalars(update(EuDoc).where(EuDoc.celex.in_(celexes),
EuDoc.in_force.is_(False))
.values(in_force=True).returning(EuDoc.celex)).all()
db.execute(update(EuDoc).where(EuDoc.celex.in_(celexes)).values(pass_id=pass_id))
db.commit()
return list(back)
def unlisted_eu(self, kind: str, pass_id: str) -> list[str]:
from sqlalchemy import or_, select
from ..models import EuDoc
with self._factory() as db:
return list(db.scalars(select(EuDoc.celex).where(
EuDoc.kind == kind, EuDoc.in_force.is_(True),
or_(EuDoc.pass_id.is_(None), EuDoc.pass_id != pass_id)).order_by(EuDoc.celex)))
def mark_eu_out_of_force(self, celexes: list[str]) -> list[str]:
if not celexes:
return []
from sqlalchemy import update
from ..models import EuDoc
with self._factory() as db:
out = db.scalars(update(EuDoc).where(EuDoc.celex.in_(celexes),
EuDoc.in_force.is_(True))
.values(in_force=False).returning(EuDoc.celex)).all()
db.commit()
return list(out)
def eu_counts(self, kind: str) -> tuple[int, int]:
from sqlalchemy import func, select
from ..models import EuDoc, EuPart
with self._factory() as db:
return (db.scalar(select(func.count()).select_from(EuDoc)
.where(EuDoc.kind == kind)) or 0,
db.scalar(select(func.count()).select_from(EuPart)
.join(EuDoc, EuDoc.celex == EuPart.celex)
.where(EuDoc.kind == kind)) or 0)
def iter_eu_rows(self, celexes: list[str] | None = None) -> Iterator[dict]:
"""Every part as an index row, streamed in (celex, ord) order."""
from sqlalchemy import select
from ..models import EuDoc, EuPart
stmt = (select(EuDoc.celex, EuDoc.kind, EuDoc.type, EuDoc.title, EuDoc.date,
EuDoc.in_force, EuPart.ord, EuPart.text)
.join(EuPart, EuPart.celex == EuDoc.celex)
.order_by(EuDoc.celex, EuPart.ord))
if celexes is not None:
if not celexes:
return
stmt = stmt.where(EuDoc.celex.in_(celexes))
with self._factory() as db:
for c, k, t, title, date, force, o, text in db.execute(stmt.execution_options(
yield_per=1000)):
yield from doc_rows({"celex": c, "kind": k, "type": t, "title": title,
"date": date, "in_force": force},
[{"ord": o, "text": text}])
+23 -1
View File
@@ -215,12 +215,22 @@ class Legal:
celex = eurlex_mod.valid_celex(celex)
except ValueError as exc:
raise ValidationError(str(exc)) from exc
found = await self._cellar(celex)
if found is not None:
return found[0] # the local CELLAR index: no request
adapter = self._adapter("eurlex")
async def fetch():
return (await adapter.fetch(celex)).to_dict()
return LegalDoc.from_dict(await self._cached(f"doc:eurlex:{celex}", TTL_ACT, fetch))
async def _cellar(self, celex: str) -> tuple[LegalDoc, str] | None:
"""(document, plain text) from the local CELLAR index while it is ready and fresh."""
local = self.registry.get("cellar")
if local is None:
return None
return await asyncio.to_thread(local.local_doc, celex)
async def get_act(self, eli: str) -> dict:
doc = await self.act(eli)
rec = await self.texts.get(doc.id, _version(doc))
@@ -228,6 +238,10 @@ class Legal:
async def get_eu_act(self, celex: str) -> dict:
doc = await self.eu_doc(celex)
if doc.source == "cellar":
# the index row already carries the consolidated version it holds; no live details
return {**doc.to_dict(), "text_status": "ready" if doc.extra.get("language")
else "failed"}
rec = await self.texts.get(doc.id, "1")
adapter = self._adapter("eurlex")
@@ -298,6 +312,14 @@ class Legal:
"text_attribution": dzu_md.ATTRIBUTION, "converted_at": act.get("converted_at")})
async def eu_text(self, celex: str, *, part: int = 1, max_chars: int = 20000) -> dict:
found = await self._cellar(eurlex_mod.valid_celex(celex)) if eurlex_mod.CELEX.match(
(celex or "").strip().upper()) else None
if found is not None and found[1].strip():
doc, text = found
rec = TextRecord(doc.id, "1", "ready", text, "cellar", doc.extra.get("language"))
return {**_text_answer(doc, rec, part, max_chars), "text_source": "cellar",
"text_celex": doc.extra.get("text_celex"),
"text_url": doc.extra.get("text_url")}
doc = await self.eu_doc(celex)
# A CELEX number names one immutable text (a consolidated version has its own number).
rec = await self.texts.get(doc.id, "1")
@@ -470,7 +492,7 @@ def _text_answer(doc: LegalDoc, rec: TextRecord | None, part: int, max_chars: in
"attribution": doc.attribution,
"text_status": rec.status if rec else "failed",
"method": rec.method if rec else None, "language": rec.language if rec else None}
if doc.source == "eurlex":
if doc.source in ("eurlex", "cellar"):
base["text_note"] = eurlex_mod.TEXT_NOTE
if rec is not None and rec.language and rec.language != "pl":
base["language_note"] = f"Brak tekstu po polsku — podano wersję '{rec.language}'."
+16 -3
View File
@@ -16,7 +16,8 @@ for how many matched), and carries its three best.
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`
records what it reflects; `ready()` = it exists and has documents. Without `tantivy` installed
records what it reflects and the stemmer (`plstem.VERSION`) it was built with; `ready()` = it
exists, has documents and matches today's stemmer. Without `tantivy` installed
`available` is False and the indexed source reports itself unavailable — the live source answers.
"""
from __future__ import annotations
@@ -84,7 +85,16 @@ class TextIndex:
return {}
def ready(self) -> bool:
return self.available and bool(self.meta().get("docs"))
"""Built, not empty, and built with TODAY's stemmer: an index from another `plstem.VERSION`
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
def stale_stemmer(self) -> bool:
"""An index exists but was built with another `plstem.VERSION` (or before it was recorded)."""
meta = self.meta()
return bool(meta) and meta.get("stemmer") != plstem.VERSION
def size_bytes(self) -> int:
try:
@@ -103,7 +113,7 @@ class TextIndex:
def _write_meta(self, path: Path, marker, docs: int) -> None:
(path / META).write_text(json.dumps({
"marker": marker, "docs": docs,
"marker": marker, "docs": docs, "stemmer": plstem.VERSION,
"built_at": dt.datetime.now(dt.UTC).isoformat(timespec="microseconds")}),
encoding="utf-8")
@@ -155,6 +165,9 @@ class TextIndex:
if not (self.path / META).exists():
self.path.mkdir(parents=True, exist_ok=True)
self._index = None
elif self.stale_stemmer():
# never mix two stemmers' terms in one index: `ensure_index` rebuilds it first
raise RuntimeError(f"index {self.path.name} was built with another stemmer")
index = tantivy.Index(self._schema, path=str(self.path))
writer = index.writer(heap_size=WRITER_HEAP, num_threads=1)
for g in groups:
+492
View File
@@ -0,0 +1,492 @@
"""INDEXED mode, CELLAR — DB-free: the in-force listing and the consolidated-version mapping, the
queries (keyset, delta, no user text), the Polish text with the English fallback, the structure pass
on real-shaped XHTML, the importer (full pass, resumable cursor, fingerprints, the daily delta, acts
leaving force), the shared run lock, search from the index with live CELLAR for the rest and as the
fallback when stale, attribution on every result, and the fixed-host / redirect allowlist.
Every upstream is a fake (`tests/fakes.py`'s MockTransport); nothing here reaches a real host.
"""
from __future__ import annotations
import asyncio
import datetime as dt
from types import SimpleNamespace
from urllib.parse import parse_qs
import httpx
import pytest
from fakes import EURLEX, FakeUpstream, _no_sleep, make_legal, sparql
from app.integrations import cellar
from app.integrations.base import ACT, JUDGMENT, Query, SourceError
from app.integrations.cellar_builder import queries as q
from app.integrations.cellar_builder.structure import split_html, split_text
from app.integrations.eurlex import ATTRIBUTION, TEXT_NOTE
from app.integrations.http import SourceClient
from app.services import indexing
from app.services.indexstore import MemoryIndexStore
from app.services.textindex import TextIndex
NOW = dt.datetime(2026, 10, 21, 2, 0, tzinfo=dt.UTC)
pytestmark = pytest.mark.skipif(not TextIndex.available, reason="tantivy is not installed")
# ── real-shaped texts (the Publications Office's XHTML classes, as eurlex-builder documents them) ──
OJ_XHTML = """<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml"><head><title>L_2016119PL.01000101.xml</title>
<script>alert(1)</script></head><body><div class="eli-container">
<p class="oj-doc-ti">ROZPORZĄDZENIE PARLAMENTU EUROPEJSKIEGO I RADY (UE) 2016/679</p>
<p class="oj-doc-ti">w sprawie ochrony osób fizycznych w związku z przetwarzaniem danych osobowych</p>
<div class="eli-subdivision" id="rct_1"><p class="oj-normal">(1) Ochrona osób fizycznych w związku
z przetwarzaniem danych osobowych jest prawem podstawowym.</p></div>
<div class="eli-subdivision" id="art_1"><p class="oj-ti-art">Artykuł 1</p>
<div class="eli-title"><p class="oj-sti-art">Przedmiot i cele</p></div>
<p class="oj-normal">1. Niniejsze rozporządzenie określa przepisy o ochronie osób fizycznych.</p></div>
<div class="eli-subdivision" id="art_2"><p class="oj-ti-art">Artykuł 2</p>
<p class="oj-sti-art">Materialny zakres stosowania</p>
<p class="oj-normal">Niniejsze rozporządzenie ma zastosowanie do przetwarzania danych osobowych.</p>
<p class="oj-normal">„Artykuł 5</p></div>
<div class="eli-subdivision" id="art_2a"><p class="oj-ti-art">Artykuł 2a</p>
<p class="oj-normal">Przepis dodany.</p></div>
<p class="oj-final">Sporządzono w Brukseli dnia 27 kwietnia 2016 r.</p>
<p class="oj-ti-grseq-1">ZAŁĄCZNIK I</p><p class="oj-normal">Wykaz informacji.</p>
</div></body></html>"""
CONSOLIDATED_XHTML = """<html><body>
<p class="disclaimer">Ten tekst służy wyłącznie jako narzędzie dokumentacyjne.</p>
<p class="modref">▼B</p>
<p class="title-doc-first">DYREKTYWA RADY 93/13/EWG</p>
<p class="title-article-norm">Artykuł 1</p><p class="stitle-article-norm">Cel</p>
<p class="norm">Celem niniejszej dyrektywy jest zbliżenie przepisów ►M1 o nieuczciwych warunkach ◄.</p>
<p class="modref">▼M1</p>
<p class="title-article-norm">Artykuł 8a</p>
<p class="norm">Państwa członkowskie informują Komisję.</p></body></html>"""
PLAIN_HTML = """<html><body><p>DYREKTYWA RADY</p><p>Artykuł 1</p><p>Cel dyrektywy.</p>
<p>Artykuł 2</p><p>Definicje.</p><p>ZAŁĄCZNIK</p><p>Warunki.</p></body></html>"""
class TestStructure:
def test_oj_classes_give_articles_annex_and_tail(self):
text, parts = split_html(OJ_XHTML)
nums = [p.num for p in parts]
assert nums == [None, "1", "2", "2a", None, "ZAŁĄCZNIK I"]
assert "Przedmiot i cele" in parts[1].text # the subtitle stays with its article
assert "„Artykuł 5" in parts[2].text # a quoted heading does not cut
assert "alert" not in text and "<" not in text # sanitised: no script, no markup
assert [p.ord for p in parts] == list(range(len(parts)))
assert "".join(p.text for p in parts) == text
def test_consolidated_markers_are_dropped(self):
_text, parts = split_html(CONSOLIDATED_XHTML)
assert [p.num for p in parts] == [None, "1", "8a"]
joined = "".join(p.text for p in parts)
assert "▼" not in joined and "►" not in joined and "◄" not in joined
assert "przepisów o nieuczciwych warunkach" in parts[1].text
def test_plain_html_falls_back_to_heading_lines(self):
_text, parts = split_html(PLAIN_HTML)
assert [p.num for p in parts] == [None, "1", "2", "ZAŁĄCZNIK"]
def test_english_and_size_cut(self):
parts = split_text("Preamble\nArticle 1\nScope.\nArticle 2\n" + "x" * 30_000)
assert [p.num for p in parts][:3] == [None, "1", "2"] and len(parts) > 3
assert all(len(p.text) <= 12_100 for p in parts)
def test_a_judgment_is_cut_by_size_only(self):
_t, parts = split_html("<p>Artykuł 1</p><p>wyrok</p>", JUDGMENT)
assert [p.num for p in parts] == [None]
class TestListing:
def test_in_force_listing_and_consolidated_mapping(self):
a = cellar.listed_act({"celex": "32016R0679", "type": "R", "date": "2016-04-27",
"force": "1", "mod": "2024-12-31T20:10:26",
"cons": "02016R0679-20160504", "consmod": "2026-02-19T13:46:21"})
assert a.text_celex == "02016R0679-20160504" and a.consolidation_date == "2016-05-04"
assert a.in_force and a.modified == "2026-02-19T13:46:21"
assert a.fingerprint == "02016R0679-20160504|2026-02-19T13:46:21"
# a "consolidated version" of ANOTHER number is not this act's
b = cellar.listed_act({"celex": "32016R0679", "force": "1", "cons": "02016R0680-20200101"})
assert b.text_celex == "32016R0679" and b.consolidation_date is None
assert cellar.listed_act({"celex": "32006L0112R(24)", "force": "1"}) is None
assert cellar.listed_act({"celex": "32016Q0001", "force": "1"}) is None
assert not cellar.listed_act({"celex": "31993L0013", "force": "0"}).in_force
def test_titles_prefer_polish(self):
rows = [{"celex": "32016R0679", "lang": "…/ENG", "title": "General Data Protection"},
{"celex": "32016R0679", "lang": "…/POL", "title": "RODO "},
{"celex": "32024R1689", "lang": "…/ENG", "title": "AI Act"}]
assert cellar.pick_titles(rows) == {"32016R0679": "RODO", "32024R1689": "AI Act"}
def test_queries_take_no_user_text(self):
s = q.acts_listing_sparql("32016R0679")
assert 'STR(?celex) > "32016R0679"' in s and "resource_legal_in-force" in s
assert "OFFSET" not in s and "act_consolidated_based_on_resource_legal" in s
assert 'IN ("1", "true")' in s and q._NOT_CORRIGENDUM in s
d = q.modified_sparql("3", "2026-10-20T00:00:00Z")
assert "cmr:lastModificationDate" in d and "UNION" in d
assert "UNION" not in q.modified_sparql("6", "2026-10-20T00:00:00Z")
for bad in ('32016R0679" } DROP', "x"):
with pytest.raises(ValueError):
q.acts_listing_sparql(bad)
with pytest.raises(ValueError):
q.modified_sparql("3", '2026" }')
with pytest.raises(ValueError):
q.caselaw_listing_sparql("2000-01-01'")
assert '"2000-01-01"^^xsd:date' in q.caselaw_listing_sparql("2000-01-01")
# ── a fake CELLAR ───────────────────────────────────────────────────────────────────────────────────
class FakeCellar:
"""SPARQL routed on what the query asks; texts by CELEX and Accept-Language (303 → cellar)."""
def __init__(self, up: FakeUpstream) -> None:
self.up = up
self.acts: dict[str, dict] = {} # celex → listing row
self.modified: list[str] = [] # what the delta query answers
self.texts: dict[tuple[str, str], str] = {}
self.queries: list[str] = []
self.text_calls: list[tuple[str, str]] = []
up.route(EURLEX, "/webapi/rdf/sparql", self._sparql)
self._n = 0
def act(self, celex, *, force="1", cons=None, mod="2026-01-01T00:00:00", consmod=None,
pl=None, en=None, title=None):
self.acts[celex] = {k: v for k, v in {
"celex": celex, "type": celex[5], "date": f"{celex[1:5]}-01-01", "force": force,
"mod": mod, "cons": cons, "consmod": consmod}.items() if v is not None}
for c, lang, body in ((cons or celex, "pl", pl), (cons or celex, "en", en)):
if body is not None:
self.text(c, lang, body)
self.titles = getattr(self, "titles", {}) | {celex: title or f"Akt {celex}"}
def text(self, celex, lang, body):
self._n += 1
path = f"/resource/cellar/u{self._n}.0001.01/DOC_1"
self.texts[(celex, lang)] = path
self.up.route(EURLEX, path, lambda r, b=body: httpx.Response(
200, text=b, headers={"content-type": "application/xhtml+xml;charset=UTF-8"}))
def negotiate(request, c=celex):
want = request.headers.get("accept-language", "")[:2]
self.text_calls.append((c, want))
target = self.texts.get((c, want))
if target is None:
return httpx.Response(404, text="")
return httpx.Response(303, headers={"location": f"http://{EURLEX}{target}"})
self.up.route(EURLEX, f"/resource/celex/{celex}", negotiate)
def _sparql(self, request):
query = parse_qs(request.url.query.decode())["query"][0]
self.queries.append(query)
if "expression_title" in query:
rows = [{"celex": c, "lang": "x/POL", "title": t} for c, t in self.titles.items()
if f'"{c}"' in query]
elif "SELECT DISTINCT ?celex" in query:
rows = [{"celex": c} for c in self.modified if f'> "{c}"' not in query]
rows = [] if "STR(?celex) >" in query else rows
elif "VALUES ?cx" in query:
rows = [r for c, r in self.acts.items() if f'"{c}"' in query]
elif "STR(?celex) >" in query:
rows = [] # one page only
else:
rows = [r for r in self.acts.values() if r.get("force") == "1"]
return httpx.Response(200, json=sparql(sorted(rows, key=lambda r: r["celex"])))
def ix_settings(tmp_path, **over):
base = dict(index_dir=tmp_path / "index", insider_contact="ops@example.test",
insider_dzu_md_stale_hours=72, insider_eli_inforce_interval_hours=24,
insider_saos_index_stale_hours=96, insider_dzu_md_rate=1000.0,
insider_dzu_md_sync=False, insider_dzu_md_sync_interval_hours=6,
insider_saos_dump_sync=False, insider_saos_dump_window="23:00-05:00",
insider_saos_dump_page_size=10, insider_saos_dump_pause_seconds=5,
insider_saos_dump_interval_hours=20, insider_eli_inforce_rate=1000.0,
insider_eli_inforce_sync=False, eli_inforce_types=["Ustawa"],
insider_cellar_sync=True, insider_cellar_caselaw=False,
insider_cellar_interval_hours=24, insider_cellar_rate=1000.0,
insider_cellar_stale_hours=96, insider_cellar_caselaw_from="2000-01-01")
base.update(over)
return SimpleNamespace(**base)
def build(tmp_path, up, store=None, clock=lambda: NOW, **over):
return indexing.build_indexing(ix_settings(tmp_path, **over), store or MemoryIndexStore(),
transport=up.transport(), clock=clock, sleep=_no_sleep)
def acts_importer(ix):
return next(i for i in ix.importers if i.name == "cellar")
def seeded(up):
fc = FakeCellar(up)
fc.act("32016R0679", cons="02016R0679-20160504", consmod="2026-02-19T13:46:21",
pl=OJ_XHTML, title="Rozporządzenie (UE) 2016/679 w sprawie ochrony danych osobowych")
fc.act("31993L0013", en=PLAIN_HTML.replace("Artykuł", "Article"),
title="Dyrektywa 93/13/EWG w sprawie nieuczciwych warunków w umowach konsumenckich")
fc.act("32024R1689") # no text in Polish or English
return fc
class TestImporter:
def test_full_pass_polish_english_fallback_and_cursor(self, tmp_path):
up = FakeUpstream()
fc = seeded(up)
ix = build(tmp_path, up)
imp = acts_importer(ix)
out = asyncio.run(imp.locked_run())
assert out["finished"] and out["fetched"] == 3 and out["mode"] == "full"
assert out["english"] == 1 and out["without_text"] == 1
gdpr = ix.store.get_eu_doc("32016R0679")
assert gdpr["text_celex"] == "02016R0679-20160504" and gdpr["language"] == "pl"
assert gdpr["consolidation_date"] == "2016-05-04"
assert ("02016R0679-20160504", "pl") in fc.text_calls
assert ("32016R0679", "pl") not in fc.text_calls # the consolidated text was enough
assert ix.store.get_eu_doc("31993L0013")["language"] == "en"
assert ix.store.get_eu_doc("32024R1689")["language"] is None
st = ix.store.sync_state("cellar")
assert st["completed_at"] == NOW and st["synced_at"] == NOW and st["doc_count"] == 3
assert st["cursor"]["next_since"] == "2026-10-21T01:00:00Z"
assert ix.adapters["cellar"].index.ready()
# a second full pass fetches nothing: the fingerprints did not move
fc.text_calls.clear()
ix.store.set_state("cellar", cursor={**st["cursor"], "full_at": None})
again = asyncio.run(imp.locked_run())
assert again["mode"] == "full" and again["fetched"] == 0 and fc.text_calls == []
def test_resumable_with_a_budget(self, tmp_path):
up = FakeUpstream()
seeded(up)
ix = build(tmp_path, up)
imp = acts_importer(ix)
imp.max_docs = 1
first = asyncio.run(imp.locked_run())
assert not first["finished"] and first["fetched"] == 1
cur = ix.store.sync_state("cellar")["cursor"]
assert cur["mode"] == "full" and cur["after"] is None and imp.due(NOW)
assert ix.store.sync_state("cellar")["completed_at"] is None
imp.max_docs = None
second = asyncio.run(imp.locked_run())
assert second["finished"] and second["fetched"] == 2 # the done one is not refetched
def test_daily_delta_refetches_only_what_moved_and_marks_out_of_force(self, tmp_path):
up = FakeUpstream()
fc = seeded(up)
later = NOW + dt.timedelta(days=1)
clock = {"t": NOW}
ix = build(tmp_path, up, clock=lambda: clock["t"])
imp = acts_importer(ix)
asyncio.run(imp.locked_run())
assert not imp.due(NOW + dt.timedelta(hours=23)) and imp.due(later)
# a new consolidated version of the GDPR; the directive left force
fc.text("02016R0679-20240101", "pl", OJ_XHTML.replace("Przedmiot", "Nowy przedmiot"))
fc.acts["32016R0679"] |= {"cons": "02016R0679-20240101", "consmod": "2026-10-21T10:00:00"}
fc.acts["31993L0013"]["force"] = "0"
fc.modified = ["31993L0013", "32016R0679", "32006L0112R(24)"]
fc.text_calls.clear()
fc.queries.clear()
clock["t"] = later
out = asyncio.run(imp.locked_run())
assert out["mode"] == "delta" and out["fetched"] == 1 and out["out_of_force"] == 1
assert fc.text_calls == [("02016R0679-20240101", "pl")]
assert any('"2026-10-21T01:00:00Z"^^xsd:dateTime' in x for x in fc.queries)
assert not any("resource_legal_id_sector ?s . FILTER(STR(?s) = \"3\")\n ?w cdm:resource"
"_legal_id_celex ?celex . FILTER(!CONTAINS" in x and "in-force ?force ."
in x for x in fc.queries) # no full listing in a delta
assert ix.store.get_eu_doc("32016R0679")["text_celex"] == "02016R0679-20240101"
assert ix.store.get_eu_doc("31993L0013")["in_force"] is False
groups, _ = ix.adapters["cellar"].index.search("nieuczciwe warunki",
exclude_tags=("nf",))
assert groups == [] # out of force: not searched
def test_full_pass_marks_acts_the_listing_dropped(self, tmp_path):
up = FakeUpstream()
fc = seeded(up)
ix = build(tmp_path, up)
imp = acts_importer(ix)
asyncio.run(imp.locked_run())
del fc.acts["32024R1689"]
ix.store.set_state("cellar", cursor={"next_since": "2026-10-21T01:00:00Z"}) # force full
imp._clock = lambda: NOW + dt.timedelta(seconds=5)
out = asyncio.run(imp.locked_run())
assert out["mode"] == "full" and out["out_of_force"] == 1
assert ix.store.get_eu_doc("32024R1689")["in_force"] is False
def test_one_lock_for_both_kinds(self, tmp_path):
up = FakeUpstream()
seeded(up)
ix = build(tmp_path, up, insider_cellar_caselaw=True)
acts = acts_importer(ix)
case = next(i for i in ix.importers if i.name == "cellar_caselaw")
held = ix.store.acquire("cellar")
try:
assert asyncio.run(case.locked_run()) is None
assert asyncio.run(acts.locked_run()) is None
finally:
ix.store.release(held)
def test_a_failed_text_is_retried_not_stored(self, tmp_path):
up = FakeUpstream()
fc = seeded(up)
up.route(EURLEX, "/resource/celex/02016R0679-20160504",
lambda r: httpx.Response(303, headers={"location": "https://evil.example/x"}))
ix = build(tmp_path, up)
out = asyncio.run(acts_importer(ix).locked_run())
assert out["failed"] == 1 and ix.store.get_eu_doc("32016R0679") is None
assert "evil.example" not in up.hosts()
assert "retried" in ix.store.sync_state("cellar")["error"]
assert fc.acts
# ── search ──────────────────────────────────────────────────────────────────────────────────────────
def legal_with_cellar(tmp_path, up, *, synced=NOW, caselaw=False):
from app.services.legal import Legal
store = MemoryIndexStore()
seeded(up)
ix = build(tmp_path, up, store=store, insider_cellar_caselaw=caselaw)
asyncio.run(acts_importer(ix).locked_run())
store.set_state("cellar", synced_at=synced)
base = make_legal(up, budget=2.0, slow_budget=3.0)
return Legal(base.registry, base.cache, base.texts, base.codec, budget=2.0, slow_budget=3.0,
indexing=ix), store
def _st(out):
return {s["name"]: s for s in out["sources"]}
class TestSearch:
def test_acts_from_the_index_with_attribution_note_and_link(self, tmp_path):
up = FakeUpstream()
legal, _ = legal_with_cellar(tmp_path, up)
n = len(up.calls)
out = asyncio.run(legal.search(Query(q="ochrona danych osobowych", kind="act",
jurisdiction="eu")))
st = _st(out)
assert st["cellar"]["status"] == "ok" and st["cellar"]["served_by"] == "index"
assert st["eurlex"]["status"] == "skipped" and "cellar" in st["eurlex"]["detail"]
assert len(up.calls) == n # no request at all
hit = out["acts"][0]
assert hit["id"] == "eurlex:32016R0679" and hit["source"] == "cellar"
assert hit["attribution"] == ATTRIBUTION and "© European Union" in hit["attribution"]
assert "https://eur-lex.europa.eu" in hit["attribution"]
assert hit["extra"]["text_note"] == TEXT_NOTE
assert hit["official_url"].startswith("https://eur-lex.europa.eu/legal-content/PL/TXT/")
assert hit["extra"]["text_celex"] == "02016R0679-20160504"
assert hit["extra"]["articles"] and hit["snippet"].startswith(("Art. ", ""))
def test_english_text_found_by_english_words_with_language_note(self, tmp_path):
up = FakeUpstream()
legal, _ = legal_with_cellar(tmp_path, up)
out = asyncio.run(legal.search(Query(q="definicje", kind="act", jurisdiction="eu")))
assert out["acts"] == [] or out["acts"][0]["source"] == "cellar"
d = cellar.to_doc({"celex": "31993L0013", "kind": ACT, "language": "en"})
assert "Brak tekstu po polsku" in d.extra["language_note"]
def test_all_kinds_narrows_live_cellar_to_judgments(self, tmp_path):
up = FakeUpstream()
legal, _ = legal_with_cellar(tmp_path, up)
before = len(up.calls)
out = asyncio.run(legal.search(Query(q="ochrona danych osobowych")))
st = _st(out)
assert st["cellar"]["status"] == "ok"
assert st["eurlex"]["status"] == "ok" and "judgments" in st["eurlex"]["detail"]
sent = [parse_qs(c.url.query.decode())["query"][0] for c in up.calls[before:]
if c.url.path.endswith("sparql")]
assert sent and all('IN ("6")' in s for s in sent) # acts were not asked live
def test_stale_index_falls_back_to_live(self, tmp_path):
up = FakeUpstream()
legal, _ = legal_with_cellar(tmp_path, up, synced=NOW - dt.timedelta(days=30))
out = asyncio.run(legal.search(Query(q="ochrona danych osobowych", kind="act",
jurisdiction="eu")))
st = _st(out)
assert st["cellar"]["status"] == "skipped" and "stale" in st["cellar"]["detail"]
assert st["eurlex"]["status"] == "ok"
def test_a_celex_lookup_stays_live(self, tmp_path):
up = FakeUpstream()
legal, _ = legal_with_cellar(tmp_path, up)
out = asyncio.run(legal.search(Query(celex="32016R0679")))
assert _st(out)["cellar"]["status"] == "skipped" and _st(out)["eurlex"]["status"] == "ok"
def test_text_and_detail_from_the_index_without_a_request(self, tmp_path):
up = FakeUpstream()
legal, _ = legal_with_cellar(tmp_path, up)
n = len(up.calls)
t = asyncio.run(legal.eu_text("32016R0679"))
assert t["text_status"] == "ready" and t["text_source"] == "cellar"
assert "Przedmiot i cele" in t["text"] and t["text_note"] == TEXT_NOTE
assert t["attribution"] == ATTRIBUTION and t["language"] == "pl"
d = asyncio.run(legal.get_eu_act("32016R0679"))
assert d["source"] == "cellar" and d["extra"]["current_consolidated"]
assert len(up.calls) == n
def test_the_datasets_card(self, tmp_path):
up = FakeUpstream()
legal, _ = legal_with_cellar(tmp_path, up)
ds = {d["name"]: d for d in legal.datasets()["datasets"]}
assert ds["cellar"]["documents"] == 3 and ds["cellar"]["index"]["ready"]
assert ds["cellar_caselaw"]["state"] == "off"
# ── SSRF: one fixed host, redirects only to it ──────────────────────────────────────────────────────
def test_upstream_is_pinned_to_the_cellar_host():
other = SourceClient("x", "https://eur-lex.europa.eu/", rate=1, concurrency=1,
contact="ops@example.test")
with pytest.raises(ValueError):
cellar.CellarUpstream(other)
asyncio.run(other.aclose())
def test_redirect_elsewhere_is_refused_and_http_is_upgraded():
up = FakeUpstream()
up.route(EURLEX, "/resource/celex/32016R0679",
lambda r: httpx.Response(303, headers={"location": "https://attacker.test/x"}))
up.route(EURLEX, "/resource/celex/31993L0013",
lambda r: httpx.Response(303, headers={
"location": f"http://{EURLEX}/resource/cellar/a.b.c/DOC_1"}))
up.route(EURLEX, "/resource/cellar/a.b.c/DOC_1",
lambda r: httpx.Response(200, text="<p>Artykuł 1</p>",
headers={"content-type": "text/html"}))
client = SourceClient("cellar", "https://publications.europa.eu/", rate=1000, concurrency=1,
contact="ops@example.test", transport=up.transport(), sleep=_no_sleep,
redirect_hosts=frozenset({"publications.europa.eu"}))
u = cellar.CellarUpstream(client)
with pytest.raises(SourceError):
asyncio.run(u.text_html("32016R0679"))
html, lang = asyncio.run(u.text_html("31993L0013"))
assert lang == "pl" and "Artykuł" in html
assert up.hosts() == {EURLEX}
assert all(c.url.scheme == "https" for c in up.calls)
with pytest.raises(ValueError):
asyncio.run(u.text_html("../../etc"))
asyncio.run(u.aclose())
def test_the_index_adapter_has_no_client_host():
ad = cellar.CellarIndexAdapter(MemoryIndexStore(), None, stale_hours=96)
assert not hasattr(ad.client, "request")
assert ad.covered_kinds(Query(q="ochrona danych")) == frozenset() # no index: live
def test_a_new_stemmer_rebuilds_the_index_from_postgres(tmp_path):
import json
from app.integrations import plstem
up = FakeUpstream()
fc = seeded(up)
ix = build(tmp_path, up)
imp = acts_importer(ix)
asyncio.run(imp.locked_run())
meta_path = imp.index.path / "index.json"
meta = json.loads(meta_path.read_text(encoding="utf-8"))
meta_path.write_text(json.dumps({**meta, "stemmer": plstem.VERSION - 1}), encoding="utf-8")
assert not imp.index.ready() and imp.index.stale_stemmer()
with pytest.raises(RuntimeError): # never mix two stemmers' terms
imp.index.update([], ["x"])
calls = len(up.calls)
asyncio.run(indexing.ensure_index(imp))
assert imp.index.ready() and len(up.calls) == calls # rebuilt from the rows, no download
assert fc.acts
+8 -9
View File
@@ -138,7 +138,9 @@ def settings(tmp_path, **over):
insider_saos_dump_page_size=10, insider_saos_dump_pause_seconds=5,
insider_saos_dump_interval_hours=20, insider_eli_inforce_rate=1000.0,
insider_eli_inforce_sync=True, eli_inforce_types=["Ustawa"],
insider_eurlex_dump_sync=False)
insider_cellar_sync=False, insider_cellar_caselaw=False,
insider_cellar_interval_hours=24, insider_cellar_rate=1000.0,
insider_cellar_stale_hours=96, insider_cellar_caselaw_from="2000-01-01")
base.update(over)
return SimpleNamespace(**base)
@@ -578,20 +580,17 @@ class TestEliInForce:
assert not indexing.is_base_act("Ustawa z dnia 1 maja 2026 r. o zmianie ustawy o VAT")
# ── the panel's data, and the EUR-Lex seam ──────────────────────────────────────────────────────────
# ── the panel's data ────────────────────────────────────────────────────────────────────────────────
def test_dataset_statuses(tmp_path):
ix = build(tmp_path, FakeUpstream(), insider_saos_dump_sync=False)
ix.store.set_state("dzu_md", running=True, heartbeat_at=NOW, commit_sha=SHA1, doc_count=3)
st = {d["name"]: d for d in ix.statuses()}
assert set(st) == {"dzu_md", "saos_dump", "eli_inforce", "eurlex_dump"}
assert set(st) == {"dzu_md", "saos_dump", "eli_inforce", "cellar", "cellar_caselaw"}
assert st["dzu_md"]["state"] == "running" and st["dzu_md"]["commit"] == SHA1
assert st["saos_dump"]["state"] == "off" and "SAOS_DUMP_SYNC" in st["saos_dump"]["off_reason"]
assert st["eurlex_dump"]["state"] == "off"
eu = indexing.EurlexDumpImporter(ix.store, None, on=True, clock=lambda: NOW)
assert eu.status()["state"] == "idle" and "EU Login" in eu.status()["error"]
assert not eu.due(NOW)
with pytest.raises(NotImplementedError):
asyncio.run(eu.run_once())
assert st["cellar"]["state"] == "off" and "INSIDER_CELLAR_SYNC" in st["cellar"]["off_reason"]
assert "INSIDER_CELLAR_CASELAW" in st["cellar_caselaw"]["off_reason"]
assert not hasattr(indexing, "EurlexDumpImporter") # the seam is gone
def test_eurlex_fts_is_cheap():
+43 -2
View File
@@ -10,14 +10,16 @@ import random
import pytest
from conftest import integration
from app.integrations import cellar, saos_dump
from app.integrations import dzu_md as dzu
from app.integrations import saos_dump
from app.services.htmltext import html_to_text
from app.services.indexstore import PgIndexStore
pytestmark = integration
YEAR = random.randint(9000, 9999)
JID = 90_000_000_000 + random.randint(0, 10_000_000)
#: CELEX numbers of year 9xxx: never a real act
EU = [f"3{YEAR}R{n:04d}" for n in (1, 2)]
@pytest.fixture(scope="module")
@@ -25,9 +27,10 @@ def store():
from sqlalchemy import delete
from app.db import SessionLocal
from app.models import DatasetSync, DzuAct, SaosJudgment
from app.models import DatasetSync, DzuAct, EuDoc, SaosJudgment
yield PgIndexStore(SessionLocal)
with SessionLocal() as db:
db.execute(delete(EuDoc).where(EuDoc.celex.in_(EU)))
db.execute(delete(DzuAct).where(DzuAct.year == YEAR))
db.execute(delete(SaosJudgment).where(SaosJudgment.id.in_([JID, JID + 1])))
db.execute(delete(DatasetSync).where(DatasetSync.name.like("test_%")))
@@ -93,3 +96,41 @@ def test_state_and_the_run_lock(store):
again = store.acquire("dzu_md")
assert again is not None
store.release(again)
def test_eu_docs_round_trip_in_force_and_passes(store):
def eu(celex, cons=None, mod="2026-01-01"):
item = cellar.listed_act({"celex": celex, "type": "R", "force": "1", "mod": mod,
"cons": cons, "consmod": mod})
html = "<p class='oj-ti-art'>Artykuł 1</p><p>Ochrona danych.</p>"
return cellar.build_record(item, "Rozporządzenie", html, "pl")
a, b = EU
store.upsert_eu(eu(a, cons=f"0{a[1:]}-20240101"), "p1")
store.upsert_eu(eu(b), "p1")
store.upsert_eu(eu(a, cons=f"0{a[1:]}-20250101", mod="2026-02-01"), "p1") # replaces parts
d = store.get_eu_doc(a)
assert d["text_celex"].endswith("-20250101") and d["language"] == "pl" and d["in_force"]
assert store.eu_fingerprints("act")[a] == f"0{a[1:]}-20250101|2026-02-01"
assert [p["num"] for p in store.get_eu_parts(a).values()] == ["1"]
assert set(store.get_eu_docs(EU)) == set(EU)
assert store.touch_eu([a], "p2") == []
assert a not in store.unlisted_eu("act", "p2") and b in store.unlisted_eu("act", "p2")
assert store.mark_eu_out_of_force([b]) == [b] and store.mark_eu_out_of_force([b]) == []
rows = list(store.iter_eu_rows([b]))
assert rows and all("nf" in r["tags"] and "k:act" in r["tags"] for r in rows)
assert store.touch_eu([b], "p2") == [b] # back in force
n, parts = store.eu_counts("act")
assert n >= 2 and parts >= 2
def test_the_two_cellar_datasets_share_one_lock(store):
one = store.acquire("cellar")
assert one is not None
try:
assert store.acquire("cellar_caselaw") is None
assert store.acquire("cellar") is None
other = store.acquire("dzu_md")
assert other is not None
store.release(other)
finally:
store.release(one)
+59
View File
@@ -40,3 +40,62 @@ def test_title_filter():
def test_longest_word_skips_stop_words():
assert plstem.longest_word("o ochronie danych osobowych") == "osobowych"
assert plstem.longest_word("o w z") is None
# ── consonant alternations (2026-10-21): masculine-personal plurals meet their singular ─────────────
@pytest.mark.parametrize("forms,stem", [
(["sygnaliści", "sygnalista", "sygnalisty", "sygnalistów", "sygnalistom"], "sygnalist"),
(["specjaliści", "specjalista", "specjalistów"], "specjalist"),
(["studenci", "student", "studenta", "studentów"], "student"),
(["adwokaci", "adwokat", "adwokata"], "adwokat"),
(["autorzy", "autor", "autora", "autorów"], "autor"),
(["lokatorzy", "lokator", "lokatora"], "lokator"),
(["prawnicy", "prawnik", "prawnika", "prawników"], "prawnic"),
(["politycy", "polityk", "polityka"], "polityc"),
(["biolodzy", "biolog", "biologa"], "biolog"),
(["sędzia", "sędziego", "sędziów"], "sedz"),
(["prezesi", "prezes", "prezesa"], "prezes"),
])
def test_masculine_personal_plurals_share_the_singular_stem(forms, stem):
assert {plstem.stem(f) for f in forms} == {stem}
@pytest.mark.parametrize("forms,stem", [
# look-alikes that must NOT be pulled into an alternation
(["części", "część"], "czesc"),
(["granicy", "granica", "granicę"], "granic"),
(["narzędzi", "narzędzia", "narzędziami"], "narzedz"),
(["lekarzy", "lekarz", "lekarza"], "lekarz"),
(["żołnierzy", "żołnierz"], "zolnierz"),
(["własności", "własność"], "wlasn"),
(["ochrona", "ochronie"], "ochron"),
(["przekroczenie", "przekroczenia"], "przekroczen"),
(["umowa", "umowy"], "umow"),
])
def test_look_alikes_keep_their_stems(forms, stem):
assert {plstem.stem(f) for f in forms} == {stem}
def test_distinct_words_stay_apart():
assert plstem.stem("części") != plstem.stem("częste") # part ≠ frequent
assert plstem.stem("młodzy") != plstem.stem("młotek")
assert plstem.stem("płaci") == plstem.stem("płacy") # too short for -aci → -at
def test_title_filter_with_a_normalised_stem():
assert plstem.title_matches("Ustawa o ochronie sygnalistów", "sygnaliści")
assert plstem.title_matches("Rozporządzenie w sprawie załącznika", "załącznik")
assert plstem.title_matches("Ustawa o rzeczniku praw pacjenta", "rzecznik")
def test_the_index_records_the_stemmer_version(tmp_path):
from app.services.textindex import TextIndex
if not TextIndex.available:
pytest.skip("tantivy is not installed")
ix = TextIndex(tmp_path / "x")
ix.rebuild([{"group": "g", "ord": 0, "title": "t", "text": "sygnaliści"}])
assert ix.ready() and ix.meta()["stemmer"] == plstem.VERSION
meta = ix.meta() | {"stemmer": plstem.VERSION - 1}
import json
(tmp_path / "x" / "index.json").write_text(json.dumps(meta), encoding="utf-8")
assert not ix.ready() # built with another stemmer: rebuilt from Postgres
+4 -4
View File
@@ -579,9 +579,9 @@ function routeApi(r) {
}
const KIND_LABEL = { act: 'Akt prawny', judgment: 'Orzeczenie' };
const SOURCE_LABEL = { eli: 'ELI (Sejm)', saos: 'SAOS', eurlex: 'EUR-Lex', dzu_md: 'Indeks aktów', saos_index: 'Indeks SAOS' };
const SOURCE_LABEL = { eli: 'ELI (Sejm)', saos: 'SAOS', eurlex: 'EUR-Lex', dzu_md: 'Indeks aktów', saos_index: 'Indeks SAOS', cellar: 'Indeks EUR-Lex' };
/* What a source is called while it is still being asked (the pending status line). */
const PENDING_LABEL = { eli: 'ELI…', saos: 'SAOS…', eurlex: 'EUR-Lex…', dzu_md: 'Indeks…', saos_index: 'Indeks…' };
const PENDING_LABEL = { eli: 'ELI…', saos: 'SAOS…', eurlex: 'EUR-Lex…', dzu_md: 'Indeks…', saos_index: 'Indeks…', cellar: 'Indeks…' };
const TEXT_STATUS = {
ready: ['gotowy', 'ok'], pending: ['OCR w toku', 'warn'], failed: ['błąd', 'err'],
not_fetched: ['nie pobrano', ''],
@@ -622,7 +622,7 @@ function citationOf(d) {
if (d.source === 'saos') {
return `${d.court_or_publisher || 'Sąd'}, ${d.status === 'RESOLUTION' ? 'uchwała' : d.status === 'DECISION' ? 'postanowienie' : 'wyrok'} z dnia ${fmtDate(d.date)}, sygn. akt ${d.signature || ''}`.trim();
}
if (d.source === 'eurlex') {
if (d.source === 'eurlex' || d.source === 'cellar') {
return d.kind === 'judgment'
? `Wyrok TSUE z dnia ${fmtDate(d.date)}, ${x.ecli || x.celex}`
: `${d.title} (CELEX: ${x.celex})`;
@@ -908,7 +908,7 @@ function hitHtml(d, i, q) {
${d.extra && d.extra.disclaimer ? `<div class="faint tiny">${esc(d.extra.disclaimer)}</div>` : ''}</button>`;
}
function isEuDoc(d) { return d.source === 'eurlex'; }
function isEuDoc(d) { return d.source === 'eurlex' || d.source === 'cellar'; }
function slowBanner() {
return `<div class="banner slow" role="status"><span class="spin" aria-hidden="true"></span>Orzeczenia: ładowanie… (SAOS bywa wolny, do ~30 s) <span class="mono" id="slowSecs">${Math.round((Date.now() - (state._slowStart || Date.now())) / 1000)} s</span></div>`;
}