Add P0 infrastructure for the Volve-DIA benchmark
Set up the data, parsing and quality-control layer for a public benchmark on the Volve daily drilling reports (DDR) and WITSML real-time data. - Data manifest with SHA-256 hashes of the three Volve subtrees in use. - DDR XML parser into DuckDB (1,759 reports, 26 wellbores, 23,447 activities, 17 tables) with locked expected counts. - Render QC of the publisher HTML against the XML (272,544 items). - OCR client for the shared chandra vLLM service, with a page cache keyed on model, prompt hash, dpi, max_tokens and temperature, and OCR QC against the HTML on a 26-report pilot. - Run logging (scripts/runlog.sh, logs/index.csv), the P0 runner and 40 tests. - Research plan, technical overview and progress page (in Vietnamese). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
34
tests/test_ddr_xml.py
Normal file
34
tests/test_ddr_xml.py
Normal file
@@ -0,0 +1,34 @@
|
||||
"""volve_dia.ddr.xml on the Volve DDR XML files (skipped without the data)."""
|
||||
|
||||
import pytest
|
||||
|
||||
from volve_dia import paths
|
||||
from volve_dia.ddr.xml import parse_dir, parse_file
|
||||
|
||||
XML = paths.ddr_xml_dir()
|
||||
pytestmark = [pytest.mark.data, pytest.mark.skipif(not XML.is_dir(), reason="missing the DDR XML folder")]
|
||||
|
||||
|
||||
def test_parse_file():
|
||||
p = parse_file(XML / "15_9_F_12_2008_01_01.xml")
|
||||
r = p.report
|
||||
assert (r["report_id"], r["wellbore"], r["file_wellbore"], r["file_date"]) == (
|
||||
"15_9_F_12_2008_01_01", "15/9-F-12", "15/9-F-12", "2008-01-01")
|
||||
assert r["nameWellbore"] == "NO 15/9-F-12" and r["dTimStart"] == "2007-12-31T00:00:00+01:00"
|
||||
assert (r["reportNo"], r["daysAhead"], r["tightWell"], r["waterDepth"]) == (98, 110.6, 0, 91.0)
|
||||
assert r["distDrill"] is None and p.sentinels[("reports", "distDrill")] == 1 # -999.99 in the file
|
||||
assert p.units[("reports", "waterDepth")] == ("m", "")
|
||||
assert {k: len(v) for k, v in p.sections.items()} == {"fluids": 1, "pore_pressure": 1, "activities": 19}
|
||||
a = p.sections["activities"][0]
|
||||
assert (a["act_id"], a["code_main"], a["code_sub"], a["state"], a["md"]) == (
|
||||
"15_9_F_12_2008_01_01:000", "drilling", "bop/wellhead equipment", "ok", 0.0)
|
||||
|
||||
|
||||
def test_parse_dir_counts():
|
||||
t = parse_dir(XML)
|
||||
r, a = t["reports"], t["activities"]
|
||||
assert len(r) == 1759 and r["wellbore"].nunique() == 26 and r["stem_ok"].all()
|
||||
assert len(a) == 23447 and (a["state"] == "fail").sum() == 480
|
||||
assert (a["stateDetailActivity"] == "equipment failure").sum() == 1975
|
||||
assert (a["duration_h"] > 0).all() and a["act_id"].is_unique
|
||||
assert t["units"].groupby(["table", "column"]).size().max() == 1
|
||||
35
tests/test_names.py
Normal file
35
tests/test_names.py
Normal file
@@ -0,0 +1,35 @@
|
||||
"""volve_dia.names: every spelling of a Volve wellbore maps to one canonical NPD code."""
|
||||
|
||||
import pytest
|
||||
|
||||
from volve_dia.names import canonical, stem, well_of
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name, expected", [
|
||||
("NO 15/9-F-15 A", "15/9-F-15 A"), # DDR nameWellbore
|
||||
("15_9_F_15_A", "15/9-F-15 A"), # DDR file stem
|
||||
("15/9-F-15 A", "15/9-F-15 A"), # NPD code
|
||||
("Norway-StatoilHydro-15_$47$_9-F-15A", "15/9-F-15 A"), # WITSML folder
|
||||
("15/9-F-15A", "15/9-F-15 A"), # MetaFileInfo.txt
|
||||
("NO 15/9-F-1 B", "15/9-F-1 B"),
|
||||
("Norway-Statoil-NO 15_$47$_9-F-1 C", "15/9-F-1 C"),
|
||||
("NA-NA-15_$47$_9-F-5", "15/9-F-5"),
|
||||
("15_9_F_11_T2", "15/9-F-11 T2"),
|
||||
("15_9_19_BT2", "15/9-19 BT2"),
|
||||
("15_9_19_S", "15/9-19 S"),
|
||||
(" NO 15/9-F-12 ", "15/9-F-12"),
|
||||
])
|
||||
def test_canonical(name, expected):
|
||||
assert canonical(name) == expected
|
||||
|
||||
|
||||
def test_stem_and_well():
|
||||
assert stem("NO 15/9-F-15 A") == "15_9_F_15_A"
|
||||
assert stem("15/9-19 BT2") == "15_9_19_BT2"
|
||||
assert well_of("Norway-StatoilHydro-15_$47$_9-F-15A") == "15/9-F-15"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["", "F-15", "15/9", "Volve"])
|
||||
def test_rejects_non_wellbores(name):
|
||||
with pytest.raises(ValueError):
|
||||
canonical(name)
|
||||
79
tests/test_ocr_blocks.py
Normal file
79
tests/test_ocr_blocks.py
Normal file
@@ -0,0 +1,79 @@
|
||||
"""volve_dia.ocr without the service: block parsing, the loop cut, the config and service checks and the page
|
||||
cache."""
|
||||
|
||||
import dataclasses
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from volve_dia import ocr
|
||||
|
||||
CFG = dataclasses.replace(ocr.load_config(), loop_chars=60, loop_max_unit=10)
|
||||
|
||||
PAGE = ('<div data-bbox="10 20 990 60" data-label="Page-Header"><p>Summary report</p></div>'
|
||||
'<div data-bbox="10 70 500 90" data-label="Section-Header"><p><b>Operations</b></p></div>'
|
||||
'<div data-bbox="0 0 0 0" data-label="Picture"></div>'
|
||||
'<div data-bbox="10 100 990 400" data-label="Table"><table><tr><th>Start time</th><th>Remark</th></tr>'
|
||||
'<tr><td>00:00</td><td>MÆRSK & co<br>line 2</td></tr></table></div>'
|
||||
'<div data-bbox="a b c d" data-label="Weird"><p>kept as paragraph</p></div>')
|
||||
|
||||
|
||||
def test_html_blocks():
|
||||
blocks = ocr.html_blocks(PAGE, 3)
|
||||
assert [b.label for b in blocks] == ["page_header", "section_header", "table", "paragraph"] # empty block dropped
|
||||
assert [b.raw_label for b in blocks] == ["Page-Header", "Section-Header", "Table", "Weird"]
|
||||
assert [b.reading_order for b in blocks] == [0, 1, 2, 3] and {b.page for b in blocks} == {3}
|
||||
assert blocks[0].bbox == [10.0, 20.0, 990.0, 60.0] and blocks[3].bbox == []
|
||||
assert blocks[2].text == "Start time | Remark\n00:00 | MÆRSK & co\nline 2"
|
||||
assert blocks[2].html.startswith("<table>") and blocks[1].html == "<p><b>Operations</b></p>"
|
||||
|
||||
|
||||
def test_bbox():
|
||||
assert ocr.bbox(["1", "2", "3", "4.06"]) == [1.0, 2.0, 3.0, 4.1]
|
||||
assert ocr.bbox({"xyxy_normalized_1000": [1, 2, 3, 4]}) == [1.0, 2.0, 3.0, 4.0]
|
||||
assert ocr.bbox([1, 2, 3]) == [] and ocr.bbox(None) == []
|
||||
|
||||
|
||||
def test_loop_start_cuts_a_trailing_repetition():
|
||||
head = "Real text. "
|
||||
assert ocr.loop_start(head + "<tr></tr>" * 20, CFG) == len(head)
|
||||
# the cut goes back to where the repetition starts, here the head's own closing tag
|
||||
assert ocr.loop_start("<td>real</td></tr>" + "<tr></tr>" * 20, CFG) == len("<td>real</td>")
|
||||
assert ocr.loop_start("no loop here, just text " * 2, CFG) is None # shorter than loop_chars
|
||||
assert ocr.loop_start("".join(chr(65 + i % 26) + str(i) for i in range(40)), CFG) is None
|
||||
|
||||
|
||||
def test_prompt_hash_is_checked(tmp_path):
|
||||
prompt = tmp_path / "prompt.txt"
|
||||
prompt.write_text("a different prompt")
|
||||
cfg = tmp_path / "ocr.yaml"
|
||||
cfg.write_text(ocr.CONFIG.read_text().replace("prompt_file: configs/ocr-prompt.txt",
|
||||
f"prompt_file: {prompt}"))
|
||||
with pytest.raises(ocr.OCRError, match="prompt changed"):
|
||||
ocr.load_config(cfg)
|
||||
|
||||
|
||||
def test_cache_is_keyed_by_settings(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("VOLVE_DIA_OUTPUTS", str(tmp_path))
|
||||
rec = {"doc_sha256": "ab" * 32, "page": 2, **CFG.key(), "status": "ok", "content": PAGE}
|
||||
ocr._write(rec)
|
||||
assert ocr.page_file(rec["doc_sha256"], 2).is_file()
|
||||
assert ocr.cached(rec["doc_sha256"], 2, CFG)["content"] == PAGE
|
||||
assert ocr.cached(rec["doc_sha256"], 1, CFG) is None
|
||||
assert ocr.cached(rec["doc_sha256"], 2, dataclasses.replace(CFG, dpi=150)) is None
|
||||
blocks, records = ocr.load_blocks(rec["doc_sha256"], 2, CFG)
|
||||
assert [r["status"] for r in records] == ["missing", "ok"] and len(blocks) == 4 and blocks[0].page == 2
|
||||
|
||||
|
||||
def test_check_service_refuses_a_service_that_is_down_or_serves_another_model():
|
||||
def client(status, body):
|
||||
return httpx.Client(base_url="http://ocr.invalid", transport=httpx.MockTransport(
|
||||
lambda request: httpx.Response(status, **body)))
|
||||
|
||||
ocr.check_service(client(200, {"json": {"data": [{"id": "chandra"}]}}), CFG)
|
||||
for status, body, message in [(503, {"text": "<html>Pod not running</html>"}, "HTTP 503"),
|
||||
(200, {"json": {"data": [{"id": "other"}]}}, "does not serve 'chandra'"),
|
||||
(200, {"text": "<html>login</html>"}, "did not answer JSON")]:
|
||||
with pytest.raises(ocr.OCRError, match=message) as err:
|
||||
ocr.check_service(client(status, body), CFG)
|
||||
assert "ocr.invalid" not in str(err.value)
|
||||
85
tests/test_qc.py
Normal file
85
tests/test_qc.py
Normal file
@@ -0,0 +1,85 @@
|
||||
"""volve_dia.ddr.qc: equality, row alignment, label matching and what the XML says the HTML should print."""
|
||||
|
||||
from volve_dia.ddr import qc
|
||||
from volve_dia.ddr.rendered import Rendered, Table
|
||||
|
||||
|
||||
def test_equalities():
|
||||
assert qc.exact("a b\n", "a b") and not qc.exact("a", None) and not qc.exact("1353", "1353.0")
|
||||
assert qc.same_value("1353", "1353.0") and qc.same_value("-999.99", "") and qc.same_value("None", "")
|
||||
assert not qc.same_value("", "x") and not qc.same_value("a", None) and qc.same_value("10 3/4", "10 3/4")
|
||||
|
||||
|
||||
def test_align_skips_missing_and_dissimilar_rows():
|
||||
a = [["00:00", "moved the BOP"], ["01:00", "tested"], ["02:00", "pulled out of hole"]]
|
||||
assert qc.align(a, [a[0], a[2]]) == [(0, 0), (2, 1)]
|
||||
assert qc.align(a, [["xx", "completely different"]]) == []
|
||||
assert qc.align([], a) == []
|
||||
|
||||
|
||||
def test_compare_counts_misread_labels_and_inventions():
|
||||
ref = Rendered(fields={"rig name": "MÆRSK INSPIRER", "status": "normal"},
|
||||
tables={"Operations": Table(["Start time", "Remark"], [["00:00", "Moved"], ["03:30", "Tested"]])})
|
||||
hyp = Rendered(fields={"rig nam": "MERSK INSPIRER", "status": "normal", "bogus": "1"},
|
||||
tables={"Operations": Table(None, [["Start time", "Remark"], ["03:30", "Tested"],
|
||||
["04:00", "Invented row"]])})
|
||||
items = {(i["part"], i["key"], i["row"]): i for i in qc.compare(ref, hyp)}
|
||||
label, field = items[("field_label", "rig name", -1)], items[("field", "rig name", -1)]
|
||||
assert not label["exact"] and label["hyp"] == "rig nam" # misread label, still matched
|
||||
assert not field["exact"] and field["edits"] == 1 and field["chars"] == 14
|
||||
assert items[("field", "status", -1)]["exact"]
|
||||
assert items[("field_extra", "bogus", -1)]["hyp"] == "bogus: 1"
|
||||
assert items[("colhead", "Start time", -1)]["exact"] # header row not recognised as one
|
||||
assert items[("cell", "Remark", 0)]["hyp"] is None # row 0 was not read
|
||||
assert items[("cell", "Remark", 1)]["exact"]
|
||||
assert items[("row_extra", "", 1)]["hyp"] == "04:00 | Invented row"
|
||||
assert not {"header_extra", "field_extra", "text_extra", "table_extra"} & {
|
||||
i["part"] for i in qc.compare(ref, hyp, extras=False)}
|
||||
|
||||
|
||||
def test_compare_pairs_labels_by_place_and_counts_invented_header_text():
|
||||
ref = Rendered(header={"wellbore": "15/9-F-15"}, fields={"tight well": "N", "hpht": "Y", "temperature": ""})
|
||||
hyp = Rendered(header={"wellbore": "15/9-F-15", "other": "Printed: 2008-10-04 00:00"},
|
||||
fields={"tight well": "N", "hptt": "Y", "temperature": ""})
|
||||
items = {(i["part"], i["key"]): i for i in qc.compare(ref, hyp)}
|
||||
assert items[("field", "hpht")]["exact"] and not items[("field_label", "hpht")]["exact"] # ratio 75: by place
|
||||
assert not any(p == "field_extra" for p, _ in items)
|
||||
assert items[("header_extra", "other")]["hyp"] == "Printed: 2008-10-04 00:00"
|
||||
|
||||
|
||||
def test_compare_maps_columns_by_header_when_their_number_differs():
|
||||
ref = Rendered(tables={"A": Table(["Start", "Activity", "State", "Remark"], [["00:00", "drilling -- trip", "ok",
|
||||
"Moved"]]),
|
||||
"B": Table(["Start", "Remark"], [["01:00", "Tested"]])})
|
||||
hyp = Rendered(tables={"A": Table(["Start", "Activity", "Remark"], [["00:00", "drilling -- ok trip", "Moved"]]),
|
||||
"B": Table(["Start", "Remark", "Note"], [["01:00", "Tested", "x"]])})
|
||||
items = {(i["part"], i["table"], i["key"]): i for i in qc.compare(ref, hyp)}
|
||||
assert items[("cell", "A", "State")]["hyp"] is None and items[("colhead", "A", "State")]["hyp"] is None
|
||||
assert items[("cell", "A", "Remark")]["exact"] and items[("cell", "A", "Activity")]["edits"] == 3
|
||||
assert items[("col_extra", "B", "Note")]["hyp"] == "Note | x" and items[("cell", "B", "Remark")]["exact"]
|
||||
|
||||
|
||||
def test_from_xml_prints_like_the_publisher():
|
||||
report = {"wellbore": "15/9-F-12", "dTimStart": "2007-12-31T00:00:00+01:00",
|
||||
"dTimEnd": "2008-01-01T00:00:00+01:00", "tightWell": 0, "hpht": 1, "waterDepth": 91.0,
|
||||
"reportNo": 98, "sum24Hr": "Installed the BOP.", "forecast24Hr": None}
|
||||
acts = [{"seq": 1, "dTimStart": "2007-12-31T03:30:00+01:00", "dTimEnd": "2008-01-01T00:00:00+01:00", "md": 0.0,
|
||||
"proprietaryCode": "drilling -- bop/wellhead equipment", "state": "ok", "comments": "Tested."},
|
||||
{"seq": 0, "dTimStart": "2007-12-31T00:00:00+01:00", "dTimEnd": "2007-12-31T03:30:00+01:00",
|
||||
"md": 12.5, "proprietaryCode": "drilling -- bop/wellhead equipment", "state": "ok", "comments": "Moved."}]
|
||||
r = qc.from_xml(report, acts)
|
||||
assert r.header == {"wellbore": "15/9-F-12", "period": "2007-12-31 00:00 - 2008-01-01 00:00"}
|
||||
assert r.fields["tight well"] == "N" and r.fields["hpht"] == "Y" and r.fields["water depth msl"] == "91"
|
||||
assert r.fields["report number"] == "98" and r.fields["wellbore type"] == ""
|
||||
assert r.texts == {"Summary of activities (24 Hours)": "Installed the BOP.",
|
||||
"Summary of planned activities (24 Hours)": ""}
|
||||
assert r.tables["Operations"].rows == [["00:00", "03:30", "12.5", "drilling -- bop/wellhead equipment", "ok",
|
||||
"Moved."],
|
||||
["03:30", "00:00", "0", "drilling -- bop/wellhead equipment", "ok",
|
||||
"Tested."]]
|
||||
|
||||
|
||||
def test_html_for_xml_drops_units():
|
||||
r = qc.html_for_xml(Rendered(header={"wellbore": "NO 15/9-F-12"}, fields={"hole dia (in)": "8.5",
|
||||
"hole dia ()": "", "status": "x"}))
|
||||
assert r.header["wellbore"] == "15/9-F-12" and r.fields == {"hole dia": "8.5", "status": "x"}
|
||||
91
tests/test_rendered.py
Normal file
91
tests/test_rendered.py
Normal file
@@ -0,0 +1,91 @@
|
||||
"""volve_dia.ddr.rendered: the publisher HTML and chandra's blocks reduce to the same `Rendered` report."""
|
||||
|
||||
from volve_dia.ddr.rendered import Rendered, Table, parse_html, parse_ocr
|
||||
from volve_dia.ocr import LABEL_MAP, Block
|
||||
|
||||
HTML = """<html><body>
|
||||
<p class="DDR-ReportHeader">Summary report</p>
|
||||
<p class="DDR-SubReportHeader"><b>Wellbore: </b>15/9-F-12</p>
|
||||
<p class="DDR-SubReportHeader"><b>Period: </b>2007-12-31 00:00 - 2008-01-01 00:00</p>
|
||||
<table id="wellboreInfoTable_1"><thead><tr><th/><th/><th/></tr></thead><tbody>
|
||||
<tr><td class="ColHead">Status:</td><td class="ColValue">normal</td></tr>
|
||||
<tr><td class="ColHead">Hole Dia ():</td><td class="ColValue"/></tr>
|
||||
<tr><td class="ColHead">Rig Name:</td><td class="ColValue">MÆRSK INSPIRER</td></tr>
|
||||
</tbody></table>
|
||||
<p class="TextHeader">Summary of activities (24 Hours)</p>
|
||||
<p class="TextData">Installed the BOP.<br/>Tested it. </p>
|
||||
<p class="TextHeader">Operations</p>
|
||||
<table><thead><tr><th class="ColHead">Start time</th><th class="ColHead">Remark</th></tr></thead><tbody>
|
||||
<tr><td class="ColValue">00:00</td><td class="ColValueWrapped">Moved the BOP.
|
||||
</td></tr><tr><td class="ColValue">03:30</td><td class="ColValueWrapped">Tested.</td></tr></tbody></table>
|
||||
<p class="TextHeader">Casing Liner Tubing</p>
|
||||
<table><tbody><tr><td class="ColHead">Start Time</td><td class="ColValue"></td></tr>
|
||||
<tr><td class="ColHead">Type</td><td class="ColValue">liner</td></tr></tbody></table>
|
||||
</body></html>"""
|
||||
|
||||
EXPECTED = Rendered(
|
||||
header={"wellbore": "15/9-F-12", "period": "2007-12-31 00:00 - 2008-01-01 00:00"},
|
||||
fields={"status": "normal", "hole dia ()": "", "rig name": "MÆRSK INSPIRER"},
|
||||
texts={"Summary of activities (24 Hours)": "Installed the BOP.\nTested it."},
|
||||
tables={"Operations": Table(["Start time", "Remark"], [["00:00", "Moved the BOP."], ["03:30", "Tested."]]),
|
||||
"Casing Liner Tubing": Table(None, [["Start Time", ""], ["Type", "liner"]])},
|
||||
)
|
||||
|
||||
|
||||
def block(page, label, html, text=None):
|
||||
return Block(page=page, label=LABEL_MAP.get(label.lower(), "paragraph"), raw_label=label, text=text or html,
|
||||
bbox=[], reading_order=0, html=html)
|
||||
|
||||
|
||||
OPS_HEAD = "<tr><th>Start time</th><th>Remark</th></tr>"
|
||||
BLOCKS = [
|
||||
block(1, "Page-Header", "<p>Summary report</p>",
|
||||
"Summary report\nWellbore: 15/9-F-12 Period: 2007-12-31 00:00 - 2008-01-01 00:00"),
|
||||
block(1, "Table", "<table><tr><td><b>Status:</b> normal</td></tr><tr><td>Hole Dia ():</td><td></td></tr>"
|
||||
"<tr><td>Rig Name:</td><td>MÆRSK INSPIRER</td></tr></table>"),
|
||||
block(1, "Section-Header", "Summary of activities (24 Hours)"),
|
||||
block(1, "Text", "<p>Installed the BOP.</p>", "Installed the BOP."),
|
||||
block(2, "Text", "<p>Tested it.</p>", "Tested it."), # the paragraph goes on
|
||||
block(2, "Text", "<p><b>Operations</b></p>", "Operations"), # bold throughout: a title
|
||||
block(2, "Table", f"<table>{OPS_HEAD}<tr><td>00:00</td><td>Moved the BOP.</td></tr></table>"),
|
||||
block(3, "Page-Footer", "<p>Page 2 of 3</p>", "Page 2 of 3"),
|
||||
block(3, "Table", f"<table>{OPS_HEAD}<tr><td>03:30</td><td>Tested.</td></tr></table>"), # header repeated
|
||||
block(3, "Section-Header", "Casing Liner Tubing"),
|
||||
block(3, "Table", "<table><tr><td><b>Start Time</b></td><td></td></tr></table>"),
|
||||
block(4, "Table", "<table><tr><th>Type</th><th>liner</th></tr></table>"), # a data row read as a header
|
||||
]
|
||||
|
||||
|
||||
def test_parse_html():
|
||||
assert parse_html(HTML) == EXPECTED
|
||||
|
||||
|
||||
def test_parse_ocr_undoes_the_page_layout():
|
||||
r = parse_ocr(BLOCKS)
|
||||
assert (r.header, r.fields, r.texts, r.tables) == (EXPECTED.header, EXPECTED.fields, EXPECTED.texts,
|
||||
EXPECTED.tables)
|
||||
assert r.notes == ["table continued: Operations",
|
||||
"table continued (header row kept as data): Casing Liner Tubing"]
|
||||
|
||||
|
||||
def test_parse_ocr_repairs_the_table_structure():
|
||||
period = "2007-12-31 00:00 - 2008-01-01 00:00"
|
||||
blocks = [
|
||||
block(1, "Table", "<table><tr><td><b>Summary report</b></td><td>Printed: 2008-10-04 00:00</td></tr>"
|
||||
f"<tr><td><b>Wellbore: 15/9-F-12</b></td><td><b>Period: {period}</b></td></tr>"
|
||||
"<tr><td><b>Status:</b></td><td>normal</td></tr></table>"), # header lines as rows
|
||||
block(1, "Section-Header", "Operations"),
|
||||
block(1, "Table", f"<table>{OPS_HEAD}<tr><td>00:00</td><td>Moved</td></tr>"
|
||||
"<tr><td></td><td>the BOP.</td></tr></table>"), # a two-line cell as rows
|
||||
block(2, "Table", "<table><tr><td>03:30</td><td>ok</td><td>Tested.</td></tr></table>"), # a column split
|
||||
]
|
||||
r = parse_ocr(blocks)
|
||||
assert r.header == {"wellbore": "15/9-F-12", "period": period, "other": "Printed: 2008-10-04 00:00"}
|
||||
assert r.fields == {"status": "normal"}
|
||||
assert r.tables == {"Operations": Table(["Start time", "Remark"], [["00:00", "Moved\nthe BOP."],
|
||||
["03:30", "ok", "Tested."]])}
|
||||
assert r.notes == ["table continued, columns differ: Operations", "rows merged into the row above: Operations (1)"]
|
||||
|
||||
|
||||
def test_round_trip():
|
||||
assert Rendered.from_dict(EXPECTED.to_dict()) == EXPECTED
|
||||
74
tests/test_runlog.py
Normal file
74
tests/test_runlog.py
Normal file
@@ -0,0 +1,74 @@
|
||||
"""volve_dia.runlog: the log captures child workers, meta/index record the correct status, nested runs, signal forwarding."""
|
||||
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from volve_dia.paths import REPO_ROOT
|
||||
|
||||
CHILD = ("import subprocess, sys; print('out-parent'); print('err-parent', file=sys.stderr); "
|
||||
"subprocess.run([sys.executable, '-c', 'print(\"out-child\")']); sys.exit(int(sys.argv[1]))")
|
||||
|
||||
|
||||
def launch(tmp: Path, *args: str, env: dict | None = None, **kw) -> subprocess.Popen:
|
||||
env = {k: v for k, v in os.environ.items() if not k.startswith("RUNLOG_")} | {"VOLVE_DIA_LOGS": str(tmp)} | (env or {})
|
||||
return subprocess.Popen([sys.executable, "-m", "volve_dia.runlog", *args], cwd=REPO_ROOT, env=env,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, **kw)
|
||||
|
||||
|
||||
def runs(tmp: Path) -> list[Path]:
|
||||
return sorted((tmp / "runs").iterdir())
|
||||
|
||||
|
||||
def test_log_meta_index(tmp_path):
|
||||
p = launch(tmp_path, "-n", "demo", "--", sys.executable, "-c", CHILD, "0")
|
||||
out, _ = p.communicate(timeout=60)
|
||||
assert p.returncode == 0 and "out-child" in out # still echoed to the terminal
|
||||
(d,) = runs(tmp_path)
|
||||
log = (d / "log.txt").read_text()
|
||||
assert all(s in log for s in ("out-parent", "err-parent", "out-child")) and "[0:00:00] out-parent" in log
|
||||
meta = json.loads((d / "meta.json").read_text())
|
||||
assert meta["status"] == "ok" and meta["exit_code"] == 0 and meta["wall_s"] >= 0 and meta["git"]["code_sha256"]
|
||||
(row,) = list(csv.DictReader(open(tmp_path / "index.csv")))
|
||||
assert row["name"] == "demo" and row["status"] == "ok" and row["parent"] == ""
|
||||
|
||||
|
||||
def test_failure_keeps_exit_code(tmp_path):
|
||||
p = launch(tmp_path, sys.executable, "-c", CHILD, "3")
|
||||
p.communicate(timeout=60)
|
||||
assert p.returncode == 3
|
||||
meta = json.loads((runs(tmp_path)[0] / "meta.json").read_text())
|
||||
assert meta["status"] == "failed" and meta["exit_code"] == 3
|
||||
|
||||
|
||||
def test_nested_steps_go_into_parent(tmp_path):
|
||||
inner = [sys.executable, '-m', 'volve_dia.runlog', '-n', 'step', '--', sys.executable, '-c', 'print(1)']
|
||||
code = f'import subprocess; cmd={inner!r}; subprocess.run(cmd, check=True); subprocess.run(cmd, check=True)'
|
||||
p = launch(tmp_path, "-n", "parent", "--", sys.executable, '-c', code)
|
||||
p.communicate(timeout=60)
|
||||
assert p.returncode == 0
|
||||
(d,) = runs(tmp_path)
|
||||
assert sorted(x.name for x in d.iterdir() if x.is_dir()) == ["01_step", "02_step"]
|
||||
rows = list(csv.DictReader(open(tmp_path / "index.csv")))
|
||||
assert [r["parent"] for r in rows] == [d.name, d.name, ""]
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name == 'nt', reason='Windows TerminateProcess bypasses Python signal handlers; POSIX SIGTERM semantics do not apply')
|
||||
def test_sigterm_marks_interrupted(tmp_path):
|
||||
p = launch(tmp_path, sys.executable, "-c", "import time; print('started', flush=True); time.sleep(60)")
|
||||
t0 = time.time()
|
||||
while not (tmp_path / "runs").exists() or not any((d / "log.txt").exists() and "started" in (d / "log.txt").read_text()
|
||||
for d in runs(tmp_path)):
|
||||
assert time.time() - t0 < 30
|
||||
time.sleep(0.1)
|
||||
p.send_signal(signal.SIGTERM)
|
||||
p.communicate(timeout=30)
|
||||
meta = json.loads((runs(tmp_path)[0] / "meta.json").read_text())
|
||||
assert meta["status"] == "interrupted" and meta["signals"] == ["SIGTERM"] and p.returncode == 128 + signal.SIGTERM
|
||||
Reference in New Issue
Block a user