sejm_interpellations: Art. 4 wording, SIS credit, acquisition route and attribution sidecar (v2#107)

#157
by ppuzio - opened
data/sejm_interpellations/sejm_interpellations.attribution.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9f9c0724d82bfa7a56ccf92f70e22b1d6a93ef73fbec517a5e79476a7b9bc531
3
+ size 6570256
data/sejm_interpellations/sejm_interpellations.license-evidence.json CHANGED
@@ -68,6 +68,15 @@
68
  ],
69
  "quote": "teksty interpelacji, którym Prezydium Sejmu nadało bieg, są udostępniane w Systemie Informacyjnym Sejmu"
70
  },
 
 
 
 
 
 
 
 
 
71
  "api_channel": "V: the API documentation, response headers and a sampled interpellation body (term 10, no. 1) carry no terms. No source states that API output is part of SIS; SIS is defined as the www.sejm.gov.pl system (Regulamin art. 201a; Zarządzenie Szefa KS 3/2006 § 1).",
72
  "reading": "I: the commercial-offer clause is not among the conditions Open Data Act art. 15 ust. 1 allows and runs against arts 14 ust. 1, 16 and 17; it could bind only through rights the Kancelaria holds (art. 14 ust. 2), and replies are written by ministries, not the Kancelaria. The source-note clause fits art. 15 ust. 1 pkt 1; the datasheet carries the requested wording as a precaution.",
73
  "source": "artifacts/rights_audit_2026-10/reports/citations/sejm_sis.md (W1-W4, D1, D4, D7, C1-C5, L7-L15)"
@@ -90,7 +99,7 @@
90
  ],
91
  "not_checked": [
92
  "lawyer review of the statutory basis and of the SIS terms",
93
- "the live SIS page on the fetch date (bot challenge; latest readable capture 2026-06-03)",
94
  "the Kancelaria Sejmu BIP 'Ponowne wykorzystywanie' page (bip.sejm.gov.pl did not connect; Wayback answered 429)",
95
  "whether the API interpellation bodies are the same documents as those on www.sejm.gov.pl",
96
  "the exact fetch date: 2026-09-05 is inferred from the findings log, the input file date and the last record (2026-09-03)",
 
68
  ],
69
  "quote": "teksty interpelacji, którym Prezydium Sejmu nadało bieg, są udostępniane w Systemie Informacyjnym Sejmu"
70
  },
71
+ "live_capture": {
72
+ "retrieved": "2026-10-19",
73
+ "method": "read in a browser; scripted fetches get a bot-verification page, so the content block was saved from the rendered page",
74
+ "sha256_of_content_html": "cb4d21a44f5b09d50cdf95518aad77632b2750b5df6535c1d8aa894152b80469",
75
+ "archived_in": "slayerlabs/polish-dynaword-v2, evidence/sis_copyright_2026-10-19.{content.html,meta.json,md} (pull request 121)",
76
+ "source_note_present": true,
77
+ "commercial_offer_clause_present": true,
78
+ "reading": "Same source note and same commercial-offer clause as the 2026-06-03 capture. The page does not say the terms cover api.sejm.gov.pl output; the clause is reported as information, not as a licence term of this dataset."
79
+ },
80
  "api_channel": "V: the API documentation, response headers and a sampled interpellation body (term 10, no. 1) carry no terms. No source states that API output is part of SIS; SIS is defined as the www.sejm.gov.pl system (Regulamin art. 201a; Zarządzenie Szefa KS 3/2006 § 1).",
81
  "reading": "I: the commercial-offer clause is not among the conditions Open Data Act art. 15 ust. 1 allows and runs against arts 14 ust. 1, 16 and 17; it could bind only through rights the Kancelaria holds (art. 14 ust. 2), and replies are written by ministries, not the Kancelaria. The source-note clause fits art. 15 ust. 1 pkt 1; the datasheet carries the requested wording as a precaution.",
82
  "source": "artifacts/rights_audit_2026-10/reports/citations/sejm_sis.md (W1-W4, D1, D4, D7, C1-C5, L7-L15)"
 
99
  ],
100
  "not_checked": [
101
  "lawyer review of the statutory basis and of the SIS terms",
102
+ "the live SIS page on the fetch date (bot challenge then; a later live read, 2026-10-19, is in sis_terms.live_capture; latest archived capture 2026-06-03)",
103
  "the Kancelaria Sejmu BIP 'Ponowne wykorzystywanie' page (bip.sejm.gov.pl did not connect; Wayback answered 429)",
104
  "whether the API interpellation bodies are the same documents as those on www.sejm.gov.pl",
105
  "the exact fetch date: 2026-09-05 is inferred from the findings log, the input file date and the last record (2026-09-03)",
data/sejm_interpellations/sejm_interpellations.md CHANGED
@@ -16,26 +16,42 @@ ministerstw dostępnymi jako HTML.
16
 
17
  ## Licensing — traceable basis
18
 
19
- Official parliamentary materials are excluded from copyright under Polish
20
- Copyright Act art. 4 pkt 2
21
- (https://eli.gov.pl/api/acts/DU/2025/24/text/O/D20250024.pdf). Reuse of
22
- public-sector information is governed by the Polish Open Data Act arts. 2(12),
23
- 5, 14 and 17 (https://eli.gov.pl/api/acts/DU/2023/1524/text.html). Same basis
24
- as the shipped `sejm_api` shard. No Creative Commons grant is asserted.
 
 
 
 
 
 
 
 
25
 
26
  Caveats (quotes, URLs and hashes in `sejm_interpellations.license-evidence.json`;
27
  not lawyer-reviewed):
28
 
29
- - **SIS terms.** The Regulamin Sejmu places interpellations, replies and written
30
- questions in the System Informacyjny Sejmu (arts. 192 ust. 7, 193 ust. 2,
31
- 195 ust. 2). The Sejm's SIS page asks for a source note on material taken from
32
- www.sejm.gov.pl and bars SIS material from being part of a commercial offer of
33
- any agency, TV station, portal or other entity. No terms were found on
34
- api.sejm.gov.pl, in its documentation or in a sampled body, and no source says
35
- that API output is part of SIS. The commercial clause is not among the
36
- conditions Open Data Act art. 15 ust. 1 allows (see also arts. 14 ust. 1, 16
37
- and 17), so whether it binds is doubtful. As a precaution, the requested source
38
- note: Źródłem tym jest System Informacyjny Sejmu.
 
 
 
 
 
 
 
 
39
  - **Replies** are written by ministries and other bodies (named in `author`),
40
  not by the Kancelaria Sejmu.
41
  - **Third-party quotations.** In the rights audit's 3,900-document sample, 2.2%
@@ -59,11 +75,25 @@ interpellations through 2019).
59
 
60
  ## Provenance and reproducibility
61
 
 
 
 
 
 
 
 
 
 
 
62
  ```bash
63
- python3 src/fetch_sejm_interpellations.py --out ~/speakleash --terms 9,10 --workers 4
64
  python3 src/build_dynaword.py --sources sejm_interpellations --speakleash-dir ~/speakleash --out .
 
65
  ```
66
 
 
 
 
67
  `src/fetch_sejm_interpellations.py` pulls HTML `/body` endpoints, strips
68
  header chrome (nr / recipient / title / signatory / date) into `meta`, then
69
  runs pattern PII redaction (the `scrub_pii` pass from #20 at build time —
@@ -130,6 +160,24 @@ w sprawie Instytutu Polskiego w Szwajcarii, uprzejmie informuję, co
130
  następuje. […]
131
  ```
132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  ## Privacy and limitations
134
 
135
  Regex PII scrub at fetch time is not a guarantee of zero personal data.
 
16
 
17
  ## Licensing — traceable basis
18
 
19
+ **Legal status (our assessment).** We consider the interpellations, written
20
+ questions and replies in this shard official documents, excluded from copyright under
21
+ Art. 4 pkt 2 of the Polish Copyright Act (official documents, materials, signs and
22
+ symbols; text: https://eli.gov.pl/api/acts/DU/2025/24/text/O/D20250024.pdf).
23
+ That is a statement of Polish law only; their status may differ in other jurisdictions.
24
+ The label `public-domain (official documents)` is a descriptive term for this status, not
25
+ a licence: no Creative Commons public-domain mark (CC0, Public Domain Mark) is applied or
26
+ implied, and no upstream Creative Commons license is asserted. api.sejm.gov.pl states no
27
+ licence or terms of use, and we found no disclaimer on it. The statement does not extend
28
+ to third-party fragments quoted inside the documents (for example constituents' letters
29
+ and press articles), and personal data is a separate matter (see "Privacy and
30
+ limitations"). The Open Data Act (Dz. U. 2023 poz. 1524, articles 2(12), 5, 6, 14, 15 and
31
+ 17; text: https://eli.gov.pl/api/acts/DU/2023/1524/text.html) is cited as the reuse framework for the institutions' own
32
+ material, not as a basis for third-party works.
33
 
34
  Caveats (quotes, URLs and hashes in `sejm_interpellations.license-evidence.json`;
35
  not lawyer-reviewed):
36
 
37
+ - **SIS terms and credit.** The Regulamin Sejmu places interpellations, replies and written
38
+ questions in the System Informacyjny Sejmu (SIS; arts. 192 ust. 7, 193 ust. 2,
39
+ 195 ust. 2). The terms page of SIS, read on 2026-10-19, asks that material taken from
40
+ www.sejm.gov.pl name its source: "Źródłem tym jest System Informacyjny Sejmu". No terms
41
+ were found on api.sejm.gov.pl, in its documentation or in a sampled body, and no source
42
+ says that API output is part of SIS. As a precaution we give the credit:
43
+
44
+ > Źródło: System Informacyjny Sejmu (Kancelaria Sejmu RP)
45
+
46
+ The same page says that SIS material, in particular live streams and archive material
47
+ produced by iTV Sejm, "nie mogą być elementem komercyjnej oferty żadnej agencji, stacji
48
+ telewizyjnej, portalu ani innego podmiotu". We report that clause as information only.
49
+ It is not a licence term of this dataset, and we have not verified whether it reaches
50
+ these texts or binds a re-user. Our reading is that it is not among the conditions Open
51
+ Data Act art. 15 ust. 1 allows (see also arts. 14 ust. 1, 16 and 17), so whether it binds
52
+ is doubtful. A dated copy of the page (SHA-256 `cb4d21a44f5b09d50cdf95518aad77632b2750b5df6535c1d8aa894152b80469`) is kept in
53
+ polish-dynaword-v2 (`evidence/sis_copyright_2026-10-19.*`, pull request 121); the root
54
+ `NOTICE.md` has the details.
55
  - **Replies** are written by ministries and other bodies (named in `author`),
56
  not by the Kancelaria Sejmu.
57
  - **Third-party quotations.** In the rights audit's 3,900-document sample, 2.2%
 
75
 
76
  ## Provenance and reproducibility
77
 
78
+ - Route: the API directly, no intermediary. `src/fetch_sejm_interpellations.py` reads the
79
+ HTML `/body` endpoints of api.sejm.gov.pl (Kancelaria Sejmu RP); this repository names no
80
+ copy of the data held by a third party.
81
+ - Acquired: the fetch date is not recorded. The raw output file
82
+ `~/speakleash/sejm_interpellations.jsonl.zst` (26,503 lines, SHA-256
83
+ `cc06156352220b653cdab20a694560bb1e9e958af576526395ffcf10d7c14a09`) has the file time
84
+ 2026-09-05 19:42 CEST, so the fetch ended on or before that day; the latest record is dated
85
+ 2026-09-03, so it ended on or after that day. The shard's `added` date, 2026-09-05, is the
86
+ registry's date, not a measured one.
87
+
88
  ```bash
89
+ python3 src/fetch_sejm_interpellations.py --out ~/speakleash --terms 10
90
  python3 src/build_dynaword.py --sources sejm_interpellations --speakleash-dir ~/speakleash --out .
91
+ python3 src/build_sejm_interpellations_attribution.py --raw ~/speakleash/sejm_interpellations.jsonl.zst
92
  ```
93
 
94
+ A new fetch returns what the API serves on the day, so it does not reproduce this shard byte
95
+ for byte; the raw file used here is not in the repository.
96
+
97
  `src/fetch_sejm_interpellations.py` pulls HTML `/body` endpoints, strips
98
  header chrome (nr / recipient / title / signatory / date) into `meta`, then
99
  runs pattern PII redaction (the `scrub_pii` pass from #20 at build time —
 
160
  następuje. […]
161
  ```
162
 
163
+ ## Attribution sidecar
164
+
165
+ `sejm_interpellations.attribution.jsonl` has one line per Parquet row, in row order (25,950
166
+ lines): `id`, `source_url` (the API document the text came from), `term`, `num`, `kind`
167
+ (`interpellation`, `written_question`, `interpellation_reply` or `written_question_reply`),
168
+ `date` (the API's `receiptDate`), `reply_key` (replies only), `text_sha1` (SHA-1 of the
169
+ stored text) and, when other API documents have exactly the same text, `identical_text_urls`
170
+ (their URLs, in raw order). The build kept one document per distinct text: 129 rows have such
171
+ duplicates, 553 dropped documents in all. The title and the author are not repeated: the
172
+ title is header chrome kept out of the text and can name private persons (the NERGAL pass is
173
+ pending), and the author is already a column.
174
+
175
+ The shard does not record which document of a duplicate group survived. The builder
176
+ recovers it from the raw file without a new fetch: the order of the shard's rows gives the
177
+ order in which the build's worker chunks arrived, the dedup is replayed in that order and
178
+ must reproduce the shard's sequence of texts exactly, and the author on each survivor must
179
+ equal the shard's author. Any mismatch stops the build; nothing is guessed.
180
+
181
  ## Privacy and limitations
182
 
183
  Regex PII scrub at fetch time is not a guarantee of zero personal data.
src/build_sejm_interpellations_attribution.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Rebuild the per-record attribution sidecar of the sejm_interpellations shard (v2#107).
3
+
4
+ The shard was built by `build_dynaword.py` from the raw fetch output of `fetch_sejm_interpellations.py`
5
+ (`sejm_interpellations.jsonl.zst`, one JSON object per line: `text` plus `meta`). The build dropped the
6
+ `meta` and kept one row per distinct stripped text, so the shard alone does not say which API document
7
+ a row came from. This script recovers that from the raw file without a new fetch.
8
+
9
+ Which document survived a duplicate text is decided by the build, not by the text: it cuts the raw
10
+ lines into chunks of 2000, processes them in a pool with `imap_unordered` (arrival order is not
11
+ deterministic), and keeps the first row of a text it sees, so the survivor is the row from the chunk that
12
+ arrived first and, inside a chunk, the lowest line. The arrival order is not stored. It is recovered
13
+ from the shard itself: the kept rows of a chunk are contiguous in the Parquet, in line order, so the
14
+ order in which the chunks first appear among the rows whose text occurs once in the raw file is the
15
+ arrival order. The dedup is then replayed over the raw chunks in that order, and the replay must give
16
+ exactly the shard's sequence of texts; any difference raises. A chunk that cannot be placed (all its
17
+ rows share a text with another chunk) raises as well. Nothing is guessed.
18
+
19
+ Sidecar line (sorted keys, one per Parquet row, same order): `id`, `source_url` (the API document the
20
+ row came from), `term`, `num`, `kind`, `date` (the document's date), `reply_key` (replies only),
21
+ `text_sha1` (SHA-1 of the stored text), `identical_text_urls` (other API documents with the same text, in
22
+ raw order; only when there are any). The title and the author are not written: the title is
23
+ header chrome kept out of the text and can name private persons (the NERGAL pass is pending), and the
24
+ author is already a Parquet column. The author is used as a cross-check, and a mismatch raises.
25
+
26
+ Usage:
27
+ python3 src/build_sejm_interpellations_attribution.py \\
28
+ --raw ~/speakleash/sejm_interpellations.jsonl.zst
29
+ """
30
+ from __future__ import annotations
31
+
32
+ import argparse
33
+ import hashlib
34
+ import io
35
+ import json
36
+ import shutil
37
+ import subprocess
38
+ import sys
39
+ from collections import defaultdict
40
+ from pathlib import Path
41
+
42
+ ROOT = Path(__file__).resolve().parents[1]
43
+ SOURCE = "sejm_interpellations"
44
+ PARQUET = ROOT / "data" / SOURCE / f"{SOURCE}.parquet"
45
+ SIDECAR = ROOT / "data" / SOURCE / f"{SOURCE}.attribution.jsonl"
46
+ # build_dynaword.py: `_chunks(line_iter, 2000)`; test_sejm_interpellations_attribution.py keeps this in sync.
47
+ CHUNK_LINES = 2000
48
+
49
+
50
+ def sha1_hex(text: str) -> str:
51
+ return hashlib.sha1(text.encode("utf-8")).hexdigest()
52
+
53
+
54
+ def read_raw_lines(path: Path):
55
+ """Non-blank lines of the .jsonl.zst, as `build_dynaword.build_source` reads them (`zstd -dc` or zstandard)."""
56
+ executable = shutil.which("zstd")
57
+ if executable:
58
+ proc = subprocess.Popen([executable, "-dc", str(path)], stdout=subprocess.PIPE, bufsize=1 << 22)
59
+ try:
60
+ for raw in proc.stdout:
61
+ line = raw.decode("utf-8")
62
+ if line.strip():
63
+ yield line
64
+ finally:
65
+ proc.stdout.close()
66
+ if proc.wait() != 0:
67
+ raise RuntimeError(f"zstd -dc failed on {path}")
68
+ return
69
+ try:
70
+ import zstandard
71
+ except ImportError as exc:
72
+ raise RuntimeError("reading .zst requires zstd or Python zstandard: pip install zstandard") from exc
73
+ with path.open("rb") as handle:
74
+ for line in io.TextIOWrapper(zstandard.ZstdDecompressor().stream_reader(handle), encoding="utf-8"):
75
+ if line.strip():
76
+ yield line
77
+
78
+
79
+ def parse_raw(lines) -> list[dict | None]:
80
+ """One entry per non-blank line, in order (the chunk index is the line index // CHUNK_LINES).
81
+
82
+ A line that is not JSON, or has no `text`/`meta`, is None: the build skips such a line but still
83
+ counts it in its chunk, so the position is kept.
84
+ """
85
+ rows: list[dict | None] = []
86
+ for line in lines:
87
+ try:
88
+ row = json.loads(line)
89
+ text = (row.get("text") or "").strip()
90
+ meta = row["meta"]
91
+ except Exception:
92
+ rows.append(None)
93
+ continue
94
+ rows.append({"key": sha1_hex(text), "meta": meta})
95
+ return rows
96
+
97
+
98
+ def resolve(raw: list[dict | None], shard: list[dict], chunk_lines: int = CHUNK_LINES) -> list[dict]:
99
+ """For every shard row (`id`, `text`, `author`, in order) return its survivor and its duplicates.
100
+
101
+ Returns dicts `{"id", "key", "survivor": raw index, "others": [raw indices]}`. Raises ValueError on
102
+ any inconsistency between the raw file and the shard.
103
+ """
104
+ by_key: dict[str, list[int]] = defaultdict(list)
105
+ for index, row in enumerate(raw):
106
+ if row is not None:
107
+ by_key[row["key"]].append(index)
108
+
109
+ keys = []
110
+ for row in shard:
111
+ if row["text"] != row["text"].strip():
112
+ raise ValueError(f"{row['id']}: stored text is not stripped, so it is not what the build kept")
113
+ keys.append(sha1_hex(row["text"]))
114
+ if len(set(keys)) != len(keys):
115
+ raise ValueError("the shard repeats a text, so it is not the output of the exact dedup")
116
+ absent = [row["id"] for row, key in zip(shard, keys) if key not in by_key]
117
+ if absent:
118
+ raise ValueError(f"{len(absent)} shard rows have no raw line with their text (first: {absent[0]}); "
119
+ "this is not the raw file the shard was built from")
120
+
121
+ # Arrival order of the chunks: first appearance among the rows whose text occurs on one raw line.
122
+ order = list(dict.fromkeys(by_key[key][0] // chunk_lines for key in keys if len(by_key[key]) == 1))
123
+ placed = set(order)
124
+ for key in keys:
125
+ for index in by_key[key]:
126
+ if index // chunk_lines not in placed:
127
+ raise ValueError(f"chunk {index // chunk_lines} holds a kept text but no text that occurs only "
128
+ "once, so its arrival order cannot be recovered")
129
+
130
+ # Replay the build's dedup over the raw chunks in that order. A raw line whose text is not in the shard
131
+ # was dropped by a gate (length, language) before the dedup and never entered `seen`.
132
+ kept = set(keys)
133
+ seen: set[str] = set()
134
+ survivors: list[int] = []
135
+ for chunk in order:
136
+ for index in range(chunk * chunk_lines, min((chunk + 1) * chunk_lines, len(raw))):
137
+ row = raw[index]
138
+ if row is None or row["key"] not in kept or row["key"] in seen:
139
+ continue
140
+ seen.add(row["key"])
141
+ survivors.append(index)
142
+ replay = [raw[index]["key"] for index in survivors]
143
+ if replay != keys:
144
+ position = next((i for i, (a, b) in enumerate(zip(replay, keys)) if a != b), min(len(replay), len(keys)))
145
+ raise ValueError(f"the replayed dedup differs from the shard at row {position} "
146
+ f"(replay has {len(replay)} rows, shard {len(keys)})")
147
+
148
+ return [{"id": row["id"], "key": key, "survivor": survivor,
149
+ "others": [i for i in by_key[key] if i != survivor]}
150
+ for row, key, survivor in zip(shard, keys, survivors)]
151
+
152
+
153
+ def sidecar_lines(raw: list[dict | None], shard: list[dict], chunk_lines: int = CHUNK_LINES) -> list[str]:
154
+ resolved = resolve(raw, shard, chunk_lines)
155
+ lines = []
156
+ for row, hit in zip(shard, resolved):
157
+ meta = raw[hit["survivor"]]["meta"]
158
+ if (meta.get("author") or "").strip() != (row["author"] or "").strip():
159
+ raise ValueError(f"{row['id']}: author {row['author']!r} in the shard, {meta.get('author')!r} on the "
160
+ f"survivor {meta.get('url')}")
161
+ record = {"id": row["id"], "source_url": meta["url"], "term": meta["term"], "num": meta["num"],
162
+ "kind": meta["kind"], "date": meta["date"], "text_sha1": hit["key"]}
163
+ if meta.get("reply_key"):
164
+ record["reply_key"] = meta["reply_key"]
165
+ others = [raw[i]["meta"]["url"] for i in hit["others"]]
166
+ if others:
167
+ record["identical_text_urls"] = others
168
+ lines.append(json.dumps(record, ensure_ascii=False, sort_keys=True))
169
+ return lines
170
+
171
+
172
+ def read_shard(path: Path) -> list[dict]:
173
+ import pyarrow.parquet as pq
174
+ table = pq.read_table(path, columns=["id", "text", "author"])
175
+ return [{"id": i, "text": t, "author": a} for i, t, a in
176
+ zip(table["id"].to_pylist(), table["text"].to_pylist(), table["author"].to_pylist())]
177
+
178
+
179
+ def main(argv=None) -> int:
180
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
181
+ ap.add_argument("--raw", required=True, type=Path, help="sejm_interpellations.jsonl.zst from fetch_sejm_interpellations.py")
182
+ ap.add_argument("--parquet", type=Path, default=PARQUET)
183
+ ap.add_argument("--out", type=Path, default=SIDECAR)
184
+ args = ap.parse_args(argv)
185
+ raw = parse_raw(read_raw_lines(args.raw.expanduser()))
186
+ shard = read_shard(args.parquet)
187
+ lines = sidecar_lines(raw, shard)
188
+ args.out.write_text("".join(line + "\n" for line in lines), encoding="utf-8")
189
+ duplicates = sum(1 for line in lines if '"identical_text_urls"' in line)
190
+ print(f"{args.out}: {len(lines):,} rows from {len(raw):,} raw lines; {duplicates:,} rows have identical-text duplicates")
191
+ return 0
192
+
193
+
194
+ if __name__ == "__main__":
195
+ sys.exit(main())
src/test_sejm_interpellations_attribution.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for the sejm_interpellations attribution sidecar builder (v2#107)."""
2
+ import io
3
+ import json
4
+ import random
5
+ import re
6
+ import shutil
7
+ import sys
8
+ import tempfile
9
+ import unittest
10
+ from pathlib import Path
11
+
12
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
13
+
14
+ import build_sejm_interpellations_attribution as B
15
+
16
+ ROOT = Path(__file__).resolve().parent.parent
17
+ DATA = ROOT / "data" / "sejm_interpellations"
18
+ PARQUET = DATA / "sejm_interpellations.parquet"
19
+ SIDECAR = DATA / "sejm_interpellations.attribution.jsonl"
20
+ STATS = DATA / "sejm_interpellations.stats.json"
21
+ SOURCE_CODE = Path(__file__).resolve().parent / "build_dynaword.py"
22
+
23
+
24
+ def meta(num, author="A", kind="interpellation", reply_key=None, date="2024-01-01"):
25
+ suffix = f"/reply/{reply_key}/body" if reply_key else "/body"
26
+ m = {"url": f"https://api.sejm.gov.pl/sejm/term10/interpellations/{num}{suffix}", "term": 10, "num": num,
27
+ "kind": kind, "title": f"title {num}", "date": date, "author": author}
28
+ if reply_key:
29
+ m["reply_key"] = reply_key
30
+ return m
31
+
32
+
33
+ def raw_rows(spec):
34
+ """spec: list of (text, num) or (text, num, extra-meta dict); None for an unparseable line."""
35
+ rows = []
36
+ for item in spec:
37
+ if item is None:
38
+ rows.append(None)
39
+ continue
40
+ text, num, *extra = item
41
+ rows.append({"key": B.sha1_hex(text.strip()), "meta": meta(num, **(extra[0] if extra else {}))})
42
+ return rows
43
+
44
+
45
+ def simulate_build(texts, authors, order, chunk_lines):
46
+ """The shard `build_source` writes when its chunks arrive in `order`: global `seen`, a chunk's rows in line order."""
47
+ seen, shard = set(), []
48
+ for chunk in order:
49
+ for i in range(chunk * chunk_lines, min((chunk + 1) * chunk_lines, len(texts))):
50
+ text = texts[i]
51
+ if text is None or B.sha1_hex(text) in seen:
52
+ continue
53
+ seen.add(B.sha1_hex(text))
54
+ shard.append({"id": f"s_{len(shard)}", "text": text, "author": authors[i], "line": i})
55
+ return shard
56
+
57
+
58
+ class ResolveTest(unittest.TestCase):
59
+ def test_no_duplicates_every_row_is_its_own_survivor(self):
60
+ raw = raw_rows([("a", 1), ("b", 2), ("c", 3), ("d", 4)])
61
+ shard = [{"id": f"s{i}", "text": t, "author": "A"} for i, t in enumerate("abcd")]
62
+ out = B.resolve(raw, shard, chunk_lines=2)
63
+ self.assertEqual([h["survivor"] for h in out], [0, 1, 2, 3])
64
+ self.assertTrue(all(h["others"] == [] for h in out))
65
+
66
+ def test_arrival_order_decides_which_duplicate_survives(self):
67
+ # chunk 0 = [x, u1], chunk 1 = [x, u2]; x is on lines 0 and 2
68
+ raw = raw_rows([("x", 1), ("u1", 2), ("x", 3), ("u2", 4)])
69
+ first = [{"id": "s0", "text": "x", "author": "A"}, {"id": "s1", "text": "u1", "author": "A"},
70
+ {"id": "s2", "text": "u2", "author": "A"}]
71
+ self.assertEqual([h["survivor"] for h in B.resolve(raw, first, chunk_lines=2)], [0, 1, 3])
72
+ second = [{"id": "s0", "text": "x", "author": "A"}, {"id": "s1", "text": "u2", "author": "A"},
73
+ {"id": "s2", "text": "u1", "author": "A"}]
74
+ # chunk 1 arrived first: its x (line 2) survives, and its rows come before chunk 0's
75
+ out = B.resolve(raw, second, chunk_lines=2)
76
+ self.assertEqual([h["survivor"] for h in out], [2, 3, 1])
77
+ self.assertEqual(out[0]["others"], [0])
78
+
79
+ def test_duplicate_inside_one_chunk_keeps_the_lowest_line(self):
80
+ raw = raw_rows([("x", 1), ("x", 2), ("y", 3), ("z", 4)])
81
+ shard = [{"id": "s0", "text": "x", "author": "A"}, {"id": "s1", "text": "y", "author": "A"},
82
+ {"id": "s2", "text": "z", "author": "A"}]
83
+ out = B.resolve(raw, shard, chunk_lines=4)
84
+ self.assertEqual([h["survivor"] for h in out], [0, 2, 3])
85
+ self.assertEqual(out[0]["others"], [1])
86
+
87
+ def test_texts_are_compared_stripped(self):
88
+ raw = raw_rows([(" x\n", 1), ("x", 2), ("y", 3), ("z", 4)])
89
+ shard = [{"id": "s0", "text": "x", "author": "A"}, {"id": "s1", "text": "y", "author": "A"},
90
+ {"id": "s2", "text": "z", "author": "A"}]
91
+ out = B.resolve(raw, shard, chunk_lines=4)
92
+ self.assertEqual((out[0]["survivor"], out[0]["others"]), (0, [1]))
93
+
94
+ def test_gated_raw_line_is_ignored(self):
95
+ # "tiny" never reached the dedup (a gate dropped it): it is not in the shard and changes nothing
96
+ raw = raw_rows([("x", 1), ("tiny", 2), ("y", 3), ("x", 4), ("z", 5), ("w", 6)])
97
+ shard = [{"id": f"s{i}", "text": t, "author": "A"} for i, t in enumerate("xyzw")]
98
+ out = B.resolve(raw, shard, chunk_lines=3)
99
+ self.assertEqual([h["survivor"] for h in out], [0, 2, 4, 5])
100
+ self.assertEqual(out[0]["others"], [3])
101
+
102
+ def test_unparseable_line_keeps_its_position_in_the_chunk(self):
103
+ raw = raw_rows([("x", 1), None, ("y", 3), ("z", 4)])
104
+ shard = [{"id": "s0", "text": "x", "author": "A"}, {"id": "s1", "text": "y", "author": "A"},
105
+ {"id": "s2", "text": "z", "author": "A"}]
106
+ # chunks of 2: [x, None] [y, z]; arrival order is read off x then y
107
+ self.assertEqual([h["survivor"] for h in B.resolve(raw, shard, chunk_lines=2)], [0, 2, 3])
108
+
109
+ def test_chunk_that_cannot_be_placed_raises(self):
110
+ # chunk 1 = [x, y] repeats the texts of chunk 0 = [x, y]: no text occurs once there, so its place is unknown
111
+ raw = raw_rows([("x", 1), ("y", 2), ("x", 3), ("y", 4), ("z", 5), ("w", 6)])
112
+ shard = [{"id": "s0", "text": "x", "author": "A"}, {"id": "s1", "text": "y", "author": "A"},
113
+ {"id": "s2", "text": "z", "author": "A"}, {"id": "s3", "text": "w", "author": "A"}]
114
+ with self.assertRaisesRegex(ValueError, "arrival order cannot be recovered"):
115
+ B.resolve(raw, shard, chunk_lines=2)
116
+
117
+ def test_shard_that_the_replay_cannot_reproduce_raises(self):
118
+ raw = raw_rows([("x", 1), ("y", 2), ("z", 3), ("w", 4)])
119
+ swapped = [{"id": "s0", "text": "y", "author": "A"}, {"id": "s1", "text": "x", "author": "A"},
120
+ {"id": "s2", "text": "z", "author": "A"}, {"id": "s3", "text": "w", "author": "A"}]
121
+ with self.assertRaisesRegex(ValueError, "replayed dedup differs from the shard at row 0"):
122
+ B.resolve(raw, swapped, chunk_lines=2)
123
+
124
+ def test_text_not_in_the_raw_file_raises(self):
125
+ raw = raw_rows([("x", 1), ("y", 2)])
126
+ shard = [{"id": "s0", "text": "x", "author": "A"}, {"id": "s1", "text": "other", "author": "A"}]
127
+ with self.assertRaisesRegex(ValueError, "not the raw file"):
128
+ B.resolve(raw, shard, chunk_lines=2)
129
+
130
+ def test_unstripped_or_repeated_shard_text_raises(self):
131
+ raw = raw_rows([("x", 1), ("y", 2)])
132
+ with self.assertRaisesRegex(ValueError, "not stripped"):
133
+ B.resolve(raw, [{"id": "s0", "text": "x ", "author": "A"}], chunk_lines=2)
134
+ with self.assertRaisesRegex(ValueError, "repeats a text"):
135
+ B.resolve(raw, [{"id": "s0", "text": "x", "author": "A"}, {"id": "s1", "text": "x", "author": "A"}],
136
+ chunk_lines=2)
137
+
138
+ def test_random_builds_are_recovered_for_every_arrival_order(self):
139
+ rng = random.Random(20261019)
140
+ for trial in range(200):
141
+ chunk_lines = rng.choice([2, 3, 5])
142
+ n = rng.randint(6, 30)
143
+ pool = [f"text {k}" for k in range(rng.randint(3, n))]
144
+ texts = [rng.choice(pool) for _ in range(n)]
145
+ authors = [f"author {i}" for i in range(n)]
146
+ n_chunks = -(-n // chunk_lines)
147
+ order = list(range(n_chunks))
148
+ rng.shuffle(order)
149
+ shard = simulate_build(texts, authors, order, chunk_lines)
150
+ raw = raw_rows([(t, i, {"author": authors[i]}) for i, t in enumerate(texts)])
151
+ try:
152
+ out = B.resolve(raw, [{k: v for k, v in r.items() if k != "line"} for r in shard], chunk_lines)
153
+ except ValueError as exc:
154
+ # the only allowed failure: a chunk whose texts all occur in other chunks too
155
+ self.assertIn("arrival order cannot be recovered", str(exc), (trial, texts, order))
156
+ continue
157
+ self.assertEqual([h["survivor"] for h in out], [r["line"] for r in shard], (trial, texts, order))
158
+
159
+
160
+ class SidecarLinesTest(unittest.TestCase):
161
+ def setUp(self):
162
+ self.raw = raw_rows([
163
+ ("question text", 1, {"author": "Poseł", "kind": "interpellation", "date": "2024-01-02"}),
164
+ ("reply text", 2, {"author": "Minister", "kind": "interpellation_reply", "reply_key": "R1",
165
+ "date": "2024-02-03"}),
166
+ ("question text", 9, {"author": "Poseł 2", "kind": "interpellation"}),
167
+ ])
168
+ self.shard = [{"id": "s0", "text": "question text", "author": "Poseł"},
169
+ {"id": "s1", "text": "reply text", "author": "Minister"}]
170
+
171
+ def test_fields_and_order(self):
172
+ lines = B.sidecar_lines(self.raw, self.shard, chunk_lines=3)
173
+ first, second = [json.loads(line) for line in lines]
174
+ self.assertEqual(first, {
175
+ "id": "s0", "source_url": "https://api.sejm.gov.pl/sejm/term10/interpellations/1/body", "term": 10,
176
+ "num": 1, "kind": "interpellation", "date": "2024-01-02", "text_sha1": B.sha1_hex("question text"),
177
+ "identical_text_urls": ["https://api.sejm.gov.pl/sejm/term10/interpellations/9/body"]})
178
+ self.assertEqual(second["reply_key"], "R1")
179
+ self.assertNotIn("identical_text_urls", second)
180
+ self.assertEqual(list(first), sorted(first)) # keys sorted
181
+ for record in (first, second):
182
+ self.assertNotIn("title", record)
183
+ self.assertNotIn("author", record)
184
+
185
+ def test_author_mismatch_raises(self):
186
+ self.shard[0]["author"] = "Someone else"
187
+ with self.assertRaisesRegex(ValueError, "s0: author"):
188
+ B.sidecar_lines(self.raw, self.shard, chunk_lines=3)
189
+
190
+ def test_author_comparison_ignores_surrounding_whitespace(self):
191
+ self.shard[0]["author"] = " Poseł "
192
+ self.assertEqual(len(B.sidecar_lines(self.raw, self.shard, chunk_lines=3)), 2)
193
+
194
+
195
+ class ParseRawTest(unittest.TestCase):
196
+ def test_bad_lines_become_none_and_keep_their_position(self):
197
+ rows = B.parse_raw(['{"text": " a ", "meta": {"url": "u"}}\n', "not json\n", '{"text": "b"}\n',
198
+ '{"text": null, "meta": {}}\n'])
199
+ self.assertEqual(rows[0], {"key": B.sha1_hex("a"), "meta": {"url": "u"}})
200
+ self.assertIsNone(rows[1])
201
+ self.assertIsNone(rows[2]) # no meta
202
+ self.assertEqual(rows[3], {"key": B.sha1_hex(""), "meta": {}})
203
+
204
+ def test_read_raw_lines_skips_blank_lines(self):
205
+ payload = b'{"text": "a", "meta": {}}\n\n \n{"text": "b", "meta": {}}\n'
206
+ with tempfile.TemporaryDirectory() as tmp:
207
+ path = Path(tmp) / "x.jsonl.zst"
208
+ try:
209
+ import zstandard
210
+ path.write_bytes(zstandard.ZstdCompressor().compress(payload))
211
+ except ImportError:
212
+ if not shutil.which("zstd"):
213
+ self.skipTest("no zstandard and no zstd binary")
214
+ import subprocess
215
+ path.write_bytes(subprocess.run(["zstd", "-c"], input=payload, capture_output=True, check=True).stdout)
216
+ self.assertEqual(len(list(B.read_raw_lines(path))), 2)
217
+
218
+
219
+ class ChunkSizeTest(unittest.TestCase):
220
+ def test_chunk_size_matches_build_dynaword(self):
221
+ self.assertIn(f"_chunks(line_iter, {B.CHUNK_LINES})", SOURCE_CODE.read_text(encoding="utf-8"))
222
+
223
+
224
+ @unittest.skipUnless(SIDECAR.is_file() and PARQUET.is_file(), "sidecar not built")
225
+ class ShippedSidecarTest(unittest.TestCase):
226
+ @classmethod
227
+ def setUpClass(cls):
228
+ import pyarrow.parquet as pq
229
+ cls.table = pq.read_table(PARQUET, columns=["id", "text"])
230
+ cls.lines = [json.loads(line) for line in SIDECAR.read_text(encoding="utf-8").splitlines()]
231
+ cls.stats = json.loads(STATS.read_text(encoding="utf-8"))
232
+
233
+ def test_one_line_per_row_in_parquet_order(self):
234
+ self.assertEqual([r["id"] for r in self.lines], self.table["id"].to_pylist())
235
+
236
+ def test_text_sha1_matches_the_stored_text(self):
237
+ for record, text in zip(self.lines, self.table["text"].to_pylist()):
238
+ self.assertEqual(record["text_sha1"], B.sha1_hex(text), record["id"])
239
+
240
+ def test_every_raw_document_is_accounted_for_once(self):
241
+ urls = [r["source_url"] for r in self.lines] + [u for r in self.lines for u in r.get("identical_text_urls", [])]
242
+ self.assertEqual(len(urls), len(set(urls)))
243
+ self.assertEqual(len(urls), self.stats["read"] - self.stats["drop_short"] - self.stats["drop_lang"]
244
+ - self.stats["drop_ocr"])
245
+ self.assertEqual(sum(len(r.get("identical_text_urls", [])) for r in self.lines), self.stats["drop_dup"])
246
+
247
+ def test_urls_agree_with_their_fields(self):
248
+ pattern = re.compile(r"^https://api\.sejm\.gov\.pl/sejm/term(\d+)/(interpellations|writtenQuestions)/(\d+)"
249
+ r"(?:/reply/([A-Z0-9]+))?/body$")
250
+ collection = {"interpellation": "interpellations", "interpellation_reply": "interpellations",
251
+ "written_question": "writtenQuestions", "written_question_reply": "writtenQuestions"}
252
+ for record in self.lines:
253
+ for url in [record["source_url"]] + record.get("identical_text_urls", []):
254
+ self.assertRegex(url, pattern)
255
+ term, coll, num, key = pattern.match(record["source_url"]).groups()
256
+ self.assertEqual((int(term), int(num), key), (record["term"], record["num"], record.get("reply_key")))
257
+ self.assertEqual(coll, collection[record["kind"]], record["id"])
258
+ self.assertEqual(record["kind"].endswith("_reply"), key is not None, record["id"])
259
+ self.assertRegex(record["date"], r"^\d{4}-\d{2}-\d{2}$")
260
+
261
+ def test_no_title_or_author_is_shipped(self):
262
+ self.assertFalse({"title", "author"} & {k for r in self.lines for k in r})
263
+
264
+
265
+ if __name__ == "__main__":
266
+ unittest.main()
src/test_sejm_interpellations_contract.py CHANGED
@@ -186,6 +186,25 @@ class SejmInterpellationsRecordsTest(unittest.TestCase):
186
  self.assertEqual(self.evidence["sis_terms"]["quotes"]["source_note_wording"], sis_note)
187
  self.assertIn(EVIDENCE.name, self.card)
188
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
 
190
  if __name__ == "__main__":
191
  unittest.main()
 
186
  self.assertEqual(self.evidence["sis_terms"]["quotes"]["source_note_wording"], sis_note)
187
  self.assertIn(EVIDENCE.name, self.card)
188
 
189
+ def test_card_credits_sis_and_keeps_the_label_descriptive(self):
190
+ # v2#107: credit line, clause as information only, no licence claim, route and sidecar named
191
+ self.assertIn("Źródło: System Informacyjny Sejmu (Kancelaria Sejmu RP)", self.card)
192
+ self.assertIn("komercyjnej oferty", self.card)
193
+ self.assertIn("information only", self.card)
194
+ self.assertIn("not a licence", self.card)
195
+ self.assertIn("Art. 4 pkt 2 of the Polish Copyright Act", self.card)
196
+ self.assertIn("the API directly, no intermediary", self.card)
197
+ self.assertIn("sejm_interpellations.attribution.jsonl", self.card)
198
+ self.assertNotIn("--workers", self.card)
199
+
200
+ def test_evidence_records_the_live_capture_of_the_sis_page(self):
201
+ live = self.evidence["sis_terms"]["live_capture"]
202
+ self.assertEqual(live["retrieved"], "2026-10-19")
203
+ self.assertRegex(live["sha256_of_content_html"], r"^[0-9a-f]{64}$")
204
+ self.assertIn(live["sha256_of_content_html"], self.card)
205
+ self.assertTrue(live["source_note_present"])
206
+ self.assertTrue(live["commercial_offer_clause_present"])
207
+
208
 
209
  if __name__ == "__main__":
210
  unittest.main()