diff --git a/README.en.md b/README.en.md index 1e49b87..3eb8e66 100644 --- a/README.en.md +++ b/README.en.md @@ -2,7 +2,7 @@ [简体中文](README.md) | **English** -This overview and the workspace-start, continuing-research and bounded FLAC3D script-review guides have Chinese and English versions. Other guides remain mostly in English; some examples are in Chinese. +This overview and the workspace-start, continuing-research, bounded FLAC3D script-review and existing-CSV result-comparison guides have Chinese and English versions. Other guides remain mostly in English; some examples are in Chinese. A filesystem-native workspace and optional research kernel for Agent-assisted mining research. Start with a small Markdown workspace, then enable durable @@ -20,6 +20,7 @@ offline examples use the Python standard library. - [Compare literature for one question](docs/LITERATURE_COMPARISON.md): compare selected papers and optional documentation with page citations and explicit missing information. - [FLAC3D review workflow](docs/FLAC3D_FIRST_TASK.md): identify inputs and version, check applicable official sources, and save findings for continuation. - [Bounded FLAC3D script review](docs/FLAC3D_SCRIPT_REVIEW.md): capture selected lines and a file hash, bind read official passages, and save cited findings; the first command family is `zone cmodel assign`. +- [Compare existing CSV results](docs/RESULT_COMPARISON.md): capture declared units and conditions, compare explicitly selected points, link saved research context and recover a derived report. Give your Agent the question and material locations, for example: "比较这两篇文献已读部分的试验条件和方法,结合对应版本官方说明,记录依据、缺口和下一步建议。" @@ -127,6 +128,7 @@ an independent review. ## Current capabilities +- Read-only result CSV captures and bounded two-case comparisons preserve raw values, physical line locators, declared quantity/units/conditions and quality diagnostics. Compute signed deltas at selected point IDs, associate historical script/documentation context and recover reports; see the [result comparison guide](docs/RESULT_COMPARISON.md). - Recoverable FLAC3D excerpt reviews with selected lines, file hashes, version-matched official passages and authored findings; optionally compare a selected current file read-only. This does not execute scripts or certify model correctness; see the [script review guide](docs/FLAC3D_SCRIPT_REVIEW.md). - Continued source review under one ResearchQuestion, retaining prior task and judgment revisions, with read-only progress and regenerable Markdown reports; diff --git a/README.md b/README.md index 70f5974..1444851 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ **简体中文** | [English](README.en.md) -本介绍页以及“建立轻量工作区”“持续研究”和“FLAC3D 局部脚本审阅”指南均可切换中英文。其余指南目前主要为英文,部分示例使用中文。 +本介绍页以及“建立轻量工作区”“持续研究”“FLAC3D 局部脚本审阅”和“已有CSV结果比较”指南均可切换中英文。其余指南目前主要为英文,部分示例使用中文。 一个基于本地文件的轻量工作区与可选研究内核,用于协助 Agent 开展矿业研究。 先用少量 Markdown 文件组织项目;需要时,再启用持久研究记录和领域工作流。 @@ -19,6 +19,7 @@ - [围绕问题比较文献](docs/LITERATURE_COMPARISON.md):按选定维度比较论文与可选软件说明,保留页码引用和缺失信息。 - [FLAC3D 核查工作流](docs/FLAC3D_FIRST_TASK.md):定位输入、确认软件版本、查阅适用的官方说明,并保存可接续的核查结果。 - [FLAC3D 局部脚本审阅](docs/FLAC3D_SCRIPT_REVIEW.zh-CN.md):捕获选定行和文件哈希,关联已读官方段落,保存带行号与引用的发现;首批关注 `zone cmodel assign`。 +- [已有CSV结果比较](docs/RESULT_COMPARISON.zh-CN.md):保存已导出结果的来源、单位与工况,按选定测点比较两组数值,关联已有研究并恢复报告。 可以直接告诉 Agent 你的问题和材料位置,例如: @@ -105,6 +106,7 @@ Agent 通过 CLI 或公开 Python API 调用内核;模型、宿主应用与用 ## 当前能力 +- 已有CSV结果的只读捕获与两组有限比较:保留原值、物理行号、单位/指标/工况声明与质量诊断,按选定测点计算有符号差值,关联历史脚本/文档背景并生成可恢复报告;见[结果比较指南](docs/RESULT_COMPARISON.zh-CN.md)。 - 可持久恢复的 FLAC3D 局部脚本审阅:记录选定行、文件哈希、匹配版本的官方段落与人工撰写的发现,按需只读比较当前文件是否变化;不执行脚本或认证模型正确性,见[审阅指南](docs/FLAC3D_SCRIPT_REVIEW.zh-CN.md)。 - 在同一个 ResearchQuestion 下接续资料研究,保留历史任务和判断修订,提供只读进度恢复及可重建的 Markdown 报告;见[持续研究指南](docs/CONTINUING_RESEARCH.zh-CN.md)。 - 简短恢复视图区分待分析任务与继承的历史判断,可展开准确历史版本,并为兼容的资料研究任务提供进展和报告入口。 diff --git a/docs/RESULT_COMPARISON.md b/docs/RESULT_COMPARISON.md new file mode 100644 index 0000000..84c3474 --- /dev/null +++ b/docs/RESULT_COMPARISON.md @@ -0,0 +1,76 @@ +# Read and compare existing CSV results + +[简体中文](RESULT_COMPARISON.zh-CN.md) | **English** · [Home](../README.en.md) + +Capture an existing result export, retain its source hash and declared metadata, compare explicitly selected point IDs, and recover the same comparison in another session. Enable research records only when needed. Original files remain in place. + +The user chooses the question, selected points and next work. The Agent reads existing project evidence and records missing information without inventing units or asking the user to repeat settled decisions. + +## Format and interpretation + +The first format is one case and quantity per comma-separated CSV, with exactly two headers, `point_id,value`, in either column order: + +```csv +point_id,value +P1,-12.5 +P2,-8.0 +P3, +``` + +Limits: 2 MiB per file, 2,000 data records, and 100 explicitly selected points per comparison. Strict decoding defaults to `utf-8-sig`, including UTF-8 BOM support; select another known encoding explicitly. Invalid CSV structure or headers are rejected. Missing, invalid, nonfinite and duplicate-point values retain diagnostics; they are not filled with zero or silently deduplicated. Other export layouts need a separately documented conversion copy, retaining the original source. + +Record quantity, units, column meanings, point definitions and case conditions alongside the capture. These are caller declarations, not proof of the software, export process or solver state. Numeric deltas are **candidate − baseline**, aligned by selected `point_id`, independently of row order. Unknown or mismatched quantity/unit labels and unavailable, missing or ambiguous values prevent the affected deltas. No implicit unit conversion, improvement percentage or engineering interpretation is supplied. Differences and uncertainty in conditions or point definitions remain gaps. + +## Agent procedure + +Run from the repository. Keep inputs and generated records in the selected project. Skip enabling if already enabled: + +```powershell +$projectRoot = 'D:\replace-with-user-chosen\existing-study' +python -B -X utf8 mining_kernel.py enable-research --project-root $projectRoot --project-id study-01 +``` + +Prepare a JSON metadata file for each export: + +```json +{ + "case_id": "baseline", + "quantity": "displacement_y", + "unit": "mm", + "column_meanings": {"point_id": "Selected monitoring-point identifier", "value": "Displacement with the declared sign convention"}, + "point_basis": "Shared point definitions established in the project record", + "conditions": {"stage": "User-confirmed construction stage", "coordinate_frame": "User-confirmed coordinates and sign convention"}, + "origin": "provided_export" +} +``` + +These are examples, not project facts. Unknown fields may be `null` or omitted; `case_id` is required. Authored teaching data require `origin: synthetic` and `--task-context synthetic` and cannot support production comparison. + +```powershell +python -B -X utf8 mining_kernel.py result-import --project-root $projectRoot --task-id baseline-read-01 --question "Record the existing baseline displacement export" --csv exports/baseline.csv --metadata-file 'D:\replace-with-user-chosen\baseline-metadata.json' +python -B -X utf8 mining_kernel.py result-import --project-root $projectRoot --task-id candidate-read-01 --question "Record the existing candidate displacement export" --csv exports/candidate.csv --metadata-file 'D:\replace-with-user-chosen\candidate-metadata.json' +``` + +The receipt identifies the comparable capture Asset. Paths may be project-relative or explicitly selected external absolute paths; external Host paths are not automatically published in persisted records. Capture preserves the whole-file hash, raw selected values, physical line locators and diagnostics, allowing historical recovery without reopening the source. + +```powershell +$baselineAsset = '' +$candidateAsset = '' +python -B -X utf8 mining_kernel.py result-compare --project-root $projectRoot --task-id displacement-compare-01 --question "What are the numeric differences at the selected points?" --baseline-asset-ref $baselineAsset --candidate-asset-ref $candidateAsset --point P1 --point P2 --point P3 --comparability-note "Compare only selected labels; recorded conditions and gaps still apply" --related-task '' --next-action "The user chooses whether to investigate conditions or more points" +python -B -X utf8 mining_kernel.py result-report --project-root $projectRoot --task-id displacement-compare-01 --output reports/displacement-comparison.md +``` + +Omit or repeat `--related-task` to associate selected script reviews, documentation readings or other research tasks. The report preserves their exact historical revisions, task contexts and documentation trust classes; production comparison rejects synthetic related tasks. Association does not prove that the CSV was generated by that script. Solver provenance requires separate evidence. This workflow starts no solver and creates no Run or engineering Verification. + +## Recover and inspect changes + +```powershell +python -B -X utf8 mining_kernel.py result-progress --project-root $projectRoot --task-id displacement-compare-01 +python -B -X utf8 mining_kernel.py result-report --project-root $projectRoot --task-id displacement-compare-01 +``` + +Default recovery reads saved captures, judgments, gaps and next actions without reopening CSV, scripts or manuals. To compare current files explicitly, supply a JSON object mapping capture Asset IDs to current paths through `result-progress --source-paths-file`. Unchecked, unchanged, changed, missing and read-error states remain distinct. + +Identical task requests replay saved records. New source versions, metadata or selected scope require new task IDs and preserve prior comparisons. Successful processing can still produce an `INSUFFICIENT` judgment. Write the task ID, agreed question, report path and pending decisions into `START.md`. Reports are derived views; the writer protects entries, registered materials and unrelated existing files. + +The [offline synthetic example](../examples/result_comparison/README.md) demonstrates reordered point rows, missing data, linked script/documentation context and fresh-process recovery. Its authored tables are not real simulation results. diff --git a/docs/RESULT_COMPARISON.zh-CN.md b/docs/RESULT_COMPARISON.zh-CN.md new file mode 100644 index 0000000..7f1411f --- /dev/null +++ b/docs/RESULT_COMPARISON.zh-CN.md @@ -0,0 +1,82 @@ +# 已有CSV结果的只读接入与比较 + +**简体中文** | [English](RESULT_COMPARISON.md) · [首页](../README.md) + +这个入口读取已有导出的结果表,保存来源版本与阅读范围,按选定测点比较两组数值,并让后续会话恢复同一份比较。它复用可选研究记录,原文件留在原位。 + +可以直接告诉 Agent: + +> 比较这两份位移导出表中的 P1、P2 和 P3,记录单位、工况、差值与缺失信息,并关联已有脚本审阅。保存报告,下次继续。 + +用户决定问题、选取范围和后续行动。Agent 从已有材料与用户已确认的信息补齐说明;未知信息保留为缺口,不要求用户重复填表,也不能自行猜单位。 + +## 当前格式与解释范围 + +首版是一份文件对应一个工况、一个指标的逗号分隔CSV,恰有 `point_id,value` 两列,列顺序可交换。例如: + +```csv +point_id,value +P1,-12.5 +P2,-8.0 +P3, +``` + +每个文件最多2 MiB、2,000条数据记录;每次明确比较最多100个测点。默认严格按 `utf-8-sig` 读取,接受UTF-8 BOM;确知其他编码时显式指定。表头、列数或CSV结构不符合时拒绝导入;空值、非法数值、非有限值和重复测点保留诊断,不自动填零或去重。若原软件导出格式不同,需要另行保留有来源说明的转换副本,本入口不会改写原表。 + +单位、指标、列含义、测点依据与工况说明随导入记录保存。它们是调用方的声明,不能证明软件版本、导出过程或模型状态已经核实。 + +差值固定为 **对照工况值 − 基准工况值**,按选定 `point_id` 对齐,与行排序无关。指标或单位未知、标签不一致,以及测点缺失、重复或数值不可用时,相应差值不能成立。首版不自动换算单位、不计算改善率,也不从正负差值推断支护效果。工况或测点依据的差异与未知仍须出现在缺口中。 + +## Agent 操作步骤 + +从仓库运行命令,把材料和生成记录留在用户自己的项目中。已有研究记录时跳过启用步骤: + +```powershell +$projectRoot = 'D:\replace-with-user-chosen\existing-study' +python -B -X utf8 mining_kernel.py enable-research --project-root $projectRoot --project-id study-01 +``` + +为每份表准备小型JSON说明文件,例如基准工况: + +```json +{ + "case_id": "baseline", + "quantity": "displacement_y", + "unit": "mm", + "column_meanings": {"point_id": "用户选定的监测点标识", "value": "按所述方向记录的位移"}, + "point_basis": "两组数据使用相同的监测点定义;依据见项目记录", + "conditions": {"stage": "用户已确认的施工阶段", "coordinate_frame": "用户已确认的坐标与正负约定"}, + "origin": "provided_export" +} +``` + +这里只展示格式,不能把示例中的声明照搬为项目事实。未知字段用 `null` 或省略;`case_id` 必须明确。匿名编写的教学数据用 `origin: synthetic` 和 `--task-context synthetic`,不能混入生产比较。 + +```powershell +python -B -X utf8 mining_kernel.py result-import --project-root $projectRoot --task-id baseline-read-01 --question "记录基准工况已导出的位移表" --csv exports/baseline.csv --metadata-file 'D:\replace-with-user-chosen\baseline-metadata.json' +python -B -X utf8 mining_kernel.py result-import --project-root $projectRoot --task-id candidate-read-01 --question "记录对照工况已导出的位移表" --csv exports/candidate.csv --metadata-file 'D:\replace-with-user-chosen\candidate-metadata.json' +``` + +回执返回可比较的捕获Asset ID。文件可以使用项目相对路径或用户明确提供的外部绝对路径;持久记录不自动暴露外部宿主路径。保存完整文件哈希、所选两列的原值、物理行号和诊断,恢复时不依赖原表仍然存在。 + +```powershell +$baselineAsset = '<基准导入回执的捕获 Asset ID>' +$candidateAsset = '<对照导入回执的捕获 Asset ID>' +python -B -X utf8 mining_kernel.py result-compare --project-root $projectRoot --task-id displacement-compare-01 --question "指定测点的两组位移数值相差多少?" --baseline-asset-ref $baselineAsset --candidate-asset-ref $candidateAsset --point P1 --point P2 --point P3 --comparability-note "仅比较用户指定标签;物理可比条件仍以记录和缺口为准" --related-task '<已有脚本审阅任务 ID>' --next-action "由用户决定是否补查工况或增加其他测点" +python -B -X utf8 mining_kernel.py result-report --project-root $projectRoot --task-id displacement-compare-01 --output reports/displacement-comparison.md +``` + +`--related-task` 可省略或重复使用,关联已有脚本审阅、文档阅读或研究任务。报告保留关联时的准确版本、任务上下文与文档来源类别;生产比较拒绝关联合成任务。**背景关联不能证明CSV由该脚本计算得到**。已有求解器运行的真实性与结果来源需要另有证据。本流程不启动求解器,不创建Run或工程Verification。 + +## 恢复与来源变化 + +```powershell +python -B -X utf8 mining_kernel.py result-progress --project-root $projectRoot --task-id displacement-compare-01 +python -B -X utf8 mining_kernel.py result-report --project-root $projectRoot --task-id displacement-compare-01 +``` + +默认恢复历史捕获、判断、缺口和后续建议,不重读CSV、脚本或文档。若需比较当前文件,明确提供一个JSON映射文件(捕获Asset ID → 当前文件路径),再给 `result-progress` 传 `--source-paths-file`。未检查、未变、已变、缺失或读取失败分别报告,不能以恢复成功代替文件未变。 + +相同任务和参数只重放已存记录;新的文件版本、说明或比较范围使用新的任务ID,保留旧结果。命令成功表示处理或记录完成,判断仍可能为 `INSUFFICIENT`。在项目 `START.md` 简短写回问题、任务ID、报告位置和待决定事项,避免重复保存整份结果。报告是可重建的派生文件,写入器保护项目入口、登记材料和其他已有手写文件。 + +没有现成结果时,可以运行[离线匿名合成示例](../examples/result_comparison/README.md),查看乱序测点、缺失数据、脚本/文档背景和跨会话恢复如何保存。它不能作为真实模拟结果。 diff --git a/examples/result_comparison/README.md b/examples/result_comparison/README.md new file mode 100644 index 0000000..b09729b --- /dev/null +++ b/examples/result_comparison/README.md @@ -0,0 +1,28 @@ +# 离线匿名CSV结果比较示例 + +[中文指南](../../docs/RESULT_COMPARISON.zh-CN.md) · [English guide](../../docs/RESULT_COMPARISON.md) + +This standard-library example uses authored CSV values and synthetic script/documentation context. It aligns selected point IDs, retains missing data and recovers a report in a fresh process. No data were produced by a solver, and the associated script does not establish CSV provenance. + +示例先复用已有合成脚本审阅,再创建两份匿名编写的结果表。对照表的测点顺序不同,并故意缺少P3;只选P1、P2、P3,不能把P4自动纳入比较,也不能把缺失值填零。 + +| 测点 | 基准值 | 对照值 | 对照值 − 基准值 | +|---|---:|---:|---:| +| P1 | -12.5 | -10.0 | 2.5 | +| P2 | -8.0 | -7.0 | 1.0 | +| P3 | 空值 | 缺少该测点 | 不足,不计算 | + +单位标签为编写的 `mm`,工况也为合成说明。差值只演示算术,不能据此推断支护改善或工程适用性。 + +从仓库根目录运行,选择仓库外的新目录或空目录: + +```powershell +$exampleRoot = 'D:\replace-with-user-chosen\csv-result-demo' +python -S -B -X utf8 examples/result_comparison/demo.py $exampleRoot +python -S -B -X utf8 mining_kernel.py result-progress --project-root $exampleRoot --task-id synthetic-result-comparison +python -S -B -X utf8 mining_kernel.py result-report --project-root $exampleRoot --task-id synthetic-result-comparison +``` + +生成的项目入口记录任务ID与报告链接;报告位于 `reports/result-comparison.md`,关联此前合成脚本与文档的历史版本。恢复命令从记录读取,默认不重新打开源CSV。 + +演示生成器拒绝覆盖非空目录。已有演示用恢复或报告命令继续查看;真实项目按指南读取已导出的CSV,不把这些教学数据换成生产证据。 diff --git a/examples/result_comparison/demo.py b/examples/result_comparison/demo.py new file mode 100644 index 0000000..308fb8e --- /dev/null +++ b/examples/result_comparison/demo.py @@ -0,0 +1,86 @@ +"""Offline teaching data: CSV results, script context and recoverable comparison.""" +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +import subprocess +import sys + +REPO = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(REPO)) + +from examples.script_review.demo import run_demo as create_script_context +from mining_research_kernel.result_comparison import import_result_csv, compare_results + +TASK = "synthetic-result-comparison" +BASELINE = "point_id,value\nP1,-12.5\nP2,-8.0\nP3,\n" +CANDIDATE = "point_id,value\nP2,-7.0\nP1,-10.0\nP4,-6.0\n" + + +def metadata(case_id: str) -> dict: + return {"case_id": case_id, "quantity": "displacement_y", "unit": "mm", + "column_meanings": {"point_id": "Invented shared point label", "value": "Invented signed displacement"}, + "point_basis": "Authored teaching points; no actual monitoring location is represented", + "conditions": {"stage": "synthetic post-excavation", "coordinate_frame": "synthetic y-positive convention", + "scheme": case_id}, "origin": "synthetic"} + + +def cli(root: Path, *args) -> str: + result = subprocess.run([sys.executable, "-S", "-B", "-X", "utf8", str(REPO / "mining_kernel.py"), + *args, "--project-root", str(root)], capture_output=True, text=True, + encoding="utf-8", check=True) + return result.stdout + + +def run_demo(value: str) -> dict: + # Reuse the bounded script example's new/empty, external-directory guard. + context = create_script_context(value) + root = Path(context["project"]) + exports = root / "exports" + exports.mkdir() + paths = [] + for name, text in (("baseline", BASELINE), ("candidate", CANDIDATE)): + source = exports / f"{name}.csv" + source.write_text(text, encoding="utf-8") + paths.append(source) + (exports / f"{name}-metadata.json").write_text( + json.dumps(metadata(name), ensure_ascii=False, indent=2), encoding="utf-8") + protected = [*paths, root / "work/example.dat", root / "teaching-docs/flac3d/script-review-teaching.html"] + before = {str(path): hashlib.sha256(path.read_bytes()).hexdigest() for path in protected} + captures = [] + for name in ("baseline", "candidate"): + result = import_result_csv(root, task_id=f"synthetic-result-{name}", + question=f"Read authored {name} point values", csv_path=f"exports/{name}.csv", + metadata=metadata(name), task_context="synthetic") + captures.append(result["asset_refs"][0]) + compare_results(root, task_id=TASK, question="所选教学测点的两组数值相差多少?", + baseline_asset_ref=captures[0], candidate_asset_ref=captures[1], point_ids=["P1", "P2", "P3"], + comparability_note="仅按编写的点标签比较;这些CSV不是脚本或求解器的输出。", + related_task_ids=["synthetic-script-review-01", "synthetic-assignment-reading"], + next_action="由用户决定是否另选真实导出表,补充测点与工况依据。", task_context="synthetic") + progress = json.loads(cli(root, "result-progress", "--task-id", TASK)) + if progress.get("task_packet", {}).get("task_id") != TASK: + raise RuntimeError("fresh-process recovery returned a different task") + cli(root, "result-report", "--task-id", TASK, "--output", "reports/result-comparison.md") + if before != {str(path): hashlib.sha256(path.read_bytes()).hexdigest() for path in protected}: + raise RuntimeError("an input changed during the example") + with (root / "START.md").open("a", encoding="utf-8") as stream: + stream.write(f"\n## 合成结果比较\n\n任务:`{TASK}`;仅选P1、P2、P3。\n\n" + "报告:[数值比较](reports/result-comparison.md)。\n\n" + "P1与P2可作教学算术对照,P3保持不足;背景关联不能证明CSV由脚本产生。\n\n" + "接续:使用 result-progress 恢复该任务。用户决定后续范围。\n") + return {"task_id": TASK, "project": str(root), "report": "reports/result-comparison.md", + "capture_asset_refs": captures, "synthetic": True, "source_unchanged": True, + "fresh_process_recovery": True, "run_created": False, "verification_created": False} + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("project_root", help="new or empty directory outside the repository") + args = parser.parse_args() + try: + print(json.dumps(run_demo(args.project_root), ensure_ascii=False, indent=2)) + except (OSError, ValueError, subprocess.CalledProcessError) as exc: + parser.exit(2, f"{exc}\n") diff --git a/mining_kernel.py b/mining_kernel.py index 69cf891..70de3ea 100644 --- a/mining_kernel.py +++ b/mining_kernel.py @@ -227,6 +227,33 @@ def main(argv=None): sr.add_argument("--project-root", required=True) sr.add_argument("--task-id", required=True) sr.add_argument("--output", help="optional separate in-project Markdown output") + ri = sub.add_parser("result-import", help="capture a bounded point_id,value CSV with declared result metadata") + ri.add_argument("--project-root", required=True) + ri.add_argument("--task-id", required=True) + ri.add_argument("--question", required=True) + ri.add_argument("--csv", dest="csv_path", required=True) + ri.add_argument("--metadata-file", required=True) + ri.add_argument("--encoding", default="utf-8-sig") + ri.add_argument("--task-context", choices=("production", "synthetic"), default="production") + rcsv = sub.add_parser("result-compare", help="compare selected point IDs from two saved result captures") + rcsv.add_argument("--project-root", required=True) + rcsv.add_argument("--task-id", required=True) + rcsv.add_argument("--question", required=True) + rcsv.add_argument("--baseline-asset-ref", required=True) + rcsv.add_argument("--candidate-asset-ref", required=True) + rcsv.add_argument("--point", dest="point_ids", action="append", required=True) + rcsv.add_argument("--comparability-note", default="") + rcsv.add_argument("--related-task", dest="related_task_ids", action="append") + rcsv.add_argument("--next-action", default="User chooses any further analysis.") + rcsv.add_argument("--task-context", choices=("production", "synthetic"), default="production") + rp = sub.add_parser("result-progress", help="recover historical result data; optionally compare explicitly selected current files") + rp.add_argument("--project-root", required=True) + rp.add_argument("--task-id", required=True) + rp.add_argument("--source-paths-file", help="optional JSON object mapping selected capture Asset IDs to current file paths") + rr = sub.add_parser("result-report", help="render a derived result comparison report from persisted records") + rr.add_argument("--project-root", required=True) + rr.add_argument("--task-id", required=True) + rr.add_argument("--output", help="optional separate in-project Markdown output") lc = sub.add_parser("literature-start", help="prepare a question-oriented comparison of selected distinct papers") lc.add_argument("--project-root", required=True) lc.add_argument("--task-id", required=True) @@ -412,6 +439,34 @@ def main(argv=None): out = {"type": "ScriptReviewReportReceipt", "task_id": args.task_id, "output": target, "sha256": digest, "authority": "derived", "source_queries_performed": False, "run_created": False, "verification_created": False} + elif args.command == "result-import": + from mining_research_kernel.result_comparison import import_result_csv + metadata = json.loads(Path(args.metadata_file).read_text(encoding="utf-8-sig")) + out = import_result_csv(args.project_root, task_id=args.task_id, question=args.question, + csv_path=args.csv_path, metadata=metadata, encoding=args.encoding, + task_context=args.task_context) + elif args.command == "result-compare": + from mining_research_kernel.result_comparison import compare_results + out = compare_results(args.project_root, task_id=args.task_id, question=args.question, + baseline_asset_ref=args.baseline_asset_ref, candidate_asset_ref=args.candidate_asset_ref, + point_ids=args.point_ids, comparability_note=args.comparability_note, + related_task_ids=args.related_task_ids, next_action=args.next_action, + task_context=args.task_context) + elif args.command == "result-progress": + from mining_research_kernel.result_comparison import result_comparison_progress + source_paths = (json.loads(Path(args.source_paths_file).read_text(encoding="utf-8-sig")) + if args.source_paths_file else None) + out = result_comparison_progress(args.project_root, task_id=args.task_id, source_paths=source_paths) + elif args.command == "result-report": + from mining_research_kernel.result_comparison import render_result_comparison_report + markdown = render_result_comparison_report(args.project_root, task_id=args.task_id) + if args.output is None: + print(markdown, end="" if markdown.endswith("\n") else "\n") + return 0 + target, digest = _write_research_report(args.project_root, args.task_id, args.output, markdown) + out = {"type": "ResultComparisonReportReceipt", "task_id": args.task_id, "output": target, + "sha256": digest, "authority": "derived", "source_queries_performed": False, + "run_created": False, "verification_created": False} elif args.command in {"research-begin", "research-continue"}: from mining_research_kernel.research_continuation import begin_research, continue_research if args.command == "research-begin": diff --git a/mining_research_kernel/project_context.py b/mining_research_kernel/project_context.py index dd98ce5..c3859e7 100644 --- a/mining_research_kernel/project_context.py +++ b/mining_research_kernel/project_context.py @@ -190,6 +190,9 @@ def list_transactions(self): elif packet.get("input", {}).get("review_mode") == "flac3d_script_review": tasks[-1]["script_review_progress_argv"] = _argv(root, "script-review-progress", "--task-id", rid) tasks[-1]["script_review_report_argv"] = _argv(root, "script-review-report", "--task-id", rid) + elif packet.get("input", {}).get("review_mode") in {"result_csv_import", "result_csv_comparison"}: + tasks[-1]["result_progress_argv"] = _argv(root, "result-progress", "--task-id", rid) + tasks[-1]["result_report_argv"] = _argv(root, "result-report", "--task-id", rid) elif record["type"] == "Asset": locator = record.get("locator", {}) loc = ({"recorded_locator": locator, "status": "caller_label_or_unresolved; supply location explicitly"}) diff --git a/mining_research_kernel/result_comparison.py b/mining_research_kernel/result_comparison.py new file mode 100644 index 0000000..62a2eea --- /dev/null +++ b/mining_research_kernel/result_comparison.py @@ -0,0 +1,653 @@ +"""Persistent observations and bounded arithmetic comparisons of exported CSVs.""" +from __future__ import annotations + +import copy +import hashlib +import json +import os +from pathlib import Path +from typing import Any, Mapping + +from mining_research_kernel.records import ResearchStore +from mining_research_kernel.result_csv import difference, read_result_csv +from mining_research_kernel.r2_workflow import ( + _edge_id, _id, _record, _relationship, _sha256_bytes, _task_ids, +) +from mining_research_kernel.on_demand import _decision_bound_to_task_state +from research_project import load_config +from mining_research_kernel.task_engine import TaskEngine +from workflows.research import build_research_workflow_pack + +_PRODUCER = {"role": "host", "model": "result_comparison"} +_DEFAULT_ACTION = "User chooses any further analysis." + + +def _canonical(value: Any) -> bytes: + return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() + + +def _base(task_id: str, task_packet: dict[str, Any], replayed: bool, **fields: Any) -> dict[str, Any]: + return {"task_packet": copy.deepcopy(task_packet), "replayed": replayed, + "run_created": False, "verification_created": False, **fields} + + +def _state(store: ResearchStore, task_id: str) -> dict[str, Any] | None: + return store.latest_record(task_id, "TaskState") + + +def _operation(state: Mapping[str, Any], mode: str) -> dict[str, Any] | None: + results = state.get("operation_results", {}) + value = results.get(mode) if isinstance(results, Mapping) else None + return dict(value) if isinstance(value, Mapping) else None + + +def _metadata(value: Any) -> tuple[dict[str, Any], list[str]]: + if not isinstance(value, dict): + raise ValueError("metadata must be an object") + allowed = {"case_id", "quantity", "unit", "column_meanings", "point_basis", "conditions", "origin"} + unknown = set(value) - allowed + if unknown: + raise ValueError("unknown metadata keys: " + ", ".join(sorted(str(key) for key in unknown))) + case_id = value.get("case_id") + if not isinstance(case_id, str) or not case_id.strip() or len(case_id) > 200: + raise ValueError("metadata.case_id must be a non-empty bounded string") + normalized: dict[str, Any] = {"case_id": case_id.strip()} + gaps: list[str] = [] + for key in ("quantity", "unit", "point_basis"): + item = value.get(key) + if item is not None and (not isinstance(item, str) or len(item) > 200): + raise ValueError(f"metadata.{key} must be a bounded string or null") + normalized[key] = item.strip() if isinstance(item, str) and item.strip() else None + if key in {"quantity", "unit"} and normalized[key] is None: + gaps.append(f"metadata_{key}_unknown") + meanings = value.get("column_meanings", {}) + if meanings is None: + meanings = {} + if not isinstance(meanings, dict) or set(meanings) - {"point_id", "value"}: + raise ValueError("metadata.column_meanings must contain only point_id/value string-or-null entries") + normalized["column_meanings"] = {} + for key in ("point_id", "value"): + item = meanings.get(key) + if item is not None and (not isinstance(item, str) or len(item) > 200): + raise ValueError(f"metadata.column_meanings.{key} must be a bounded string or null") + normalized["column_meanings"][key] = item.strip() if isinstance(item, str) and item.strip() else None + if normalized["column_meanings"][key] is None: + gaps.append(f"column_meaning_{key}_unknown") + conditions = value.get("conditions", {}) + if conditions is None: + conditions = {} + if not isinstance(conditions, dict) or len(conditions) > 50: + raise ValueError("metadata.conditions must be an object with at most 50 entries") + normalized_conditions = {} + for key, item in conditions.items(): + if not isinstance(key, str) or not key.strip() or len(key) > 100: + raise ValueError("condition keys must be bounded non-empty strings") + if item is not None and (not isinstance(item, str) or len(item) > 500): + raise ValueError("condition values must be bounded strings or null") + clean_key = key.strip() + if clean_key in normalized_conditions: + raise ValueError("condition keys collide after whitespace normalization") + normalized_conditions[clean_key] = item.strip() if isinstance(item, str) and item.strip() else None + normalized["conditions"] = normalized_conditions + if not normalized["point_basis"]: + gaps.append("point_basis_unknown") + if not normalized_conditions: + gaps.append("conditions_unknown") + for key, item in normalized_conditions.items(): + if item is None: + gaps.append(f"condition_value_unknown:{key}") + origin = value.get("origin", "provided_export") + if not isinstance(origin, str) or origin not in {"provided_export", "synthetic"}: + raise ValueError("metadata.origin must be provided_export or synthetic") + normalized["origin"] = origin + return normalized, gaps + + +def _locator(root: Path, source: Path) -> tuple[dict[str, Any], str]: + resolved = source.resolve() + try: + relative = resolved.relative_to(root.resolve()).as_posix() + return {"path": relative, "path_kind": "project_relative"}, relative + except ValueError: + label = source.name[:180] or "external.csv" + path_digest = hashlib.sha256(os.path.normcase(str(resolved)).encode()).hexdigest() + return {"path": f"caller:{label}", "path_kind": "caller_label", "identity_sha256": path_digest}, label + + +def _resolve_source(root: Path, source_path: str | os.PathLike[str]) -> Path: + raw = Path(source_path).expanduser() + if raw.is_absolute(): + return raw.resolve() + if ".." in raw.parts: + raise ValueError("relative csv_path must not contain '..'") + resolved = (root / raw).resolve() + try: + resolved.relative_to(root.resolve()) + except ValueError as exc: + raise ValueError("relative csv_path resolves outside project_root") from exc + return resolved + + +def _commit_review_task(root: Path, *, task_id: str, question: str, task_context: str, + mode: str, input_data: dict[str, Any], assets: list[dict[str, Any]], + evidences: list[dict[str, Any]], assessment: dict[str, Any], + operation_result: dict[str, Any], new_records: list[dict[str, Any]] | None = None, + expected_revisions: dict[str, int] | None = None) -> dict[str, Any]: + """Build and commit one fully linked evidence-review snapshot atomically.""" + store = ResearchStore(root) + ids = _task_ids(task_id) + source_refs = list(dict.fromkeys([f"task:{task_id}", + *[f"asset:{a['id']}" for a in assets], *[f"evidence:{e['id']}" for e in evidences]])) + task_request = {"project_id": store.project_id, "task_id": task_id, + "workflow_id": "mining_research_kernel.workflow.research", + "task_type": "mining_research_kernel.task.evidence_review", "maturity": "known_workflow", + "max_runs": 1, "route_id": ids["route"], "routes": [ids["route"]], + "allowed_tools": ["evidence.read_only"], "verification_gates": [], + "task_context": task_context, "question_statement": question, + "claim_statement": f"Recorded {mode.replace('_', ' ')} observation for existing exported data.", + "input": {"question": question, "review_mode": mode, **copy.deepcopy(input_data)}, + "asset_refs": [a["id"] for a in assets], "evidence_refs": [e["id"] for e in evidences]} + config = load_config(root) + packet = TaskEngine(config, build_research_workflow_pack(config, task_request, {})).start(task_request) + decision_id = "decision.resultcsv." + hashlib.sha256((task_id + "|" + mode).encode()).hexdigest()[:24] + judgment = copy.deepcopy(assessment["judgment"]) + packet.update({"state": "completed", "asset_refs": [a["id"] for a in assets], + "evidence_refs": [e["id"] for e in evidences], "citation_refs": [e["id"] for e in evidences], + "review_status": "recorded", "review_record_ref": decision_id, + "research_judgment_status": judgment["status"], "completion_scope": mode, + "material_reads": [{"asset_id": asset["id"], "evidence_refs": [ev["id"] for ev in evidences if ev.get("asset_ref") == asset["id"]], + "locator": copy.deepcopy(asset["locator"]), "registration_status": "registered", + "locator_status": "embedded_snapshot", "content_status": "snapshot_hash_verified", + "reading_status": "READ_WITH_LIMITS", "verification_status": "NOT_VERIFIED", + "asset_kind": asset["asset_kind"], "authority": asset["authority"], + "asset_status": asset["status"], "content_sha256": asset["content_sha256"]} + for asset in assets], + "material_gaps": copy.deepcopy(assessment.get("material_gaps", [])), + "next_action": {"action_id": None, "executable": False, "input_refs": [], + "expected_outputs": [], "preconditions": [], "reason": mode + "_recorded", + "resume_condition": "start a new task with a new task_id for a new capture or comparison"}}) + packet.setdefault("history", []).append({"event": mode + "_recorded", "from": "ready", + "to": "completed", "decision_id": decision_id}) + question_record = _record("ResearchQuestion", ids["question"], store.project_id, source_refs, + statement=question, status="active") + claim_record = _record("Claim", ids["claim"], store.project_id, source_refs, + statement=task_request["claim_statement"], status="proposed") + route = _record("Route", ids["route"], store.project_id, source_refs, + status="completed", route_id=ids["route"], question_id=ids["question"], + research_question_id=ids["question"], hypothesis_id=None, claim_id=ids["claim"], + task_id=task_id, parent_route_id=None, supersedes_route_id=None, + workflow_id=task_request["workflow_id"], method_id="mining_research_kernel.method.research.evidence_review", + inputs=[input_data], expected_evidence=["captured result CSV evidence"], assigned_role="host", + budget=1, runs_used=0, stop_conditions=[], verification_gates=[], + outputs=[e["id"] for e in evidences], reservations=[], write_set=["research/records"]) + decision = _record("Decision", decision_id, store.project_id, + list(dict.fromkeys([*source_refs, f"decision:{decision_id}"])), + status=judgment["status"].lower(), statement=judgment["summary"], + scope={"project_id": store.project_id, "task_id": task_id, "route_id": ids["route"], "kind": mode}, + assessment=copy.deepcopy(assessment), judgment=judgment, + material_read_count=len(assets)) + results = {mode: copy.deepcopy(operation_result)} + task_state = _record("TaskState", task_id, store.project_id, + list(dict.fromkeys([*source_refs, f"decision:{decision_id}"])), task_id=task_id, + state="completed", packet=packet, operation_results=results) + records = [*(new_records or []), question_record, claim_record, route, decision, task_state] + relationships = [ + _relationship(_edge_id(task_id, "route-addresses"), "route_addresses_question", route, question_record, store.project_id, source_refs), + _relationship(_edge_id(task_id, "route-claim"), "route_targets_claim", route, claim_record, store.project_id, source_refs), + ] + record_by_id = {r["id"]: r for r in [*assets, *evidences, *records]} + for index, asset in enumerate(assets): + relationships.append(_relationship(_edge_id(task_id, f"route-asset-{index}"), "route_reads_asset", route, asset, store.project_id, source_refs)) + for index, evidence in enumerate(evidences): + relationships.append(_relationship(_edge_id(task_id, f"route-evidence-{index}"), "route_reads_evidence", route, evidence, store.project_id, source_refs)) + relationships.append(_relationship(_edge_id(task_id, f"decision-evidence-{index}"), "decision_records_evidence", decision, evidence, store.project_id, source_refs)) + asset = record_by_id[evidence["asset_ref"]] + if asset.get("revision") == 1 and asset.get("id") in {r["id"] for r in (new_records or [])}: + relationships.append(_relationship(_edge_id(task_id, f"evidence-asset-{index}"), "evidence_derived_from_asset", evidence, asset, store.project_id, source_refs)) + relationships.append(_relationship(_edge_id(task_id, "decision-route"), "decision_closes_route", decision, route, store.project_id, source_refs)) + store.commit("result-csv." + hashlib.sha256(task_id.encode()).hexdigest()[:32], _PRODUCER, + records, relationships, expected_revisions=expected_revisions or {}) + return {"task_packet": packet, "decision_id": decision_id} + + +def _find_capture(store: ResearchStore, asset_ref: str) -> tuple[dict[str, Any], dict[str, Any]]: + asset = store.latest_record(asset_ref, "Asset") + evidence_id = asset.get("payload", {}).get("evidence_id") if asset else None + evidence = store.latest_record(evidence_id, "Evidence") if isinstance(evidence_id, str) else None + if asset is None or evidence is None or asset.get("asset_kind") != "result_csv_capture": + raise ValueError(f"unknown result CSV capture asset: {asset_ref}") + payload = asset.get("payload") + if not isinstance(payload, dict) or payload.get("kind") != "result_csv_observation": + raise ValueError(f"invalid result CSV capture payload: {asset_ref}") + snapshot_hash = _sha256_bytes(_canonical(payload)) + relation_bound = any( + relation.get("relation") == "evidence_derived_from_asset" + and relation.get("from_id") == evidence.get("id") + and relation.get("from_revision") == evidence.get("revision") + and relation.get("to_id") == asset.get("id") + and relation.get("to_revision") == asset.get("revision") + for transaction in store.list_transactions() + for relation in transaction.get("relationships", []) + ) + if (snapshot_hash != asset.get("content_sha256") or evidence.get("asset_ref") != asset_ref + or not relation_bound): + raise ValueError(f"capture asset/evidence hash or binding mismatch: {asset_ref}") + return asset, evidence + + +def import_result_csv(project_root: str | os.PathLike[str], *, task_id: str, question: str, + csv_path: str | os.PathLike[str], metadata: dict[str, Any], + encoding: str = "utf-8-sig", task_context: str = "production") -> dict[str, Any]: + root = Path(project_root).expanduser().resolve() + task_id = _id(task_id, "task_id") + if not isinstance(question, str) or not question.strip() or len(question) > 2000: + raise ValueError("question must be a non-empty string of at most 2000 characters") + if not isinstance(task_context, str) or task_context not in {"production", "synthetic"}: + raise ValueError("task_context must be production or synthetic") + if not isinstance(csv_path, (str, os.PathLike)) or not str(csv_path).strip() or len(str(csv_path)) > 4096: + raise ValueError("csv_path must be a non-empty bounded string or Path") + if not isinstance(encoding, str) or not encoding.strip() or len(encoding) > 100: + raise ValueError("encoding must be a non-empty bounded string") + meta, metadata_gaps = _metadata(metadata) + if (task_context == "synthetic") != (meta["origin"] == "synthetic"): + raise ValueError("synthetic metadata and task_context must be used together") + mode = "result_csv_import" + store = ResearchStore(root) + request_core = {"task_id": task_id, "question": question.strip(), "metadata": meta, + "encoding": encoding, "task_context": task_context} + # Compare the path identity without opening the source on replay. + source_path = _resolve_source(root, csv_path) + locator, source_label = _locator(root, source_path) + request_hash = _sha256_bytes(_canonical({**request_core, "locator": locator})) + prior = _state(store, task_id) + if prior is not None: + recorded = _operation(prior, mode) + if not recorded or recorded.get("request_sha256") != request_hash: + raise ValueError(f"task_id already exists for a different request: {task_id}") + capture = copy.deepcopy(recorded["capture"]) + return _base(task_id, prior["packet"], True, capture=capture, + asset_refs=copy.deepcopy(recorded["asset_refs"]), + evidence_refs=copy.deepcopy(recorded["evidence_refs"]), + capture_asset_ref=recorded["capture_asset_ref"], source_label=source_label) + parsed = read_result_csv(source_path, encoding=encoding) + if meta["origin"] == "synthetic" and task_context != "synthetic": + raise ValueError("synthetic data cannot be imported as production") + raw_hash = parsed["sha256"] + # Pin the original bytes through a derived, immutable row snapshot. No source bytes are copied. + payload = {"schema_version": 1, "kind": "result_csv_observation", "capture_task_id": task_id, + "source_sha256": raw_hash, + "source_locator": locator, "source_label": source_label, "format": parsed["format"], + "encoding": parsed["encoding"], "columns": parsed["columns"], "row_count": parsed["row_count"], + "rows": parsed["rows"], "diagnostics": parsed["diagnostics"], "limits": parsed["limits"], + "metadata": meta, "metadata_gaps": metadata_gaps, + "conditions_are_caller_assertions": True} + snapshot_hash = _sha256_bytes(_canonical(payload)) + _task_ids(task_id) + suffix = hashlib.sha256(task_id.encode()).hexdigest()[:24] + asset_id, evidence_id = f"capture.{suffix}", f"evidence.capture.{suffix}" + payload["evidence_id"] = evidence_id + snapshot_hash = _sha256_bytes(_canonical(payload)) + refs = [f"task:{task_id}", f"asset:{asset_id}", f"evidence:{evidence_id}"] + asset_locator = {"path": f"record:{asset_id}#payload", "path_kind": "record_embedded", + "record_id": asset_id, "field": "payload", "embedded_payload": "payload", + "source_locator": locator, "caller_label": source_label} + asset = _record("Asset", asset_id, store.project_id, refs, asset_kind="result_csv_capture", + locator=asset_locator, content_sha256=snapshot_hash, authority="derived", + status="observed", payload=payload) + evidence = _record("Evidence", evidence_id, store.project_id, refs, + evidence_kind="result_csv_observation", asset_ref=asset_id, + locator=asset_locator, status="observed") + quality_gaps = [f"csv_{item['code']}" for item in parsed["diagnostics"]] + valid_rows = [row for row in parsed["rows"] if row["status"] == "VALID"] + capture_status = "PROVISIONAL_WITH_GAPS" if valid_rows else "INSUFFICIENT" + capture_gaps = list(dict.fromkeys(metadata_gaps + quality_gaps + ["solver_not_run", "engineering_causality_not_verified"])) + assessment = {"scope": "material_reading_and_evidence_synthesis_only", + "material_reads": [{"asset_id": asset_id, "evidence_refs": [evidence_id], + "observed_sha256": snapshot_hash, "reading_status": "READ_WITH_LIMITS", + "verification_status": "NOT_VERIFIED", "locator": asset_locator, + "summary": "Read-only capture of an existing exported CSV; solver provenance and engineering meaning are unverified.", + "numeric_check_status": "PARTIAL", "scientific_validation_status": "NOT_VERIFIED", + "gaps": capture_gaps}], + "material_gaps": [{"asset_id": asset_id, "reason": "export provenance and engineering interpretation unverified", + "next_action": "User chooses any further analysis."}], + "judgment": {"status": capture_status, "summary": "CSV observations captured; no solver was run and no engineering causality was verified.", + "gaps": capture_gaps, + "next_action": {"action": _DEFAULT_ACTION, "executable": False, "requires_user_choice": True}}} + capture = {"source_sha256": raw_hash, "snapshot_sha256": snapshot_hash, "source_locator": locator, + "source_label": source_label, "metadata": meta, "metadata_gaps": metadata_gaps, + "columns": parsed["columns"], "row_count": parsed["row_count"], "rows": parsed["rows"], + "diagnostics": parsed["diagnostics"], "quality_gaps": quality_gaps, "limits": parsed["limits"], + "judgment": copy.deepcopy(assessment["judgment"])} + operation_result = {"request_sha256": request_hash, "capture": capture, + "asset_refs": [asset_id], "capture_asset_ref": asset_id, + "evidence_refs": [evidence_id]} + _commit_review_task(root, task_id=task_id, question=question.strip(), task_context=task_context, + mode=mode, input_data={"metadata": meta, "source_sha256": raw_hash}, assets=[asset], + evidences=[evidence], assessment=assessment, operation_result=operation_result, + new_records=[asset, evidence]) + final_state = _state(store, task_id) + return _base(task_id, final_state["packet"], False, capture=capture, + asset_refs=[asset_id], capture_asset_ref=asset_id, + evidence_refs=[evidence_id], source_label=source_label) + + +def compare_results(project_root: str | os.PathLike[str], *, task_id: str, question: str, + baseline_asset_ref: str, candidate_asset_ref: str, point_ids: list[str], + comparability_note: str = "", related_task_ids: list[str] | None = None, + next_action: str = _DEFAULT_ACTION, task_context: str = "production") -> dict[str, Any]: + root = Path(project_root).expanduser().resolve() + task_id = _id(task_id, "task_id") + if not isinstance(question, str) or not question.strip() or len(question) > 2000: + raise ValueError("question must be a non-empty string of at most 2000 characters") + if not isinstance(task_context, str) or task_context not in {"production", "synthetic"}: + raise ValueError("task_context must be production or synthetic") + if not isinstance(point_ids, list) or not 1 <= len(point_ids) <= 100: + raise ValueError("point_ids must contain 1 to 100 selected points") + if any(not isinstance(point, str) or not point.strip() or len(point) > 200 for point in point_ids): + raise ValueError("point_ids must be bounded non-empty strings") + if len(set(point_ids)) != len(point_ids): + raise ValueError("point_ids must be unique") + if not isinstance(related_task_ids, (list, type(None))): + raise ValueError("related_task_ids must be a list or null") + related_task_ids = related_task_ids or [] + if any(not isinstance(item, str) or not item.strip() for item in related_task_ids): + raise ValueError("related_task_ids must contain non-empty task ID strings") + related_task_ids = [_id(item, "related_task_id") for item in related_task_ids] + if len(set(related_task_ids)) != len(related_task_ids) or len(related_task_ids) > 20: + raise ValueError("related_task_ids must be unique and at most 20") + if not isinstance(comparability_note, str) or len(comparability_note) > 2000: + raise ValueError("comparability_note must be a string of at most 2000 characters") + if not isinstance(next_action, str) or not next_action.strip() or len(next_action) > 1000: + raise ValueError("next_action must be a non-empty bounded string") + if baseline_asset_ref == candidate_asset_ref: + raise ValueError("baseline and candidate must reference distinct capture Assets") + store = ResearchStore(root) + request = {"task_id": task_id, "question": question.strip(), + "baseline_asset_ref": baseline_asset_ref, "candidate_asset_ref": candidate_asset_ref, + "point_ids": point_ids, "comparability_note": comparability_note, + "related_task_ids": related_task_ids, "next_action": next_action, + "task_context": task_context} + request_hash = _sha256_bytes(_canonical(request)) + prior = _state(store, task_id) + if prior is not None: + recorded = _operation(prior, "result_csv_comparison") + if not recorded or recorded.get("request_sha256") != request_hash: + raise ValueError(f"task_id already exists for a different comparison: {task_id}") + return _base(task_id, prior["packet"], True, **copy.deepcopy(recorded["result"])) + + baseline, baseline_evidence = _find_capture(store, baseline_asset_ref) + candidate, candidate_evidence = _find_capture(store, candidate_asset_ref) + for asset in (baseline, candidate): + origin = asset["payload"].get("metadata", {}).get("origin") + if (origin == "synthetic") != (task_context == "synthetic"): + raise ValueError("synthetic captures cannot enter a production comparison") + + related_snapshots = [] + pins: dict[str, int] = {baseline["id"]: baseline["revision"], + candidate["id"]: candidate["revision"], + baseline_evidence["id"]: baseline_evidence["revision"], + candidate_evidence["id"]: candidate_evidence["revision"]} + for related_id in related_task_ids: + related = store.latest_record(_id(related_id, "related_task_id"), "TaskState") + if related is None: + raise ValueError(f"unknown related task: {related_id}") + related_context = related.get("packet", {}).get("task_context", "production") + if task_context == "production" and related_context == "synthetic": + raise ValueError("synthetic related tasks cannot enter a production comparison") + decision = _decision_bound_to_task_state(store, related) + if decision is None: + raise ValueError(f"related task has no Decision bound to its current revision: {related_id}") + pins[related["id"]] = related["revision"] + pins[decision["id"]] = decision["revision"] + packet_input = related.get("packet", {}).get("input", {}) + script_review = packet_input.get("script_review", {}) if isinstance(packet_input, Mapping) else {} + script_snapshot = script_review.get("script_snapshot", {}) if isinstance(script_review, Mapping) else {} + document_sources = script_review.get("documentation_sources", []) if isinstance(script_review, Mapping) else [] + source_context = {} + if isinstance(script_snapshot, Mapping): + source_context["script"] = {key: copy.deepcopy(script_snapshot.get(key)) for key in + ("source", "start_line", "end_line", "script_sha256", "encoding") if key in script_snapshot} + if isinstance(document_sources, list): + source_context["documentation"] = [] + for doc in document_sources: + citation = doc.get("citation", {}) if isinstance(doc, Mapping) else {} + if isinstance(citation, Mapping): + source_context["documentation"].append({key: copy.deepcopy(citation.get(key)) for key in + ("source_id", "product", "page", "anchor", "document_build", "sha256_body", "trust_class") if key in citation}) + assessment = decision.get("assessment", {}) + doc_result = assessment.get("documentation_result", {}) if isinstance(assessment, Mapping) else {} + citation = doc_result.get("citation", {}) if isinstance(doc_result, Mapping) else {} + if isinstance(citation, Mapping) and citation: + source_context["documentation"] = [{key: copy.deepcopy(citation.get(key)) for key in + ("source_id", "product", "page", "anchor", "document_build", "sha256_body", "trust_class") if key in citation}] + summary = {"task_id": related["id"], "task_revision": related["revision"], + "task_context": related_context, + "task_type": related.get("packet", {}).get("task_type"), + "decision_id": decision["id"], "decision_revision": decision["revision"], + "judgment": copy.deepcopy(decision.get("judgment", {})), + "source_context": source_context} + related_snapshots.append(summary) + bpayload, cpayload = baseline["payload"], candidate["payload"] + bmeta, cmeta = bpayload["metadata"], cpayload["metadata"] + gaps: list[str] = [] + metadata_compatible = True + for key in ("quantity", "unit"): + if not bmeta.get(key) or not cmeta.get(key): + metadata_compatible = False + gaps.append(f"{key}_unknown") + elif bmeta[key] != cmeta[key]: + metadata_compatible = False + gaps.append(f"{key}_mismatch") + if bmeta.get("point_basis") != cmeta.get("point_basis") or not bmeta.get("point_basis") or not cmeta.get("point_basis"): + gaps.append("point_basis_unknown_or_different") + condition_keys = set(bmeta.get("conditions", {})) | set(cmeta.get("conditions", {})) + condition_differences = [key for key in sorted(condition_keys) + if bmeta.get("conditions", {}).get(key) != cmeta.get("conditions", {}).get(key)] + if condition_differences: + gaps.extend("condition_unknown_or_different:" + key for key in condition_differences) + gaps.extend(f"condition_value_unknown:{key}" for key in condition_keys + if bmeta.get("conditions", {}).get(key) is None or cmeta.get("conditions", {}).get(key) is None) + for capture in (bpayload, cpayload): + gaps.extend(capture.get("metadata_gaps", [])) + gaps.extend(f"csv_{diagnostic.get('code', 'diagnostic')}" for diagnostic in capture.get("diagnostics", [])) + if bmeta.get("case_id") == cmeta.get("case_id"): + gaps.append("same_case_id") + brows = {} + crows = {} + for row in bpayload.get("rows", []): + brows.setdefault(row["point_id"], []).append(row) + for row in cpayload.get("rows", []): + crows.setdefault(row["point_id"], []).append(row) + points = [] + for point_id in point_ids: + br = brows.get(point_id, []) + cr = crows.get(point_id, []) + item: dict[str, Any] = {"point_id": point_id, + "baseline": {"source_sha256": bpayload["source_sha256"], "rows": copy.deepcopy(br)}, + "candidate": {"source_sha256": cpayload["source_sha256"], "rows": copy.deepcopy(cr)}, + "delta": None} + if not br or not cr: + item.update(status="INSUFFICIENT", reason="point_missing_from_baseline" if not br else "point_missing_from_candidate") + elif len(br) != 1 or len(cr) != 1 or br[0]["status"] == "DUPLICATE" or cr[0]["status"] == "DUPLICATE": + item.update(status="INSUFFICIENT", reason="duplicate_point_id") + elif br[0]["status"] != "VALID" or cr[0]["status"] != "VALID": + item.update(status="INSUFFICIENT", reason="baseline_" + br[0]["status"].lower() if br[0]["status"] != "VALID" else "candidate_" + cr[0]["status"].lower()) + elif not metadata_compatible: + item.update(status="INSUFFICIENT", reason="quantity_or_unit_not_known_and_identical") + else: + item.update(status="ARITHMETIC_DELTA_ONLY", baseline_value=br[0]["value_text"], + candidate_value=cr[0]["value_text"], + delta=difference(cr[0]["value_text"], br[0]["value_text"])) + points.append(item) + computable = sum(1 for item in points if item["delta"] is not None) + result_status = "INSUFFICIENT" if not computable else "PROVISIONAL_WITH_GAPS" + judgment = {"status": result_status, + "summary": f"Computed candidate-minus-baseline arithmetic deltas for {computable} selected points; engineering comparability remains unverified.", + "gaps": list(dict.fromkeys(gaps + ([] if computable == len(points) else ["one_or_more_selected_points_insufficient"]) + ["solver_not_run", "engineering_causality_not_verified"])), + "next_action": {"action": next_action, "executable": False, "requires_user_choice": True}} + comparison = {"status": result_status, "baseline_asset_ref": baseline_asset_ref, + "candidate_asset_ref": candidate_asset_ref, "point_ids": list(point_ids), "points": points, + "comparability_note": comparability_note, + "metadata": {"baseline": copy.deepcopy(bmeta), "candidate": copy.deepcopy(cmeta)}, + "conditions_are_caller_assertions": True, + "statement": "Existing exported data only; no solver was run and no engineering causality or physical comparability is verified."} + related_context = {"snapshots": related_snapshots, + "meaning": "User-associated historical context only; it does not establish that a script produced either CSV."} + sources = [{"asset_ref": baseline["id"], "evidence_ref": baseline_evidence["id"], + "asset_revision": baseline["revision"], "evidence_revision": baseline_evidence["revision"], + "source_sha256": bpayload["source_sha256"], "snapshot_sha256": baseline["content_sha256"], + "source_locator": copy.deepcopy(bpayload["source_locator"]), "source_label": bpayload["source_label"], + "metadata": copy.deepcopy(bpayload["metadata"]), "columns": copy.deepcopy(bpayload["columns"]), + "diagnostics": copy.deepcopy(bpayload["diagnostics"]), + "citation": {"source_label": bpayload["source_label"], "locator": copy.deepcopy(bpayload["source_locator"]), + "metadata": copy.deepcopy(bpayload["metadata"]), "columns": copy.deepcopy(bpayload["columns"])}}, + {"asset_ref": candidate["id"], "evidence_ref": candidate_evidence["id"], + "asset_revision": candidate["revision"], "evidence_revision": candidate_evidence["revision"], + "source_sha256": cpayload["source_sha256"], "snapshot_sha256": candidate["content_sha256"], + "source_locator": copy.deepcopy(cpayload["source_locator"]), "source_label": cpayload["source_label"], + "metadata": copy.deepcopy(cpayload["metadata"]), "columns": copy.deepcopy(cpayload["columns"]), + "diagnostics": copy.deepcopy(cpayload["diagnostics"]), + "citation": {"source_label": cpayload["source_label"], "locator": copy.deepcopy(cpayload["source_locator"]), + "metadata": copy.deepcopy(cpayload["metadata"]), "columns": copy.deepcopy(cpayload["columns"])}}] + + assessment = {"scope": "material_reading_and_evidence_synthesis_only", "comparison": comparison, + "related_context": related_context, + "material_reads": [{"asset_id": src["asset_ref"], "evidence_refs": [src["evidence_ref"]], + "observed_sha256": store.latest_record(src["asset_ref"], "Asset")["content_sha256"], + "reading_status": "READ_WITH_LIMITS", + "verification_status": "NOT_VERIFIED", "locator": store.latest_record(src["asset_ref"], "Asset")["locator"], + "summary": "Compared persisted read-only CSV capture snapshot.", "numeric_check_status": "PARTIAL", + "scientific_validation_status": "NOT_VERIFIED", "gaps": judgment["gaps"]} for src in sources], + "material_gaps": [{"asset_id": src["asset_ref"], "reason": "engineering meaning and source provenance are unverified", + "next_action": next_action} for src in sources], "judgment": judgment} + full = {"comparison": comparison, "sources": sources, "related_context": related_context, + "judgment": judgment} + operation_result = {"request_sha256": request_hash, "result": full} + _commit_review_task(root, task_id=task_id, question=question.strip(), task_context=task_context, + mode="result_csv_comparison", input_data={"request_sha256": request_hash, + "related_task_ids": related_task_ids, "baseline_asset_ref": baseline_asset_ref, + "candidate_asset_ref": candidate_asset_ref, "point_ids": point_ids}, + assets=[baseline, candidate], evidences=[baseline_evidence, candidate_evidence], + assessment=assessment, operation_result=operation_result, expected_revisions=pins) + saved = _state(store, task_id) + return _base(task_id, saved["packet"], False, **full) + + +def result_comparison_progress(project_root: str | os.PathLike[str], *, task_id: str, + source_paths: dict[str, str] | None = None) -> dict[str, Any]: + root = Path(project_root).expanduser().resolve() + store = ResearchStore(root) + state = _state(store, _id(task_id, "task_id")) + if state is None: + raise ValueError(f"unknown task: {task_id}") + if source_paths is not None and (not isinstance(source_paths, dict) or any( + not isinstance(k, str) or not isinstance(v, str) or not v.strip() or len(v) > 4096 + for k, v in source_paths.items())): + raise ValueError("source_paths must map capture asset IDs to paths") + operation = _operation(state, "result_csv_import") + if operation: + captures = [operation["capture"]] + assets = operation["asset_refs"] + comparisons = [] + kind = "import" + else: + operation = _operation(state, "result_csv_comparison") + if not operation: + raise ValueError(f"task has no result CSV import or comparison: {task_id}") + full = operation["result"] + captures, assets, comparisons, kind = [], [s["asset_ref"] for s in full["sources"]], [full], "comparison" + known_assets = set(assets) + if source_paths is not None and set(source_paths) - known_assets: + raise ValueError("source_paths contains an unknown capture Asset ID") + checks = {} + for asset_id in assets: + if source_paths is None or asset_id not in source_paths: + status = "not_checked" + else: + try: + path = _resolve_source(root, source_paths[asset_id]) + if not path.is_file(): + status = "missing" + else: + with path.open("rb") as stream: + raw = stream.read(2 * 1024 * 1024 + 1) + if len(raw) > 2 * 1024 * 1024: + raise OSError("source exceeds 2 MiB check limit") + current = hashlib.sha256(raw).hexdigest() + if kind == "import": + original_hash = captures[0]["source_sha256"] + else: + original_hash = next(item["source_sha256"] for item in comparisons[0]["sources"] if item["asset_ref"] == asset_id) + status = "unchanged" if current == original_hash else "changed" + except OSError: + status = "read_error" + checks[asset_id] = {"status": status, "snapshot_retained": True} + import_judgment = copy.deepcopy(captures[0].get("judgment", {})) if captures else None + return _base(task_id, state["packet"], True, kind=kind, captures=copy.deepcopy(captures), + comparisons=copy.deepcopy(comparisons), sources=copy.deepcopy(assets), source_checks=checks, + related_context=copy.deepcopy(comparisons[0].get("related_context", {})) if comparisons else {}, + judgment=copy.deepcopy(comparisons[0].get("judgment", {})) if comparisons else import_judgment) + + +def render_result_comparison_report(project_root: str | os.PathLike[str], *, task_id: str) -> str: + def md(value: Any) -> str: + return str(value).replace("|", "\\|").replace("\r", " ").replace("\n", " ") + + progress = result_comparison_progress(project_root, task_id=task_id) + lines = [f"# Result CSV {progress['kind']} report", "", + "Existing exported data only. No solver was run; engineering causality and physical comparability are not verified.", ""] + if progress["kind"] == "import": + for capture in progress["captures"]: + lines.extend([f"## Capture {capture['metadata']['case_id']}", "", + f"- Original source SHA-256: `{capture['source_sha256']}`", + f"- Snapshot SHA-256: `{capture['snapshot_sha256']}`", + f"- Source: `{capture['source_label']}`", + f"- Metadata: `{json.dumps(capture['metadata'], ensure_ascii=False, sort_keys=True)}`", + f"- Diagnostics: `{json.dumps(capture['diagnostics'], ensure_ascii=False, sort_keys=True)}`", "", + "| Point | Value | Status | Lines |", "|---|---|---|---|"]) + for row in capture["rows"]: + lines.append(f"| {md(row['point_id'])} | {md(row['value_text'])} | {md(row['status'])} | {row['start_line']}-{row['end_line']} |") + lines.extend(["", f"Gaps: {', '.join(capture.get('judgment', {}).get('gaps', [])) or '(none recorded)'}", + f"Next action: {capture.get('judgment', {}).get('next_action', {}).get('action', _DEFAULT_ACTION)}", ""]) + else: + full = progress["comparisons"][0] + comparison = full["comparison"] + lines.extend([f"## Comparison: {comparison['status']}", "", + f"- Comparability note: {comparison['comparability_note'] or '(none)'}", + f"- Metadata: `{json.dumps(comparison['metadata'], ensure_ascii=False, sort_keys=True)}`", "", + "### Sources", ""]) + for source in full["sources"]: + lines.extend([f"- `{source['asset_ref']}` Asset revision {source['asset_revision']}, Evidence revision {source['evidence_revision']}", + f" Original SHA-256: `{source['source_sha256']}`; snapshot SHA-256: `{source['snapshot_sha256']}`", + f" Citation: `{json.dumps(source['citation'], ensure_ascii=False, sort_keys=True)}`", + f" Diagnostics: `{json.dumps(source['diagnostics'], ensure_ascii=False, sort_keys=True)}`"]) + lines.extend(["", "### Selected points", "", + "| Point | Status | Baseline | Candidate | Candidate − baseline | Baseline lines | Candidate lines |", + "|---|---|---:|---:|---:|---|---|"]) + for point in comparison["points"]: + b, c = point["baseline"]["rows"], point["candidate"]["rows"] + bv = point.get("baseline_value", b[0].get("value_text") if len(b) == 1 else "") + cv = point.get("candidate_value", c[0].get("value_text") if len(c) == 1 else "") + bline = f"{b[0]['start_line']}-{b[0]['end_line']}" if len(b) == 1 else "" + cline = f"{c[0]['start_line']}-{c[0]['end_line']}" if len(c) == 1 else "" + lines.append(f"| {md(point['point_id'])} | {md(point['status'])} ({md(point.get('reason', 'arithmetic only'))}) | {md(bv)} | {md(cv)} | {md(point.get('delta') or '')} | {bline} | {cline} |") + gaps = progress["judgment"].get("gaps", []) + lines.extend(["", f"Gaps: {', '.join(gaps) or '(none recorded)'}", "", + "### Related historical context", "", progress["related_context"].get("meaning", "")]) + for related in progress["related_context"].get("snapshots", []): + lines.append(f"- Task `{md(related.get('task_id'))}` revision {related.get('task_revision')} ({md(related.get('task_context', 'unknown'))}); Decision `{md(related.get('decision_id'))}` revision {related.get('decision_revision')}") + related_judgment = related.get("judgment", {}) + if isinstance(related_judgment, Mapping): + lines.append(f" - Judgment: {md(related_judgment.get('status', 'unknown'))}: {md(related_judgment.get('summary', ''))}") + lines.append(f" - Judgment gaps: {md(', '.join(related_judgment.get('gaps', [])))}") + for category, items in related.get("source_context", {}).items(): + if isinstance(items, Mapping): + lines.append(f" - {md(category)}: `{json.dumps(items, ensure_ascii=False, sort_keys=True)}`") + elif isinstance(items, list): + for item in items: + lines.append(f" - {md(category)}: `{json.dumps(item, ensure_ascii=False, sort_keys=True)}`") + lines.extend(["", f"Next action: {progress['judgment'].get('next_action', {}).get('action', _DEFAULT_ACTION)}", ""]) + return "\n".join(lines) + + +__all__ = ["import_result_csv", "compare_results", "result_comparison_progress", "render_result_comparison_report"] diff --git a/mining_research_kernel/result_csv.py b/mining_research_kernel/result_csv.py new file mode 100644 index 0000000..41a6bde --- /dev/null +++ b/mining_research_kernel/result_csv.py @@ -0,0 +1,187 @@ +"""Read-only parser for bounded MRK point-value CSV results.""" + +from __future__ import annotations + +import csv +import hashlib +import io +import re +from decimal import Decimal, InvalidOperation, localcontext +from pathlib import Path +from typing import Any + + +MAX_FILE_BYTES = 2 * 1024 * 1024 +MAX_ROWS = 2000 +MAX_CELL_CHARS = 512 +MAX_POINT_ID_CHARS = 200 +MAX_NUMERIC_TOKEN_CHARS = 128 +MAX_NUMERIC_DIGITS = 100 +MIN_ADJUSTED_EXPONENT = -100 +MAX_ADJUSTED_EXPONENT = 100 +MIN_DECIMAL_EXPONENT = MIN_ADJUSTED_EXPONENT - (MAX_NUMERIC_DIGITS - 1) + +_NUMBER_RE = re.compile(r"^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$") + + +def _parse_value(value_text: str) -> tuple[str, str, Decimal | None]: + token = value_text.strip() + if not token: + return "MISSING", "", None + if len(token) > MAX_NUMERIC_TOKEN_CHARS or not _NUMBER_RE.fullmatch(token): + return "INVALID", "value is not a bounded decimal number", None + try: + value = Decimal(token) + except InvalidOperation: + return "INVALID", "value is not a decimal number", None + if not value.is_finite(): + return "INVALID", "non-finite values are not allowed", None + digits = value.as_tuple().digits + significant_digits = len("".join(str(digit) for digit in digits).lstrip("0")) + if significant_digits > MAX_NUMERIC_DIGITS: + return "INVALID", "value exceeds 100 significant digits", None + exponent = value.as_tuple().exponent + if value.is_zero(): + if not MIN_DECIMAL_EXPONENT <= exponent <= MAX_ADJUSTED_EXPONENT: + return "INVALID", "zero exponent is outside [-199, 100]", None + elif not MIN_ADJUSTED_EXPONENT <= value.adjusted() <= MAX_ADJUSTED_EXPONENT: + return "INVALID", "adjusted exponent is outside [-100, 100]", None + return "VALID", str(value), value + + +def read_result_csv(path: str | Path, *, encoding: str = "utf-8-sig") -> dict[str, Any]: + """Read one bounded point_id,value CSV without modifying or executing it.""" + try: + with Path(path).open("rb") as source: + raw = source.read(MAX_FILE_BYTES + 1) + except (IsADirectoryError, PermissionError) as exc: + raise ValueError("CSV source must be a readable regular file") from exc + if len(raw) > MAX_FILE_BYTES: + raise ValueError(f"CSV exceeds maximum size of {MAX_FILE_BYTES} bytes") + try: + text = raw.decode(encoding, errors="strict") + except (LookupError, UnicodeDecodeError) as exc: + raise ValueError(f"CSV cannot be decoded with encoding {encoding!r}") from exc + + reader = csv.reader(io.StringIO(text, newline=""), delimiter=",", strict=True) + try: + headers = next(reader) + except StopIteration as exc: + raise ValueError("CSV is empty; expected a header and at least one data row") from exc + except csv.Error as exc: + raise ValueError(f"invalid CSV header: {exc}") from exc + + if len(headers) != 2 or len(set(headers)) != len(headers): + raise ValueError("CSV header must contain exactly two distinct columns") + if any(len(cell) > MAX_CELL_CHARS for cell in headers): + raise ValueError("CSV header cell exceeds maximum length") + if set(headers) != {"point_id", "value"}: + raise ValueError("CSV columns must be exactly point_id and value") + point_index = headers.index("point_id") + value_index = headers.index("value") + + rows: list[dict[str, Any]] = [] + diagnostics: list[dict[str, Any]] = [] + row_occurrences: dict[str, list[int]] = {} + previous_end_line = reader.line_num + try: + for record_index, cells in enumerate(reader, start=1): + start_line = previous_end_line + 1 + end_line = reader.line_num + previous_end_line = end_line + if len(cells) != 2: + raise ValueError(f"CSV record {record_index} has {len(cells)} columns; expected 2") + if record_index > MAX_ROWS: + raise ValueError(f"CSV exceeds maximum of {MAX_ROWS} data rows") + if any(len(cell) > MAX_CELL_CHARS for cell in cells): + raise ValueError(f"CSV record {record_index} contains a cell over {MAX_CELL_CHARS} characters") + + point_id = cells[point_index] + value_text = cells[value_index] + row: dict[str, Any] = { + "point_id": point_id, + "value_text": value_text, + "value": None, + "status": "VALID", + "start_line": start_line, + "end_line": end_line, + "record_index": record_index, + } + row_index = len(rows) + + point_issue = None + if not point_id or len(point_id) > MAX_POINT_ID_CHARS: + point_issue = "point_id must contain 1 to 200 characters" + elif point_id != point_id.strip(): + point_issue = "point_id must not have leading or trailing whitespace" + elif any(ord(char) < 32 or 127 <= ord(char) <= 159 for char in point_id): + point_issue = "point_id must not contain control characters" + if point_issue: + row["status"] = "INVALID" + diagnostics.append({"code": "invalid_point_id", "point_id": point_id, + "row_indexes": [row_index], "detail": point_issue}) + else: + row_occurrences.setdefault(point_id, []).append(row_index) + + if start_line != end_line: + if row["status"] == "VALID": + row["status"] = "INVALID" + diagnostics.append({"code": "multiline_record", "point_id": point_id, + "row_indexes": [row_index], + "detail": "data records spanning physical lines are not allowed"}) + else: + value_status, detail, parsed = _parse_value(value_text) + if row["status"] == "VALID": + row["status"] = value_status + row["value"] = str(parsed) if parsed is not None else None + if value_status != "VALID": + diagnostics.append({"code": value_status.lower(), "point_id": point_id, + "row_indexes": [row_index], "detail": detail}) + rows.append(row) + except csv.Error as exc: + raise ValueError(f"invalid CSV structure: {exc}") from exc + + if not rows: + raise ValueError("CSV must contain at least one data row") + + for point_id, indexes in row_occurrences.items(): + if len(indexes) > 1: + for index in indexes: + rows[index]["status"] = "DUPLICATE" + rows[index]["value"] = None + diagnostics.append({"code": "duplicate_point_id", "point_id": point_id, + "row_indexes": indexes, + "detail": "point_id occurs in multiple data rows"}) + + return { + "format": "mrk_point_values_v1", + "sha256": hashlib.sha256(raw).hexdigest(), + "encoding": encoding, + "columns": headers, + "row_count": len(rows), + "rows": rows, + "diagnostics": diagnostics, + "limits": {"max_file_bytes": MAX_FILE_BYTES, "max_rows": MAX_ROWS}, + } + + +def difference(candidate_value: str, baseline_value: str) -> str: + """Return the exact finite Decimal difference candidate minus baseline.""" + candidate_status, candidate_detail, candidate = _parse_value(candidate_value) + baseline_status, baseline_detail, baseline = _parse_value(baseline_value) + if candidate_status != "VALID" or candidate is None: + raise ValueError(f"invalid candidate value: {candidate_detail or candidate_status}") + if baseline_status != "VALID" or baseline is None: + raise ValueError(f"invalid baseline value: {baseline_detail or baseline_status}") + candidate_tuple = candidate.as_tuple() + baseline_tuple = baseline.as_tuple() + common_exponent = min(candidate_tuple.exponent, baseline_tuple.exponent) + candidate_width = len(candidate_tuple.digits) + candidate_tuple.exponent - common_exponent + baseline_width = len(baseline_tuple.digits) + baseline_tuple.exponent - common_exponent + required_precision = max(candidate_width, baseline_width) + 1 + with localcontext() as context: + context.prec = required_precision + result = candidate - baseline + if not result.is_finite(): + raise ValueError("difference is not finite") + return str(result) diff --git a/tests/test_result_comparison.py b/tests/test_result_comparison.py new file mode 100644 index 0000000..6ff38d8 --- /dev/null +++ b/tests/test_result_comparison.py @@ -0,0 +1,161 @@ +from __future__ import annotations + +import hashlib +import json +import shutil +import tempfile +import unittest +from pathlib import Path + +from mining_research_kernel.records import ResearchStore +from mining_research_kernel.result_comparison import ( + compare_results, import_result_csv, render_result_comparison_report, + result_comparison_progress, +) +from research_project import enable_research + + +class ResultComparisonTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.base = Path(self.temp.name) + self.project = self.base / "project" + self.project.mkdir() + enable_research(self.project, "result.csv.tests") + self.baseline = self.base / "baseline.csv" + self.candidate = self.base / "candidate.csv" + self.baseline.write_text("point_id,value\nP1,-12.5\nP2,-8\nP3,\n", encoding="utf-8") + self.candidate.write_text("value,point_id\n-6,P4\n-10,P1\n-7,P2\n", encoding="utf-8") + self.meta = {"case_id": "case-A", "quantity": "stress", "unit": "MPa", + "column_meanings": {"point_id": "monitoring point", "value": "stress"}, + "point_basis": "same named points", "conditions": {"support": "A"}} + + def tearDown(self): + self.temp.cleanup() + + def capture(self, task, path, case): + metadata = {**self.meta, "case_id": case} + return import_result_csv(self.project, task_id=task, question="Capture export", csv_path=path, metadata=metadata) + + def test_import_replay_and_restore_without_source(self): + first = self.capture("import-base", self.baseline, "base") + source_hash = hashlib.sha256(self.baseline.read_bytes()).hexdigest() + self.assertEqual(source_hash, first["capture"]["source_sha256"]) + self.assertEqual(first["capture_asset_ref"], first["asset_refs"][0]) + self.baseline.unlink() + replay = self.capture("import-base", self.baseline, "base") + self.assertTrue(replay["replayed"]) + self.assertEqual(first["capture"], replay["capture"]) + self.assertFalse(replay["run_created"]) + self.assertFalse(replay["verification_created"]) + with self.assertRaises(ValueError): + import_result_csv(self.project, task_id="import-base", question="Changed", csv_path=self.baseline, + metadata={**self.meta, "case_id": "base"}) + + def test_selected_points_delta_status_lines_report_and_no_run(self): + base = self.capture("base-cap", self.baseline, "base") + candidate = self.capture("candidate-cap", self.candidate, "candidate") + result = compare_results(self.project, task_id="compare", question="Compare selected points", + baseline_asset_ref=base["asset_refs"][0], candidate_asset_ref=candidate["asset_refs"][0], + point_ids=["P1", "P2", "P3"]) + points = result["comparison"]["points"] + self.assertEqual(["P1", "P2", "P3"], [row["point_id"] for row in points]) + self.assertEqual(["2.5", "1"], [row["delta"] for row in points[:2]]) + self.assertEqual("INSUFFICIENT", points[2]["status"]) + self.assertEqual(2, points[0]["baseline"]["rows"][0]["start_line"]) + self.assertEqual(3, points[0]["candidate"]["rows"][0]["start_line"]) + self.assertNotIn("P4", json.dumps(result["comparison"])) + self.assertFalse(result["run_created"]) + self.assertFalse(result["verification_created"]) + report = render_result_comparison_report(self.project, task_id="compare") + self.assertIn("Candidate − baseline", report) + self.assertIn("No solver was run", report) + self.assertEqual([], list((self.project / "reports").glob("*")) if (self.project / "reports").exists() else []) + + def test_metadata_gates_and_synthetic_isolation(self): + base = self.capture("base-cap", self.baseline, "base") + wrong = self.capture("candidate-cap", self.candidate, "candidate") + # A fresh task with a different unit preserves values but does not calculate deltas. + store = ResearchStore(self.project) + # The mismatch is exercised with a separately captured synthetic pair below. + self.assertIsNotNone(store.latest_record(base["capture_asset_ref"], "Asset")) + synthetic_meta = {**self.meta, "case_id": "syn", "origin": "synthetic"} + synth = import_result_csv(self.project, task_id="synthetic-cap", question="Capture synthetic", + csv_path=self.candidate, metadata=synthetic_meta, task_context="synthetic") + with self.assertRaisesRegex(ValueError, "synthetic captures"): + compare_results(self.project, task_id="mixed", question="Do not mix", + baseline_asset_ref=base["capture_asset_ref"], candidate_asset_ref=synth["capture_asset_ref"], + point_ids=["P1"]) + self.assertTrue(wrong["capture"]["source_sha256"]) + + def test_unit_mismatch_keeps_selected_points_without_delta(self): + base = self.capture("base-unit", self.baseline, "base") + other_metadata = {**self.meta, "case_id": "other", "unit": "kPa"} + other = import_result_csv(self.project, task_id="other-unit", question="Capture other unit", + csv_path=self.candidate, metadata=other_metadata) + result = compare_results(self.project, task_id="unit-compare", question="Compare unlike units", + baseline_asset_ref=base["capture_asset_ref"], candidate_asset_ref=other["capture_asset_ref"], + point_ids=["P1"]) + point = result["comparison"]["points"][0] + self.assertEqual("INSUFFICIENT", point["status"]) + self.assertIsNone(point["delta"]) + self.assertIn("unit_mismatch", result["judgment"]["gaps"]) + + def test_bad_requests_and_progress_source_hash_are_bounded(self): + result = self.capture("base-cap", self.baseline, "base") + with self.assertRaises(ValueError): + compare_results(self.project, task_id="bad", question="bad", + baseline_asset_ref=result["capture_asset_ref"], candidate_asset_ref=result["capture_asset_ref"], + point_ids=["P1", "P1"]) + checks = result_comparison_progress(self.project, task_id="base-cap", + source_paths={result["capture_asset_ref"]: str(self.baseline)}) + self.assertEqual("unchanged", checks["source_checks"][result["capture_asset_ref"]]["status"]) + self.baseline.write_text("point_id,value\nP1,999\n", encoding="utf-8") + changed = result_comparison_progress(self.project, task_id="base-cap", + source_paths={result["capture_asset_ref"]: str(self.baseline)}) + self.assertEqual("changed", changed["source_checks"][result["capture_asset_ref"]]["status"]) + self.assertEqual(result["capture"]["source_sha256"], result_comparison_progress( + self.project, task_id="base-cap")["captures"][0]["source_sha256"]) + + def test_malformed_json_types_fail_as_value_errors(self): + with self.assertRaises(ValueError): + import_result_csv(self.project, task_id="bad-origin", question="bad", csv_path=self.baseline, + metadata={**self.meta, "origin": {}}) + with self.assertRaises(ValueError): + import_result_csv(self.project, task_id="bad-path", question="bad", csv_path={}, metadata=self.meta) + with self.assertRaises(ValueError): + compare_results(self.project, task_id="bad-related", question="bad", + baseline_asset_ref="a", candidate_asset_ref="b", point_ids=["P1"], related_task_ids=[{}]) + + def test_relative_paths_migrate_and_external_same_names_are_distinct(self): + exports = self.project / "exports" + exports.mkdir() + source = exports / "baseline.csv" + source.write_text("point_id,value\nP1,2\n", encoding="utf-8") + first = import_result_csv(self.project, task_id="portable", question="Portable capture", + csv_path="exports/baseline.csv", metadata=self.meta) + moved = self.base / "moved-project" + shutil.copytree(self.project, moved) + replay = import_result_csv(moved, task_id="portable", question="Portable capture", + csv_path="exports/baseline.csv", metadata=self.meta) + self.assertTrue(replay["replayed"]) + self.assertEqual(first["capture"]["source_locator"], replay["capture"]["source_locator"]) + with self.assertRaisesRegex(ValueError, "'..'"): + import_result_csv(self.project, task_id="escape", question="Escape", csv_path="../baseline.csv", metadata=self.meta) + + one = self.base / "external-one" + two = self.base / "external-two" + one.mkdir(); two.mkdir() + (one / "same.csv").write_text("point_id,value\nP1,1\n", encoding="utf-8") + (two / "same.csv").write_text("point_id,value\nP1,1\n", encoding="utf-8") + a = import_result_csv(self.project, task_id="external-one", question="External", csv_path=one / "same.csv", metadata=self.meta) + b = import_result_csv(self.project, task_id="external-two", question="External", csv_path=two / "same.csv", metadata=self.meta) + self.assertEqual("caller:same.csv", a["capture"]["source_locator"]["path"]) + self.assertNotEqual(a["capture"]["source_locator"]["identity_sha256"], b["capture"]["source_locator"]["identity_sha256"]) + with self.assertRaisesRegex(ValueError, "collide"): + import_result_csv(self.project, task_id="bad-conditions", question="Bad metadata", csv_path=source, + metadata={**self.meta, "conditions": {" support": "A", "support ": "B"}}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_result_comparison_cli.py b/tests/test_result_comparison_cli.py new file mode 100644 index 0000000..3c98b69 --- /dev/null +++ b/tests/test_result_comparison_cli.py @@ -0,0 +1,232 @@ +"""Result import/comparison across CLI processes and protected persistence.""" +from __future__ import annotations + +from decimal import Decimal +import hashlib +import json +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +import jsonschema + +from mining_research_kernel.project_context import project_context +from mining_research_kernel.records import ResearchStore +from research_project import enable_research + +REPO = Path(__file__).resolve().parents[1] + + +class ResultComparisonCLITests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.base = Path(self.temp.name) + self.root = self.base / "project with spaces" + self.root.mkdir() + enable_research(self.root, "results.cli.test") + (self.root / "START.md").write_text("# Existing project\n", encoding="utf-8") + self.paths = [] + for name, body in (("baseline", "point_id,value\nP1,-12.5\nP2,-8.0\nP3,\n"), + ("candidate", "value,point_id\n-7.0,P2\n-10.0,P1\n-6.0,P4\n")): + path = self.root / f"{name}.csv" + path.write_text(body, encoding="utf-8") + self.paths.append(path) + (self.base / f"{name}.json").write_text(json.dumps(self.metadata(name)), encoding="utf-8") + + def tearDown(self): + self.temp.cleanup() + + def metadata(self, case): + return {"case_id": case, "quantity": "displacement_y", "unit": "mm", + "column_meanings": {"point_id": "Authored point ID", "value": "Authored signed value"}, + "point_basis": "Shared synthetic point definitions", + "conditions": {"stage": "synthetic stage", "scheme": case}, "origin": "synthetic"} + + def cli(self, *args, expected=0): + result = subprocess.run([sys.executable, "-S", "-B", "-X", "utf8", str(REPO / "mining_kernel.py"), + *args, "--project-root", str(self.root)], cwd=self.base, + capture_output=True, text=True, encoding="utf-8") + self.assertEqual(expected, result.returncode, result.stdout + result.stderr) + return result.stdout + + def import_pair(self): + captures = [] + for name in ("baseline", "candidate"): + result = json.loads(self.cli("result-import", "--task-id", f"import-{name}", "--question", "Read selected export", + "--csv", f"{name}.csv", "--metadata-file", str(self.base / f"{name}.json"), "--task-context", "synthetic")) + captures.append(result["asset_refs"][0]) + return captures + + def compare_args(self, refs, task="compare"): + return ["result-compare", "--task-id", task, "--question", "Compare selected synthetic points", + "--baseline-asset-ref", refs[0], "--candidate-asset-ref", refs[1], + "--point", "P1", "--point", "P2", "--point", "P3", "--task-context", "synthetic"] + + def records(self): + return {p.name: p.read_bytes() for p in (self.root / "research/records").glob("*.json")} + + def test_cli_alignment_source_locators_offline_recovery_and_protected_export(self): + hashes = [hashlib.sha256(p.read_bytes()).hexdigest() for p in self.paths] + refs = self.import_pair() + compared = json.loads(self.cli(*self.compare_args(refs))) + schema = json.loads((REPO / "schemas/task_packet.schema.json").read_text(encoding="utf-8")) + jsonschema.Draft202012Validator(schema).validate(compared["task_packet"]) + rows = {p["point_id"]: p for p in compared["comparison"]["points"]} + self.assertEqual({"P1", "P2", "P3"}, set(rows)) + self.assertEqual(Decimal("2.5"), Decimal(rows["P1"]["delta"])) + self.assertEqual(Decimal("1"), Decimal(rows["P2"]["delta"])) + self.assertIsNone(rows["P3"]["delta"]) + self.assertEqual("INSUFFICIENT", rows["P3"]["status"]) + self.assertEqual(2, rows["P1"]["baseline"]["rows"][0]["start_line"]) + self.assertEqual(3, rows["P1"]["candidate"]["rows"][0]["start_line"]) + self.assertEqual(hashes, [hashlib.sha256(p.read_bytes()).hexdigest() for p in self.paths]) + before = self.records() + for path in self.paths: + path.unlink() + progress = json.loads(self.cli("result-progress", "--task-id", "compare")) + self.assertEqual("compare", progress["task_packet"]["task_id"]) + report = self.cli("result-report", "--task-id", "compare") + for digest in hashes: + self.assertIn(digest, report) + self.assertIn("P3", report) + self.assertTrue(json.loads(self.cli(*self.compare_args(refs)))["replayed"]) + self.cli("result-report", "--task-id", "compare", "--output", "reports/results.md") + self.cli("result-report", "--task-id", "compare", "--output", "START.md", expected=2) + self.assertEqual("# Existing project\n", (self.root / "START.md").read_text(encoding="utf-8")) + self.assertEqual(before, self.records()) + mapping = self.base / "current-paths.json" + mapping.write_text(json.dumps({refs[0]: "baseline.csv"}), encoding="utf-8") + missing = json.loads(self.cli("result-progress", "--task-id", "compare", "--source-paths-file", str(mapping))) + self.assertEqual("missing", missing["source_checks"][refs[0]]["status"]) + self.assertEqual("not_checked", missing["source_checks"][refs[1]]["status"]) + types = {r["type"] for tx in ResearchStore(self.root).list_transactions() for r in tx["records"]} + self.assertTrue(types.isdisjoint({"Run", "RunReference", "Verification"})) + items, offset = [], 0 + while True: + view = project_context(self.root, offset=offset) + items.extend(view["items"]) + offset = view["page"]["next_offset"] + if offset is None: + break + row = next(i for i in items if i["kind"] == "task" and i["id"] == "compare") + self.assertIn("result-progress", row["result_progress_argv"]) + self.assertIn("result-report", row["result_report_argv"]) + + def test_compare_rejects_concurrent_source_revision_at_atomic_commit(self): + from mining_research_kernel.result_comparison import compare_results + refs = self.import_pair() + store = ResearchStore(self.root) + original_commit = ResearchStore.commit + injected = False + + def race(selected_store, operation_id, producer, records, *args, **kwargs): + nonlocal injected + if not injected and any(r["type"] == "TaskState" and r["id"] == "race" for r in records): + injected = True + changed = store.latest_record(refs[0], "Asset") + old_revision = changed["revision"] + changed["revision"] += 1 + changed["status"] = "changed_during_commit" + original_commit(store, "concurrent-result-update", {"role": "test", "model": "race"}, + [changed], expected_revisions={refs[0]: old_revision}) + return original_commit(selected_store, operation_id, producer, records, *args, **kwargs) + + with patch.object(ResearchStore, "commit", race): + with self.assertRaisesRegex(ValueError, "revision"): + compare_results(self.root, task_id="race", question="Compare with a source race", + baseline_asset_ref=refs[0], candidate_asset_ref=refs[1], point_ids=["P1"], task_context="synthetic") + self.assertTrue(injected) + self.assertIsNone(store.latest_record("race", "TaskState")) + + def test_import_can_replay_after_commit_response_is_lost(self): + from mining_research_kernel.result_comparison import import_result_csv + original_commit = ResearchStore.commit + interrupted = False + + def interrupted_commit(store, operation_id, producer, records, *args, **kwargs): + nonlocal interrupted + result = original_commit(store, operation_id, producer, records, *args, **kwargs) + if not interrupted and any(r["type"] == "TaskState" and r["id"] == "lost-response" + and r.get("state") == "completed" for r in records): + interrupted = True + raise OSError("simulated response loss after commit") + return result + + params = dict(task_id="lost-response", question="Read selected export", csv_path="baseline.csv", + metadata=self.metadata("baseline"), task_context="synthetic") + with patch.object(ResearchStore, "commit", interrupted_commit): + with self.assertRaises(OSError): + import_result_csv(self.root, **params) + self.assertTrue(interrupted) + self.paths[0].unlink() + before = self.records() + with patch("mining_research_kernel.result_comparison.read_result_csv", side_effect=AssertionError("no fresh source read")): + replay = import_result_csv(self.root, **params) + self.assertTrue(replay["replayed"]) + self.assertEqual(before, self.records()) + + def test_offline_demo_links_saved_script_and_documentation_context(self): + root = self.base / "independent result demo" + args = [sys.executable, "-S", "-B", "-X", "utf8", str(REPO / "examples/result_comparison/demo.py"), str(root)] + result = subprocess.run(args, cwd=self.base, capture_output=True, text=True, encoding="utf-8") + self.assertEqual(0, result.returncode, result.stdout + result.stderr) + receipt = json.loads(result.stdout) + self.assertTrue(receipt["source_unchanged"]) + self.assertTrue(receipt["fresh_process_recovery"]) + report = (root / receipt["report"]).read_text(encoding="utf-8") + self.assertIn("synthetic-script-review-01", report) + self.assertIn("synthetic-assignment-reading", report) + self.assertIn("script-review-teaching.html", report) + self.assertIn("assign-elastic", report) + self.assertIn("9.6.44", report) + before = {p.relative_to(root).as_posix(): p.read_bytes() for p in root.rglob("*") if p.is_file()} + repeated = subprocess.run(args, cwd=self.base, capture_output=True, text=True, encoding="utf-8") + self.assertEqual(2, repeated.returncode) + self.assertEqual(before, {p.relative_to(root).as_posix(): p.read_bytes() for p in root.rglob("*") if p.is_file()}) + + def test_historical_comparison_keeps_source_versions_after_valid_capture_revision(self): + refs = self.import_pair() + original = json.loads(self.cli(*self.compare_args(refs))) + report_before = self.cli("result-report", "--task-id", "compare") + store = ResearchStore(self.root) + asset = store.latest_record(refs[0], "Asset") + evidence = store.latest_record(asset["payload"]["evidence_id"], "Evidence") + edge = next(rel for tx in store.list_transactions() for rel in tx["relationships"] + if rel["relation"] == "evidence_derived_from_asset" and rel["from_id"] == evidence["id"]) + asset["revision"] += 1 + asset["payload"]["metadata"]["unit"] = "m" + asset["content_sha256"] = hashlib.sha256(json.dumps(asset["payload"], ensure_ascii=False, sort_keys=True, + separators=(",", ":"), allow_nan=False).encode("utf-8")).hexdigest() + evidence["revision"] += 1 + edge["revision"] += 1 + edge["from_revision"], edge["to_revision"] = evidence["revision"], asset["revision"] + store.commit("source-metadata-revision", {"role": "test", "model": "fixture"}, [asset, evidence], [edge]) + self.assertEqual(report_before, self.cli("result-report", "--task-id", "compare")) + replay = json.loads(self.cli(*self.compare_args(refs))) + self.assertTrue(replay["replayed"]) + self.assertEqual(original["comparison"], replay["comparison"]) + changed = json.loads(self.cli(*self.compare_args(refs, task="compare-revised"))) + self.assertEqual("INSUFFICIENT", changed["comparison"]["status"]) + self.assertTrue(all(p["delta"] is None for p in changed["comparison"]["points"])) + + def test_production_comparison_rejects_synthetic_related_context(self): + from mining_research_kernel.result_comparison import import_result_csv, compare_results + self.import_pair() + refs = [] + for name in ("baseline", "candidate"): + capture = import_result_csv(self.root, task_id=f"provided-{name}", question="Read provided test fixture", + csv_path=f"{name}.csv", metadata={**self.metadata(name), "origin": "provided_export"}) + refs.append(capture["asset_refs"][0]) + before = self.records() + with self.assertRaisesRegex(ValueError, "synthetic related tasks"): + compare_results(self.root, task_id="bad-context", question="Reject synthetic background in production", + baseline_asset_ref=refs[0], candidate_asset_ref=refs[1], point_ids=["P1"], + related_task_ids=["import-baseline"]) + self.assertEqual(before, self.records()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_result_csv.py b/tests/test_result_csv.py new file mode 100644 index 0000000..faf0006 --- /dev/null +++ b/tests/test_result_csv.py @@ -0,0 +1,181 @@ +from __future__ import annotations + +import hashlib +import tempfile +import unittest +from decimal import Decimal, localcontext +from pathlib import Path + +from mining_research_kernel.result_csv import ( + MAX_FILE_BYTES, + MAX_ROWS, + difference, + read_result_csv, +) + + +class ResultCsvTests(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + + def tearDown(self) -> None: + self.temp.cleanup() + + def write(self, name: str, data: bytes) -> Path: + path = self.root / name + path.write_bytes(data) + return path + + def test_bom_crlf_chinese_reordered_columns_hash_and_read_only(self) -> None: + content = "\ufeffvalue,point_id\r\n0.30,测点一\r\n".encode("utf-8") + path = self.write("result.csv", content) + + result = read_result_csv(path) + + self.assertEqual(result["columns"], ["value", "point_id"]) + self.assertEqual(result["rows"][0]["point_id"], "测点一") + self.assertEqual(result["rows"][0]["value_text"], "0.30") + self.assertEqual(result["rows"][0]["value"], "0.30") + self.assertEqual(result["sha256"], hashlib.sha256(content).hexdigest()) + self.assertEqual(path.read_bytes(), content) + self.assertEqual(result["encoding"], "utf-8-sig") + + def test_physical_line_numbers_for_multiline_csv_record(self) -> None: + path = self.write( + "lines.csv", + b'point_id,value\r\np1,"1\r\n2"\r\np2,3\r\n', + ) + + result = read_result_csv(path) + + self.assertEqual( + [(row["start_line"], row["end_line"]) for row in result["rows"]], + [(2, 3), (4, 4)], + ) + self.assertEqual(result["rows"][0]["status"], "INVALID") + self.assertEqual(result["rows"][1]["status"], "VALID") + + def test_missing_invalid_nonfinite_and_duplicate_rows_are_retained(self) -> None: + path = self.write( + "quality.csv", + b"point_id,value\na,\nb,NaN\nc,Infinity\nd,not-a-number\nx,1\nx,2\n", + ) + + result = read_result_csv(path) + + self.assertEqual( + [row["status"] for row in result["rows"]], + ["MISSING", "INVALID", "INVALID", "INVALID", "DUPLICATE", "DUPLICATE"], + ) + self.assertEqual(result["rows"][4]["value_text"], "1") + self.assertEqual(result["rows"][5]["value_text"], "2") + duplicate = next(item for item in result["diagnostics"] if item["code"] == "duplicate_point_id") + self.assertEqual(duplicate["row_indexes"], [4, 5]) + + def test_invalid_point_id_is_a_data_quality_diagnostic(self) -> None: + path = self.write("ids.csv", "point_id,value\n bad ,2\n".encode()) + + row = read_result_csv(path)["rows"][0] + + self.assertEqual(row["point_id"], " bad ") + self.assertEqual(row["status"], "INVALID") + + def test_structural_csv_errors_raise_value_error(self) -> None: + malformed_inputs = ( + b"point_id,value,extra\np,1,x\n", + b"point_id,point_id\np,1\n", + b"point_id,value\np,1,extra\n", + b'point_id,value\np,"unterminated\n', + b"point_id,value\n", + b"point_id,value\np,1\n\n", + ) + for content in malformed_inputs: + with self.subTest(content=content): + with self.assertRaises(ValueError): + read_result_csv(self.write("bad.csv", content)) + + def test_cell_and_file_byte_limits(self) -> None: + long_cell = "x" * 513 + path = self.write("cell.csv", f"point_id,value\np,{long_cell}\n".encode()) + with self.assertRaises(ValueError): + read_result_csv(path) + + path = self.write("large.csv", b"point_id,value\np,1\n" + b" " * MAX_FILE_BYTES) + with self.assertRaises(ValueError): + read_result_csv(path) + + def test_row_limit_and_maximum_row_count(self) -> None: + accepted = "point_id,value\n" + "".join(f"p{i},1\n" for i in range(MAX_ROWS)) + result = read_result_csv(self.write("max-rows.csv", accepted.encode())) + self.assertEqual(result["row_count"], MAX_ROWS) + + rejected = accepted + f"p{MAX_ROWS},1\n" + with self.assertRaises(ValueError): + read_result_csv(self.write("too-many-rows.csv", rejected.encode())) + + def test_numeric_token_precision_and_exponent_bounds(self) -> None: + accepted_100_digits = "9" * 100 + content = ( + "point_id,value\n" + f"a,{accepted_100_digits}\n" + "b,1e100\n" + "c,1e-100\n" + f"d,{'9' * 101}\n" + "e,1e101\n" + "f,1e-101\n" + f"g,{'1' * 129}\n" + "h,0e999999999\n" + ) + + rows = read_result_csv(self.write("numeric-bounds.csv", content.encode()))["rows"] + + self.assertEqual([row["status"] for row in rows[:3]], ["VALID"] * 3) + self.assertEqual([row["status"] for row in rows[3:]], ["INVALID"] * 5) + + def test_explicit_encoding_and_decode_failures(self) -> None: + path = self.write("latin.csv", "point_id,value\ncafé,1\n".encode("cp1252")) + self.assertEqual(read_result_csv(path, encoding="cp1252")["rows"][0]["point_id"], "café") + with self.assertRaises(ValueError): + read_result_csv(path) + with self.assertRaises(ValueError): + read_result_csv(path, encoding="unknown-encoding") + + directory = self.root / "directory" + directory.mkdir() + with self.assertRaises(ValueError): + read_result_csv(directory) + + def test_difference_is_exact_for_decimal_and_long_coefficients(self) -> None: + self.assertEqual(difference("0.3", "0.1"), "0.2") + self.assertEqual( + difference("123456789012345678901234567890.1", "0.1"), + "123456789012345678901234567890.0", + ) + + def test_difference_uses_precision_for_full_allowed_exponent_span(self) -> None: + low_coefficient = "1234567890" * 10 + low_value = f"{low_coefficient[0]}.{low_coefficient[1:]}e-100" + + actual = difference("1e100", low_value) + + with localcontext() as context: + context.prec = 512 + expected = Decimal("1e100") - Decimal(low_value) + self.assertEqual(Decimal(actual), expected) + self.assertNotEqual(Decimal(actual), Decimal("1e100")) + + def test_difference_can_exceed_input_adjusted_exponent_range(self) -> None: + self.assertEqual(difference("9e100", "-9e100"), "1.8E+101") + + def test_difference_rejects_extreme_zero_quantum_and_invalid_numbers(self) -> None: + with self.assertRaises(ValueError): + difference("0e999999999", "1") + with self.assertRaises(ValueError): + difference("1", "Infinity") + with self.assertRaises(ValueError): + difference("1e101", "1") + + +if __name__ == "__main__": + unittest.main()