Swedish Tax Bench: Legal Research That Survives a Review
- Recovered missing HTML section anchors during statutory ingestion so renumbered VAT provisions keep separate bodies and valid official Riksdag citations.
- Enforced jurisdiction and effective-date eligibility before ranking, combining exact catalog lookups with FTS5 BM25 and MiniLM provision-level fusion.
- Removed free-form LLM answer generation from the public research path, returning verbatim statutory text with numeric-checked Marian translations in English and Turkish.
- Staged Chroma vectors and Fernet-encrypted SQLite chunks behind cryptographic verification and atomic pointer swaps, reaching 49.63 req/s at 156.51 ms p95 across four warm clients.
15 statutes and regulations. 10,041 indexed chunks. 5,763 evidence groups. 3 workspace languages.
Swedish Tax Bench is a public research application for Swedish tax law. A user asks a question in plain language or pastes a statutory citation. The system locates the relevant provision, selects the applicable version where the corpus supports it and presents the text beside its official source. The same workspace operates in Swedish, English and Turkish.
The application represents the open-source component of a system our team developed for a European public institution. The public release uses published Swedish legislation. That separation makes the engineering inspectable while preserving the confidentiality of the institutional engagement. The public workspace runs independently.
Open the live workspace ↗ · Inspect the public implementation ↗

Live public research workspace running on published Swedish tax legislation.
| 15 statutes and regulations | 10,041 indexed chunks | 5,763 evidence groups | 3 workspace languages |
|---|---|---|---|
| Selected Swedish tax legislation | Statute bodies, transitions and annexes | Provision versions, transition entries and annexes | Swedish original, English and Turkish translations |
Why legal retrieval starts as a question of evidence
A revenue officer reviewing a transaction from an earlier quarter needs to know what the rule said on that date. A tax advisor needs to see the exception printed immediately below the paragraph that sets the rate. An English-speaking resident needs the official Swedish wording to stay one click away. All three can ask the same question, and all three need a result that holds up when another person checks it.
General search boxes treat topical relevance as the finish line. Legal research works differently. Jurisdiction and effective dates decide what is eligible to rank in the first place, and provenance gives a reviewer a direct path back to the promulgated statute. We built both constraints directly into the corpus schema and request router after testing how standard parsers failed on a Swedish food VAT amendment.
1. Follow the amendment when the section number moves
The Swedish VAT feed gave us a concrete parser trap. In the consolidated Riksdag HTML, the provision governing food appeared as a plain-text section label right after the provision on sport. Standard HTML extraction locates sections through structural anchors. Relying on anchors alone merges the food rules into the sport provision, attaching the wrong statutory citation before a single vector is computed.
Our parser detects the renumbering notation, derives the chapter from the preceding statutory anchor and inserts an explicit internal boundary before extracting either rule. The index then resolves the food provision under its own section number while pointing its public citation to the official chapter whenever the upstream HTML lacks a section anchor. A dedicated regression fixture places both provisions side by side and verifies that each keeps its own body and citation path. (Corpus builder · Parser regression)

Sweden’s investment savings account (investeringssparkonto, ISK) rules exposed a second failure mode. Consolidated feeds can carry two different wordings under the same section number without clean markup separating when each applies. Rather than overwriting earlier text, the builder isolates each wording in its own version group and records the promulgating SFS amendment that backs it. Eligibility checks run before retrieval so a reviewer can trace the selected text straight to the earlier amendment or the replacement amendment.
2. Put the language model only where it earns its keep
A statutory citation is a lookup key, not an open-ended prompt. When a user supplies a statute, chapter and section reference, the router resolves the exact provision version in the catalog without computing a query embedding. Broad questions such as “Who is subject to unlimited income tax liability in Sweden?” benefit from dense semantic matching. Narrow statutory terms buried inside an exception, such as dricksvattendirektivet, need lexical matching even when vector similarity is weak.
We separated those request paths cleanly. Known references hit the provision catalog. Historical queries run an explicit date-interval check and, where supported, verified topic mappings. Open-ended searches fuse SQLite FTS5 (BM25 across titles, headings and body text) with multilingual MiniLM vectors in Chroma. Ranking operates on whole provision groups rather than loose chunks: when a long rule matches across four fragments, it claims a single slot in the results and reassembles its full text in original statutory order. (Search router · Provision reconstruction)

Early CPU profiling also settled the output format. An initial retrieval-and-generation path spent several seconds inside Llama inference whenever long statutory context was attached. Because a legal researcher needs the exact wording and its qualifications rather than a paraphrase, we removed free-form generation from the primary workspace path. The service returns the provision itself and invokes neural models strictly for translation when requested, while keeping the legacy generation endpoint available for compatibility. (Research service · Benchmark harness)
3. Make a translation failure a usable research result
A neural translation can read smoothly while dropping a percentage rate, altering a threshold or collapsing two numbered exceptions into one. In tax work, fluent prose is worthless if a number moves. Swedish queries therefore render the original statutory text untouched. English uses a pinned Helsinki-NLP Marian model, and Turkish runs a second Marian pass from the verified English output.
Every translation pass extracts numeric values from both source and output, normalizing Swedish, English and Turkish decimal and thousands separators. If a number disappears, an extra figure appears or a long clause hits the token ceiling, the engine retries on shorter sentence boundaries. If the retry still fails verification, the workspace still delivers the statutory finding and official link alongside a clear translation status badge. Reviewers never lose the underlying evidence. (Translation & numeric gate)
Interface state follows the same discipline. Switching the workspace language updates navigation, sample prompts, notices, voice controls and result cards together. Changing languages mid-search dispatches a fresh request and blocks stale responses from overwriting the active view. Where the browser supports local speech recognition, voice dictation populates the query box on-device so the researcher can inspect the wording before submitting. (Browser workspace · Local dictation)
4. Publish a readable snapshot even when one store fails
Chroma and SQLite carry distinct responsibilities in this architecture. Chroma holds dense vectors and citation metadata. SQLite stores ordered chunk text encrypted at rest with Fernet, while a readable corpus copy feeds the in-memory lexical index. Updating two persistent stores in place creates a classic split-brain hazard: a mid-run crash can leave new vectors pointing at missing SQLite rows or pair old statutory text with a new amendment label.
We modeled index publication as an immutable release pipeline. Corpus files, embedding weights and text-normalization logic are fingerprinted together. Every new release builds inside an isolated staging directory. Before anything goes live, a store verifier checks Chroma IDs, vector dimensions and provenance metadata against SQLite integrity and decrypted Fernet chunk text from the frozen snapshot. Only when every check passes does the launcher swap the active release pointer under a filesystem lock. Running workers finish serving from the snapshot they opened at startup, and the prior verified release stays on disk for instant rollback. (Release pipeline · Ingest safety tests · Release tests)
| Scenario exercised | Verified runtime behavior |
|---|---|
| Input contains an invalid row while operator requested a reset | Pre-flight validation aborts the run before existing stores are cleared |
| Chroma rejects a batch while an existing SQLite row updates | Batch-level rollback restores SQLite to the prior row state |
| Staged candidate fails cross-store verification | Active release pointer stays pinned to the current verified release |
| Requested rollback target fails integrity verification | Rollback is refused and the current verified release remains active |
| Source metadata changes while normalized chunk text stays identical | Existing compatible vectors are reused and updated metadata is written |

5. Measure the application people actually wait for
We benchmarked both steady-state research queries and cold deployment rollouts so operational planning rests on measured numbers rather than guesswork.
On warm local HTTP replay, the benchmark harness ran 12 reference cases six times per concurrency profile (72 requests per run, 288 requests across four profiles). Every 72-request profile returned 60 verified statutory findings passing source and translation checks alongside 12 expected abstentions for out-of-scope jurisdictions or uncovered historical intervals. With four closed-loop clients matching the four worker slots, the server completed 49.63 requests per second at 156.51 ms p95 latency. Pushing load to eight clients lifted completed throughput to 56.35 requests per second while queuing raised p95 latency to 205.32 ms.

Hosted container rollout runs on a separate clock. During the observed Hugging Face Docker Space release, the new container built and verified its full 10,041-chunk index before opening the service listener. Container startup to open port took roughly 7 minutes 40 seconds (with staged ingest accounting for 6 minutes 44 seconds), while the preceding container continued serving live traffic without interruption. Seven live post-cutover checks then verified current VAT, historical VAT, ISK amendment cutovers, whole-period coverage, unsupported jurisdiction refusal and paragraph-body term retrieval.

Technology stack and trade-off ledger
| Layer | Technologies | Role in production |
|---|---|---|
| Corpus engineering | Python 3.12, Riksdag SFS HTML, promulgated SFS PDFs, JSONL, SHA-256 | Recover section boundaries, pin official provenance and record effective intervals |
| Hybrid retrieval | SQLite FTS5 & BM25, ChromaDB 1.5.6, multilingual MiniLM-L12-v2, Sentence Transformers 5.3.0 | Resolve exact citations, match body-level statutory terms and rank cross-lingual queries |
| Encrypted store | SQLite, Python cryptography, Fernet symmetric encryption | Authenticate and decrypt ordered provision chunks by ID |
| Checked translation | PyTorch 2.5.1 CPU, Transformers 5.5.0, Helsinki-NLP Marian, SentencePiece | Translate selected provisions on CPU and enforce passage-level numeric parity |
| Research workspace | Gradio 5.50.0, Vanilla JS, Shadow DOM, browser-local speech recognition | Keep UI language independent of legal jurisdiction and guard concurrent requests |
| Release & verification | Docker, Hugging Face Spaces, filesystem locks, atomic pointer swap, 23 unittest suites | Stage, cross-verify, deploy and benchmark complete releases |
Every architectural choice addressed a specific failure mode observed in statutory material:
| Candidate approach | Failure mode in statutory research | Shipped engineering decision |
|---|---|---|
| Store one consolidated record per section | Earlier ISK wording vanishes when an amendment overwrites the section | Version each wording separately with explicit effective dates and SFS proof links |
| Run nearest-neighbor vector search on every query | Legally adjacent sections outrank exact citations or superseded historical rules | Check jurisdiction and temporal eligibility first; reserve hybrid fusion for open questions |
| Rank and display raw embedding chunks | Exceptions land in neighboring chunks while one long section floods top results | Fuse scores at the provision group level and reconstruct complete text in statutory order |
| Refresh vector and text stores in place | Mid-ingest failure pairs new metadata with old wording | Verify staged Chroma and Fernet SQLite stores together before atomic pointer promotion |
| Trust fluent neural translation blindly | Tax rates, thresholds or list counts drift silently | Enforce passage-level numeric verification and keep the official Swedish link attached |
Human accountability at the right boundaries
Software can enforce parser boundaries, date intervals, numeric parity and release integrity on every request, yet institutional authority still belongs to accountable specialists. In a public-sector deployment, legal and fiscal owners define source hierarchy, effective dates and transition coverage. Engineering owns cross-store verification, bounded concurrency and rollback readiness. The authorized case officer verifies the facts of the matter against the official wording and records the administrative decision inside the institution’s workflow.

The same architecture transfers directly to municipal fee schedules governed by transition clauses, customs and tariff classifications with annex-only exceptions, regulatory compliance manuals and healthcare or financial audit archives where answers must cite the exact rule in force on a given date.
Useful engagements start with the edge cases your reviewers already debate. Bring us the superseded fee schedule, the annex exception or the multilingual public service workflow, and we will turn those constraints into a verified corpus model, a repeatable acceptance suite and a release process your legal and engineering leads can sign off with confidence. Explore our broader AI integration and legal & professional services capabilities, discuss a public-sector project with ORZED ↗ or read the deep technical write-up on gokce.ai ↗.
Frequently asked questions
Why does Swedish Tax Bench return verbatim statutory provisions instead of generated summaries?
In fiscal and legal workflows, a fluent summary that drops an exception or shifts a rate creates audit risk. Early CPU profiling also showed free-form Llama generation adding seconds of latency. Returning the exact provision in chunk order alongside its official Swedish source gives officers and advisors verifiable legal text, while neural models handle only checked translation when requested.
How does the system prevent a partial database failure from serving mismatched legal text and citations?
Publication runs as a staged release rather than an in-place refresh. Corpus inputs, model files and normalization code are fingerprinted, and a verifier reconciles Chroma IDs, vector dimensions and metadata against decrypted Fernet SQLite chunks before flipping the active release pointer under a file lock.
How are tax rates and monetary thresholds protected during English and Turkish translation?
Swedish queries display the original statute text directly. English and Turkish views run through pinned Helsinki-NLP Marian models where every passage is checked to ensure numeric values match the source across decimal and thousands separators, retrying on shorter sentence boundaries or surfacing an explicit translation status while preserving the official link.
How does temporal retrieval distinguish superseded wording from the currently active statute?
Rather than overwriting a section number with a single consolidated record, the corpus builder stores distinct wording versions in separate evidence groups tied to their promulgating SFS amendments and effective intervals. Eligibility checks filter provisions before ranking.