forked from ChelseaKR/fare-policy-assistant
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_ingest_pipeline.py
More file actions
615 lines (522 loc) · 20.5 KB
/
Copy pathtest_ingest_pipeline.py
File metadata and controls
615 lines (522 loc) · 20.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
"""Ingest pipeline tests: fetch (mocked HTTP), process, and the CLI dispatch.
The fetch path is exercised against an in-memory transport so no real network
request is made; the process path runs end to end over a tiny temp corpus and is
read back with `load_chunks`. These cover the manifest-driven plumbing that the
section/table tests (test_ingest.py, test_pdf_ingest.py) do not.
"""
from __future__ import annotations
import hashlib
import httpx
import pytest
import yaml
from assistant import config
from assistant.ingest import load_chunks, main, process_all
from assistant.snapshots import SnapshotArchiveError
# Capture the genuine client class before any test patches the (shared) httpx
# module, so the mock factory can build a real client with a MockTransport
# without recursing into itself.
_REAL_CLIENT = httpx.Client
def _mock_client(handler):
return lambda **kw: _REAL_CLIENT(transport=httpx.MockTransport(handler), **kw)
def _point_config_at(tmp_path, monkeypatch, manifest: dict):
raw = tmp_path / "raw"
processed = tmp_path / "processed"
manifest_path = tmp_path / "manifest.yaml"
manifest_path.write_text(yaml.safe_dump(manifest), encoding="utf-8")
monkeypatch.setattr(config, "MANIFEST_PATH", manifest_path)
monkeypatch.setattr(config, "RAW_DIR", raw)
monkeypatch.setattr(config, "PROCESSED_DIR", processed)
monkeypatch.setattr(config, "CHUNKS_PATH", processed / "chunks.jsonl")
# process_all() archives into VERSIONS_DIR (EXP-05); keep that under
# tmp_path too so tests never write into the repo's real corpus/versions/.
monkeypatch.setattr(config, "VERSIONS_DIR", tmp_path / "versions")
monkeypatch.setattr(config, "SNAPSHOTS_DIR", tmp_path / "snapshots")
monkeypatch.setattr(config, "FACTS_PATH", processed / "facts.jsonl")
return raw, processed
_HTML_DOC = """<html><head><title>Fares</title></head><body><main>
<h1>Fares</h1>
<h2>Discount Eligibility</h2>
<p>Discount fare for riders 65 years and older, and individuals with
disabilities. Proof of age such as a Medicare card is required when boarding the
bus on any fixed-route service the district runs across the county.</p>
</main></body></html>"""
def _write_html_snapshot(
raw,
*,
doc_id: str = "mst-fares",
url: str = "https://mst.org/fares/",
fetch_date: str = "2026-06-12",
) -> None:
content = _HTML_DOC.encode()
raw.mkdir(parents=True, exist_ok=True)
(raw / f"{doc_id}.html").write_bytes(content)
receipt = {
"doc_id": doc_id,
"url": url,
"final_url": url,
"fetch_date": fetch_date,
"http_status": 200,
"format": "html",
"sha256": hashlib.sha256(content).hexdigest(),
"bytes": len(content),
}
(raw / f"{doc_id}.meta.yaml").write_text(
yaml.safe_dump(receipt, sort_keys=False),
encoding="utf-8",
)
# ── fetch (mocked transport) ─────────────────────────────────────────────────
def test_fetch_all_writes_snapshot_and_meta(tmp_path, monkeypatch):
manifest = {
"user_agent": "test-agent/0.1",
"crawl_delay_seconds": 7,
"documents": [
{
"id": "mst-fares",
"agency": "MST",
"agency_full": "Monterey-Salinas Transit",
"title": "Fares",
"url": "https://mst.org/fares/",
"language": "en",
},
{
"id": "mst-fares-2",
"agency": "MST",
"agency_full": "Monterey-Salinas Transit",
"title": "More",
"url": "https://mst.org/fares/more/",
"language": "en",
},
],
}
raw, _ = _point_config_at(tmp_path, monkeypatch, manifest)
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(
200, content=_HTML_DOC.encode(), headers={"content-type": "text/html"}
)
monkeypatch.setattr("assistant.ingest.httpx.Client", _mock_client(handler))
slept: list[float] = []
monkeypatch.setattr("assistant.ingest.time.sleep", lambda s: slept.append(s))
from assistant import ingest
ingest.fetch_all()
assert (raw / "mst-fares.html").exists()
meta = yaml.safe_load((raw / "mst-fares.meta.yaml").read_text())
assert meta["http_status"] == 200 and meta["format"] == "html"
assert len(meta["sha256"]) == 64
# Two docs on the same host → the crawl delay slept once between them.
assert slept, "expected a crawl-delay sleep between same-host requests"
def test_fetch_all_pdf_is_sniffed_from_content_type(tmp_path, monkeypatch):
manifest = {
"user_agent": "test-agent/0.1",
"crawl_delay_seconds": 0,
"documents": [
{
"id": "policy",
"agency": "MST",
"agency_full": "MST",
"title": "Policy",
"url": "https://mst.org/p.pdf",
"language": "en",
}
],
}
raw, _ = _point_config_at(tmp_path, monkeypatch, manifest)
def handler(request):
return httpx.Response(
200, content=b"%PDF-1.4 fake", headers={"content-type": "application/pdf"}
)
monkeypatch.setattr("assistant.ingest.httpx.Client", _mock_client(handler))
from assistant import ingest
ingest.fetch_all()
assert (raw / "policy.pdf").exists()
def test_fetch_all_records_failures_and_exits_nonzero(tmp_path, monkeypatch):
manifest = {
"user_agent": "test-agent/0.1",
"crawl_delay_seconds": 0,
"documents": [
{
"id": "gone",
"agency": "MST",
"agency_full": "MST",
"title": "Gone",
"url": "https://mst.org/404",
"language": "en",
}
],
}
_point_config_at(tmp_path, monkeypatch, manifest)
def handler(request):
return httpx.Response(404, content=b"not found")
monkeypatch.setattr("assistant.ingest.httpx.Client", _mock_client(handler))
import pytest
from assistant import ingest
with pytest.raises(SystemExit):
ingest.fetch_all()
def test_fetch_all_keeps_partial_success_and_reports_what_failed(tmp_path, monkeypatch):
"""One unreachable source must not discard the sources that answered.
Regression test for the corpus-freshness loop: every scheduled run from
2026-07-13 to 2026-08-10 exited non-zero because some documents 404'd or
403'd, which aborted the step before ingest and threw away the documents
that had fetched successfully. Yolobus went two months past a published
fare change as a result.
"""
import json as _json
manifest = {
"user_agent": "test-agent/0.1",
"crawl_delay_seconds": 0,
"documents": [
{
"id": "reachable",
"agency": "Yolobus",
"agency_full": "Yolobus",
"title": "Fares",
"url": "https://yolobus.com/fares/",
"language": "en",
},
{
"id": "blocked",
"agency": "MST",
"agency_full": "MST",
"title": "Fares",
"url": "https://mst.org/fares/",
"language": "en",
},
],
}
_point_config_at(tmp_path, monkeypatch, manifest)
def handler(request):
if "mst.org" in str(request.url):
return httpx.Response(403, content=b"forbidden")
return httpx.Response(200, content=b"<html><body><main>Fares</main></body></html>")
monkeypatch.setattr("assistant.ingest.httpx.Client", _mock_client(handler))
from assistant import config, ingest
ingest.fetch_all() # must NOT raise: one source answered
assert (config.RAW_DIR / "reachable.html").exists()
assert (config.RAW_DIR / "reachable.meta.yaml").exists()
assert not (config.RAW_DIR / "blocked.html").exists()
report = _json.loads((config.RAW_DIR / "fetch-failures.json").read_text())
assert [f["doc_id"] for f in report["failed"]] == ["blocked"]
def test_fetch_all_clears_a_stale_failure_report_on_a_clean_run(tmp_path, monkeypatch):
manifest = {
"user_agent": "test-agent/0.1",
"crawl_delay_seconds": 0,
"documents": [
{
"id": "reachable",
"agency": "Yolobus",
"agency_full": "Yolobus",
"title": "Fares",
"url": "https://yolobus.com/fares/",
"language": "en",
}
],
}
_point_config_at(tmp_path, monkeypatch, manifest)
page = b"<html><body><main>x</main></body></html>"
monkeypatch.setattr(
"assistant.ingest.httpx.Client",
_mock_client(lambda r: httpx.Response(200, content=page)),
)
from assistant import config, ingest
config.RAW_DIR.mkdir(parents=True, exist_ok=True)
stale = config.RAW_DIR / "fetch-failures.json"
stale.write_text('{"failed": [{"doc_id": "blocked", "error": "old"}]}\n', encoding="utf-8")
ingest.fetch_all()
assert not stale.exists(), "a clean run must not leave last week's failures readable as current"
def test_fetch_all_only_filter_skips_unselected_docs(tmp_path, monkeypatch):
manifest = {
"user_agent": "test-agent/0.1",
"crawl_delay_seconds": 0,
"documents": [
{
"id": "keep",
"agency": "MST",
"agency_full": "MST",
"title": "K",
"url": "https://mst.org/keep",
"language": "en",
},
{
"id": "skip",
"agency": "MST",
"agency_full": "MST",
"title": "S",
"url": "https://mst.org/skip",
"language": "en",
},
],
}
raw, _ = _point_config_at(tmp_path, monkeypatch, manifest)
monkeypatch.setattr(
"assistant.ingest.httpx.Client",
_mock_client(
lambda r: httpx.Response(
200, content=_HTML_DOC.encode(), headers={"content-type": "text/html"}
)
),
)
from assistant import ingest
ingest.fetch_all(only={"keep"})
assert (raw / "keep.html").exists()
assert not (raw / "skip.html").exists()
# ── process + load round trip ────────────────────────────────────────────────
def test_process_all_round_trips_through_load_chunks(tmp_path, monkeypatch):
manifest = {
"user_agent": "test-agent/0.1",
"crawl_delay_seconds": 0,
"documents": [
{
"id": "mst-fares",
"agency": "MST",
"agency_full": "Monterey-Salinas Transit",
"title": "Fares",
"url": "https://mst.org/fares/",
"language": "en",
}
],
}
raw, processed = _point_config_at(tmp_path, monkeypatch, manifest)
_write_html_snapshot(raw)
process_all()
# A processed markdown view and the chunk index were both written.
assert (processed / "mst-fares.md").exists()
chunks = load_chunks()
assert chunks, "process_all produced at least one chunk"
c = chunks[0]
assert c.agency == "MST" and c.doc_id == "mst-fares"
assert c.fetch_date == "2026-06-12"
assert "65 years and older" in " ".join(ch.text for ch in chunks)
def test_process_all_archives_the_corpus_version(tmp_path, monkeypatch):
"""EXP-05: process_all() retains this content under corpus/versions/<id>/,
not just corpus/processed/, so a later re-ingest cannot erase it."""
from assistant import corpus
manifest = {
"user_agent": "test-agent/0.1",
"crawl_delay_seconds": 0,
"documents": [
{
"id": "mst-fares",
"agency": "MST",
"agency_full": "Monterey-Salinas Transit",
"title": "Fares",
"url": "https://mst.org/fares/",
"language": "en",
}
],
}
raw, _ = _point_config_at(tmp_path, monkeypatch, manifest)
_write_html_snapshot(raw)
process_all()
live_chunks = load_chunks()
version = corpus.corpus_version(live_chunks)
archived = corpus.load_chunks(version)
assert [c.chunk_id for c in archived] == [c.chunk_id for c in live_chunks]
assert version in corpus.list_versions()
snapshot = config.VERSIONS_DIR / version / "manifest.snapshot.yaml"
assert "mst-fares" in snapshot.read_text(encoding="utf-8")
from assistant.snapshots import list_snapshots, load_snapshot_chunks
snapshots = list_snapshots()
assert len(snapshots) == 1
assert [c.chunk_id for c in load_snapshot_chunks(snapshots[0])] == [
c.chunk_id for c in live_chunks
]
def test_process_all_fails_if_any_manifest_document_has_no_snapshot(tmp_path, monkeypatch):
manifest = {
"user_agent": "test-agent/0.1",
"crawl_delay_seconds": 0,
"documents": [
{
"id": "missing",
"agency": "MST",
"agency_full": "MST",
"title": "Fares",
"url": "https://mst.org/fares/",
"language": "en",
}
],
}
_, processed = _point_config_at(tmp_path, monkeypatch, manifest)
processed.mkdir(parents=True)
with pytest.raises(SnapshotArchiveError, match="metadata for missing"):
process_all()
assert not config.CHUNKS_PATH.exists()
def test_process_all_archives_the_exact_bytes_used_to_derive_chunks(
tmp_path,
monkeypatch,
):
from assistant import ingest
from assistant.snapshots import list_snapshots
manifest = {
"user_agent": "test-agent/0.1",
"crawl_delay_seconds": 0,
"documents": [
{
"id": "mst-fares",
"agency": "MST",
"agency_full": "Monterey-Salinas Transit",
"title": "Fares",
"url": "https://mst.org/fares/",
"language": "en",
}
],
}
raw, _ = _point_config_at(tmp_path, monkeypatch, manifest)
_write_html_snapshot(raw)
original_bytes = (raw / "mst-fares.html").read_bytes()
replacement_bytes = original_bytes.replace(b"65 years", b"99 years")
original_sections_from_html = ingest.sections_from_html
def replace_working_source_after_parse(html: str):
sections = original_sections_from_html(html)
(raw / "mst-fares.html").write_bytes(replacement_bytes)
replacement_receipt = {
"doc_id": "mst-fares",
"url": "https://mst.org/fares/",
"final_url": "https://mst.org/fares/",
"fetch_date": "2026-06-12",
"http_status": 200,
"format": "html",
"sha256": hashlib.sha256(replacement_bytes).hexdigest(),
"bytes": len(replacement_bytes),
}
(raw / "mst-fares.meta.yaml").write_text(
yaml.safe_dump(replacement_receipt, sort_keys=False),
encoding="utf-8",
)
return sections
monkeypatch.setattr(
ingest,
"sections_from_html",
replace_working_source_after_parse,
)
process_all()
live_text = " ".join(chunk.text for chunk in load_chunks())
assert "65 years" in live_text
assert "99 years" not in live_text
[snapshot_id] = list_snapshots()
archived_raw = (config.SNAPSHOTS_DIR / snapshot_id / "raw" / "mst-fares.html").read_bytes()
assert archived_raw == original_bytes
assert (raw / "mst-fares.html").read_bytes() == replacement_bytes
def test_archive_failure_leaves_prior_live_chunks_untouched(tmp_path, monkeypatch):
manifest = {
"user_agent": "test-agent/0.1",
"crawl_delay_seconds": 0,
"documents": [
{
"id": "mst-fares",
"agency": "MST",
"agency_full": "Monterey-Salinas Transit",
"title": "Fares",
"url": "https://mst.org/fares/",
"language": "en",
}
],
}
raw, processed = _point_config_at(tmp_path, monkeypatch, manifest)
_write_html_snapshot(raw)
processed.mkdir(parents=True)
original = b'{"prior":"serving"}\n'
config.CHUNKS_PATH.write_bytes(original)
def fail_archive(*args, **kwargs):
raise RuntimeError("injected archive failure")
monkeypatch.setattr("assistant.snapshots.archive_snapshot", fail_archive)
with pytest.raises(RuntimeError, match="injected archive failure"):
process_all()
assert config.CHUNKS_PATH.read_bytes() == original
def test_legacy_archive_failure_leaves_prior_live_chunks_untouched(
tmp_path,
monkeypatch,
):
manifest = {
"user_agent": "test-agent/0.1",
"crawl_delay_seconds": 0,
"documents": [
{
"id": "mst-fares",
"agency": "MST",
"agency_full": "Monterey-Salinas Transit",
"title": "Fares",
"url": "https://mst.org/fares/",
"language": "en",
}
],
}
raw, processed = _point_config_at(tmp_path, monkeypatch, manifest)
_write_html_snapshot(raw)
processed.mkdir(parents=True)
original = b'{"prior":"serving"}\n'
config.CHUNKS_PATH.write_bytes(original)
def fail_legacy_archive(*args, **kwargs):
raise RuntimeError("injected legacy archive failure")
monkeypatch.setattr("assistant.corpus.archive_version", fail_legacy_archive)
with pytest.raises(RuntimeError, match="injected legacy archive failure"):
process_all()
assert config.CHUNKS_PATH.read_bytes() == original
# ── CLI dispatch ─────────────────────────────────────────────────────────────
def test_main_process_dispatch(tmp_path, monkeypatch):
manifest = {
"user_agent": "x",
"crawl_delay_seconds": 0,
"documents": [
{
"id": "mst-fares",
"agency": "MST",
"agency_full": "MST",
"title": "Fares",
"url": "https://mst.org/fares/",
"language": "en",
}
],
}
raw, processed = _point_config_at(tmp_path, monkeypatch, manifest)
_write_html_snapshot(raw)
monkeypatch.setattr("sys.argv", ["ingest", "process"])
main()
assert (processed / "chunks.jsonl").exists()
def test_dash_m_invocation_archives_with_the_canonical_chunk_class(tmp_path, monkeypatch):
# Regression: ``python -m assistant.ingest process`` runs this module as
# ``__main__``, whose Chunk class is a distinct object from
# ``assistant.ingest.Chunk``. Before the ``__main__`` delegation shim,
# identity validation rejected every CLI-produced chunk with
# "chunks[0] must be a Chunk" and the archive step crashed, which is how
# the scheduled corpus-freshness loop silently lost its process stage.
# Drive the real ``-m`` path with runpy rather than calling main().
import runpy
import sys
import warnings
manifest = {
"user_agent": "x",
"crawl_delay_seconds": 0,
"documents": [
{
"id": "mst-fares",
"agency": "MST",
"agency_full": "MST",
"title": "Fares",
"url": "https://mst.org/fares/",
"language": "en",
}
],
}
raw, processed = _point_config_at(tmp_path, monkeypatch, manifest)
_write_html_snapshot(raw)
monkeypatch.setattr(sys, "argv", ["assistant.ingest", "process"])
with warnings.catch_warnings():
# runpy warns that assistant.ingest is already imported; that shadowed
# double-import is precisely the condition under test.
warnings.simplefilter("ignore", RuntimeWarning)
runpy.run_module("assistant.ingest", run_name="__main__")
assert (processed / "chunks.jsonl").exists()
snapshots = tmp_path / "snapshots"
assert snapshots.exists() and any(snapshots.iterdir()), (
"the -m entrypoint must reach the snapshot archive step with canonically-typed chunks"
)
def test_main_unknown_command_exits():
import pytest
monkeypatch_argv = ["ingest", "frobnicate"]
import sys
old = sys.argv
sys.argv = monkeypatch_argv
try:
with pytest.raises(SystemExit, match="unknown command"):
main()
finally:
sys.argv = old