diff --git a/docs/testing/2026-10-31-dsh-pr11-decision-log.md b/docs/testing/2026-10-31-dsh-pr11-decision-log.md new file mode 100644 index 0000000..c969eec --- /dev/null +++ b/docs/testing/2026-10-31-dsh-pr11-decision-log.md @@ -0,0 +1,19 @@ +# PR #11 决策日志审查修复 + +对应审查:[评论 #103](https://git.simgreek.com/Skyworth_Digital_Hardware/dxdesigner-part-replacement/pulls/11#issuecomment-103)。 + +原实现将界面列表的 2,000 条上限用于追加和校验,造成第 2,001 条之后重复序号、前链错误及漏检。本次将完整原始日志的流式校验与界面展示分离,追加依据实际尾记录分配连续序号和前链哈希,默认校验覆盖文件末尾。只有调用方明确提供 `sequence` 时才校验指定前缀。 + +校验同时检查连续序号、事件编号、前链哈希和记录哈希,不跳过损坏 JSON、非记录行或残缺尾行。损坏时拒绝追加并保留原字节;兼容原有 JSONL 和完整 JSON 尾行缺少换行的情况。同一进程内的日志实例串行访问,追加执行 flush 与 fsync 后返回。跨进程写入的协调仍沿用现有应用执行所有权,本次未新增多进程写入协议。 + +界面只保留最近 N 条记录,最多 2,000 条;该显示上限不限制追加或完整校验。修复不删除或重写历史记录,也不自动修复已经损坏的审计链。 + +验证结果: + +- 新增回归先在旧实现复现失败:9 failed,2 passed。 +- 决策日志、自动诊断和监管页定向测试:37 passed。 +- DSH、UI、任务队列和打包相关回归:222 passed。 +- 独立复核未发现本次修复的新阻断问题。 +- Python 语法检查、`git diff --check` 通过。 + +回归覆盖 2,001 条合法历史记录后的追加与重启校验、2,000 条之后的篡改、有效哈希下的重复序号、损坏尾行、最新记录有界展示、尾行缺少换行及同一进程多实例并发追加。 diff --git a/src/dx_productivity/dsh/decision_log.py b/src/dx_productivity/dsh/decision_log.py index d647352..cddcecc 100644 --- a/src/dx_productivity/dsh/decision_log.py +++ b/src/dx_productivity/dsh/decision_log.py @@ -1,16 +1,20 @@ """Append-only, hash-linked records for automatic DSH decisions.""" from __future__ import annotations +from collections import deque from datetime import datetime, timezone from hashlib import sha256 import json +import os from pathlib import Path import re +from threading import RLock from .evidence import scrub _ID = re.compile(r"^[0-9a-f]{24}$") -_MAX = 2000 +_MAX = 2000 # Presentation limit only; never limits append or verification. +_LOCK = RLock() def _bounded(value, limit=1000): @@ -24,6 +28,18 @@ def _bounded(value, limit=1000): return value +def _record_hash(value): + body = {key: item for key, item in value.items() if key != 'record_hash'} + payload = json.dumps(body, ensure_ascii=False, sort_keys=True, separators=(',', ':')) + return sha256(payload.encode('utf8')).hexdigest() + + +class _CorruptLog(ValueError): + def __init__(self, code, checked): + super().__init__('decision_log_corrupt: ' + code) + self.code, self.checked = code, checked + + class DecisionLog: def __init__(self, data_root): self.path = Path(data_root) / "dsh" / "decisions.jsonl" @@ -31,9 +47,27 @@ class DecisionLog: def append(self, record): if not isinstance(record, dict) or not _ID.fullmatch(str(record.get("incident_id", ""))): raise ValueError("incident_id") - rows = self.list(limit=_MAX) - previous = rows[-1]["record_hash"] if rows else "" - value = {"sequence": len(rows) + 1, "at_utc": datetime.now(timezone.utc).isoformat(), + # Validate the original bytes all the way to EOF. Display truncation or + # redaction must never choose the next sequence or change hashed input. + with _LOCK: + sequence, previous = 0, '' + for row in self._records(): + sequence, previous = row['sequence'], row['record_hash'] + value = self._new_record(record, sequence + 1, previous) + self.path.parent.mkdir(parents=True, exist_ok=True) + with self.path.open('a+b') as stream: + if stream.tell(): + stream.seek(-1, os.SEEK_END) + if stream.read(1) != b'\n': + stream.write(b'\n') + stream.write((json.dumps(value, ensure_ascii=False, sort_keys=True) + '\n').encode('utf8')) + stream.flush() + os.fsync(stream.fileno()) + return value + + @staticmethod + def _new_record(record, sequence, previous): + value = {"sequence": sequence, "at_utc": datetime.now(timezone.utc).isoformat(), "previous_hash": previous, "incident_id": record["incident_id"], "trigger": _bounded(record.get("trigger", ""), 160), "evidence_refs": _bounded(record.get("evidence_refs", []), 300), @@ -42,44 +76,52 @@ class DecisionLog: "authorized_scope": _bounded(record.get("authorized_scope", {}), 600), "outcome": _bounded(record.get("outcome", "unknown"), 160), "human_takeover": bool(record.get("human_takeover", False))} - payload = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) - value["record_hash"] = sha256(payload.encode("utf8")).hexdigest() - self.path.parent.mkdir(parents=True, exist_ok=True) - with self.path.open("a", encoding="utf8") as stream: - stream.write(json.dumps(value, ensure_ascii=False, sort_keys=True) + "\n") - stream.flush() - return dict(value) + value['record_hash'] = _record_hash(value) + return value + + def _records(self, sequence=None): + """Stream the complete raw chain, failing at the first invalid record.""" + try: + stream = self.path.open('rb') + except FileNotFoundError: + return + previous, checked = '', 0 + with stream: + while sequence is None or checked < sequence: + line = stream.readline() + if not line: + break + try: + value = json.loads(line) + except (ValueError, UnicodeError) as error: + raise _CorruptLog('invalid_json', checked) from error + if not isinstance(value, dict) or not _ID.fullmatch(str(value.get('incident_id', ''))): + raise _CorruptLog('invalid_record', checked) + if type(value.get('sequence')) is not int or value['sequence'] != checked + 1: + raise _CorruptLog('sequence_mismatch', checked) + if value.get('previous_hash') != previous or value.get('record_hash') != _record_hash(value): + raise _CorruptLog('hash_mismatch', checked) + previous, checked = value['record_hash'], checked + 1 + yield value def list(self, limit=20): - if not isinstance(limit, int) or limit <= 0: + if type(limit) is not int or limit <= 0: return [] - rows = [] - try: - with self.path.open(encoding="utf8") as stream: - for line in stream: - if len(rows) >= min(limit, _MAX): - break - try: - value = json.loads(line) - except (ValueError, TypeError): - continue - if isinstance(value, dict) and _ID.fullmatch(str(value.get("incident_id", ""))): - rows.append(_bounded(value, 2000)) - except OSError: - return [] - return rows + with _LOCK: + rows = deque(self._records(), maxlen=min(limit, _MAX)) + return [_bounded(row, 2000) for row in rows] def verify(self, sequence=None): - rows = self.list(limit=_MAX) - previous = "" - checked = 0 - for value in rows: - if sequence is not None and value.get("sequence") > sequence: - break - expected = value.get("record_hash") - body = {key: item for key, item in value.items() if key != "record_hash"} - payload = json.dumps(body, ensure_ascii=False, sort_keys=True, separators=(",", ":")) - if value.get("previous_hash") != previous or expected != sha256(payload.encode("utf8")).hexdigest(): - return {"valid": False, "checked": checked, "error": "hash_mismatch"} - previous, checked = expected, checked + 1 - return {"valid": True, "checked": checked, "last_hash": previous} + """Verify every record unless the caller explicitly requests a prefix.""" + if sequence is not None and (type(sequence) is not int or sequence < 1): + raise ValueError('decision_sequence') + with _LOCK: + previous, checked = '', 0 + try: + for value in self._records(sequence): + previous, checked = value['record_hash'], checked + 1 + except _CorruptLog as error: + return {'valid': False, 'checked': error.checked, 'error': error.code} + except OSError: + return {'valid': False, 'checked': checked, 'error': 'read_unavailable'} + return {"valid": True, "checked": checked, "last_hash": previous} diff --git a/tests/dsh/test_decision_log.py b/tests/dsh/test_decision_log.py index 1428d00..298db46 100644 --- a/tests/dsh/test_decision_log.py +++ b/tests/dsh/test_decision_log.py @@ -1,4 +1,6 @@ import json +from concurrent.futures import ThreadPoolExecutor +from hashlib import sha256 import pytest @@ -31,3 +33,98 @@ def test_decision_log_detects_tampering_and_bounds_text(tmp_path): assert DecisionLog(tmp_path).verify()['valid'] is False with pytest.raises(ValueError, match='incident_id'): store.append(_row('bad')) + + +def _seal(record): + body = {key: value for key, value in record.items() if key != 'record_hash'} + payload = json.dumps(body, ensure_ascii=False, sort_keys=True, separators=(',', ':')) + return body | {'record_hash': sha256(payload.encode('utf8')).hexdigest()} + + +@pytest.fixture +def long_log(tmp_path): + # Seed a valid historical log without thousands of quadratic append calls. + path = tmp_path / 'dsh' / 'decisions.jsonl' + path.parent.mkdir() + previous = '' + with path.open('w', encoding='utf8') as stream: + for sequence in range(1, 2002): + last = _seal(_row() | {'sequence': sequence, 'at_utc': '2026-10-31T00:00:00+00:00', + 'previous_hash': previous}) + stream.write(json.dumps(last) + '\n') + previous = last['record_hash'] + return DecisionLog(tmp_path), last + + +def test_append_after_2000_records_uses_actual_tail_and_verifies_entire_chain(long_log): + store, previous = long_log + result = store.append(_row('b' * 24)) + assert result['sequence'] == 2002 + assert result['previous_hash'] == previous['record_hash'] + reopened = DecisionLog(store.path.parent.parent) + assert reopened.verify() == {'valid': True, 'checked': 2002, 'last_hash': result['record_hash']} + + +def test_verify_detects_tampering_past_2000_records(long_log): + store, last = long_log + lines = store.path.read_text(encoding='utf8').splitlines() + lines[-1] = json.dumps(last | {'outcome': 'resolved'}) + store.path.write_text('\n'.join(lines) + '\n', encoding='utf8') + assert store.verify(sequence=2000)['valid'] is True + result = store.verify() + assert result['valid'] is False and result['checked'] == 2000 + before = store.path.read_bytes() + with pytest.raises(ValueError, match='decision_log_corrupt'): + store.append(_row('b' * 24)) + assert store.path.read_bytes() == before + + +def test_verify_rejects_duplicate_sequence_even_with_valid_hash_links(long_log): + store, last = long_log + duplicate = _seal(last | {'previous_hash': last['record_hash']}) + with store.path.open('a', encoding='utf8') as stream: + stream.write(json.dumps(duplicate) + '\n') + result = store.verify() + assert result['valid'] is False and result['checked'] == 2001 + + +@pytest.mark.parametrize('tail', ['{incomplete', '{"incident_id":', '[]\n', '\n']) +def test_corrupt_tail_is_reported_and_append_preserves_original_bytes(tmp_path, tail): + store = DecisionLog(tmp_path) + store.append(_row()) + with store.path.open('a', encoding='utf8') as stream: + stream.write(tail) + before = store.path.read_bytes() + assert store.verify()['valid'] is False + with pytest.raises(ValueError, match='decision_log_corrupt'): + store.list() + with pytest.raises(ValueError, match='decision_log_corrupt'): + store.append(_row('b' * 24)) + assert store.path.read_bytes() == before + + +def test_listing_remains_bounded_and_shows_recent_records(long_log): + store, _ = long_log + assert [row['sequence'] for row in store.list(limit=3)] == [1999, 2000, 2001] + assert len(store.list(limit=100000)) == 2000 + + +def test_append_after_complete_json_without_newline_keeps_records_separate(tmp_path): + store = DecisionLog(tmp_path) + first = store.append(_row()) + store.path.write_bytes(store.path.read_bytes().rstrip(b'\r\n')) + second = store.append(_row('b' * 24)) + assert len(store.path.read_text(encoding='utf8').splitlines()) == 2 + assert second['previous_hash'] == first['record_hash'] + assert store.verify()['checked'] == 2 and store.verify()['valid'] is True + + +def test_concurrent_instances_append_one_ordered_chain(tmp_path): + def append(index): + return DecisionLog(tmp_path).append(_row(f'{index:024x}')) + + with ThreadPoolExecutor(max_workers=4) as pool: + results = list(pool.map(append, range(20))) + assert sorted(row['sequence'] for row in results) == list(range(1, 21)) + assert DecisionLog(tmp_path).verify()['valid'] is True + assert DecisionLog(tmp_path).verify()['checked'] == 20