Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

fix(diagnostics): 保留有界 JSON 状态与完整问题记录

longmeidaode7aa129755e
diff --git a/docs/DIAGNOSTICS.md b/docs/DIAGNOSTICS.md
index 0f574a733..b75761148 100644
--- a/docs/DIAGNOSTICS.md
+++ b/docs/DIAGNOSTICS.md
@@ -10,6 +10,19 @@
错误发生时必须实际记录底层证据。完整问题清单位于 `state/library-processing-<job_id>.issues.jsonl`。通用问题清单不能还原被丢弃的 FFmpeg 错误;没有原始记录的历史失败需要重试取证。
+诊断 ZIP 对 JSON 状态文件最多读取完整的 16 MiB,解析后按字段脱敏。每个状态文件的导出内容最多 96 KiB;需要缩减时,先保留任务标识、状态、阶段和计数,再纳入步骤、问题预览与其他字段。缩减后的集合最多保留前 20 项,文本最多保留 4000 字符,嵌套最多 8 层;字段放不下时继续减少集合项数。JSONL 问题清单读取尾部 96 KiB,只导出可完整解析的近期记录;截断的首条记录、损坏记录和超出脱敏后大小上限的记录不导出。媒体名称、路径及凭据沿用字段脱敏。
+
+`report.json` 的 `logs` 清单记录各文件的 `source_bytes`、`exported_bytes`、`status` 与 `truncated`。JSON 字段缩减会标记 `projected`,并记录未纳入的顶层字段数 `omitted_fields`、前 64 个顶层字段中集合的原始数量 `collection_counts`;顶层数组使用 `collection_count`。JSONL 使用 `skipped_records` 记录读取范围内未导出的记录数,截断的首条记录不计入该数。空 JSON、损坏 JSON、超出读取上限、无有效记录等情况只记录清单状态,不生成空文件。
+
+| 清单状态 | 含义 |
+| --- | --- |
+| `included` | 已导出有效内容;是否缩减另见 `truncated` 和 `projected` |
+| `empty_json` / `empty_jsonl` | JSON 为空白内容,或 JSONL 为零字节 |
+| `unreadable_json` / `invalid_json_shape` | JSON 无法解析,或顶层不是对象、数组 |
+| `json_size_limit` / `json_depth_limit` | JSON 超出完整读取上限,或解析、脱敏时嵌套过深 |
+| `json_projection_limit` | JSON 字段缩减后仍无法在大小上限内保留有效内容 |
+| `no_complete_records` | JSONL 读取范围内没有可导出的完整记录 |
+
## 证据链
| 链路 | 持久证据与核验 |
diff --git a/src/peach/support_bundle.py b/src/peach/support_bundle.py
index 01c5bbd9b..a19cad5ca 100644
--- a/src/peach/support_bundle.py
+++ b/src/peach/support_bundle.py
@@ -7,6 +7,7 @@ import json
import os
import zipfile
from datetime import datetime, timezone
+from itertools import islice
from pathlib import Path
from . import error_reporting
@@ -20,9 +21,10 @@ STATE_NAMES = ('library-processing.json', 'runtime-prepare.json', 'standalone-up
#: 发现页封面逐番号处理结果的份数上限;每份只有几十字节,排查缺封面靠它们。
COVER_ATTEMPT_LIMIT = 500
TAIL_BYTES = 96 * 1024
+JSON_READ_BYTES = 16 * 1024 * 1024
-def _processing_log(text: str) -> str:
+def _processing_value(value):
"""处理证据保留资产编号和错误,媒体名称与路径留在本机。"""
def hide_names(value):
if isinstance(value, dict):
@@ -34,18 +36,100 @@ def _processing_log(text: str) -> str:
return [hide_names(item) for item in value]
return value
+ return error_reporting.scrub(hide_names(value))
+
+
+def _json_text(value):
+ return json.dumps(value, ensure_ascii=False) + '\n'
+
+
+def _limited_value(value, depth=0, limit=20):
+ """集合保留前 20 项、文本保留 4000 字符,嵌套最多 8 层。"""
+ if isinstance(value, (dict, list)) and depth >= 8:
+ return '<depth-limit>'
+ if isinstance(value, dict):
+ return {key: _limited_value(item, depth + 1, limit) for key, item in islice(value.items(), limit)}
+ if isinstance(value, list):
+ return [_limited_value(item, depth + 1, limit) for item in value[:limit]]
+ return value[:4000] if isinstance(value, str) else value
+
+
+def _structured_json(stream):
+ raw = stream.read(JSON_READ_BYTES + 1)
+ if len(raw) > JSON_READ_BYTES:
+ return '', {'status': 'json_size_limit', 'truncated': True}
+ if not raw.strip():
+ return '', {'status': 'empty_json', 'truncated': False}
try:
- values = [json.loads(text)]
- except ValueError:
- values = []
- for line in text.splitlines():
- try:
- values.append(json.loads(line))
- except ValueError:
- continue
- lines = [json.dumps(error_reporting.scrub(hide_names(value)), ensure_ascii=False)
- for value in values if isinstance(value, (dict, list))]
- return '\n'.join(lines) + ('\n' if lines else '')
+ value = json.loads(raw)
+ if not isinstance(value, (dict, list)):
+ return '', {'status': 'invalid_json_shape', 'truncated': False}
+ value = _processing_value(value)
+ content = _json_text(value)
+ if len(content.encode('utf-8')) <= TAIL_BYTES:
+ return content, {'status': 'included', 'truncated': False, 'projected': False}
+ if isinstance(value, dict):
+ # 任务标识、状态、阶段、计数先于续跑索引;问题与步骤先于其他集合。
+ primary = ('job_id', 'run_id', 'status', 'stage', 'requested_stage', 'checked', 'total',
+ 'issue_count', 'current_action', 'error', 'started_at', 'last_progress_at', 'completed_at')
+ fields = sorted(value, key=lambda key: (key not in primary,
+ isinstance(value[key], (dict, list)), key not in ('steps', 'issue_preview', 'notes')))
+ projected, omitted = {}, 0
+ for key in fields:
+ for limit in (20, 10, 5, 1):
+ candidate = {**projected, key: _limited_value(value[key], limit=limit)}
+ if len(_json_text(candidate).encode('utf-8')) <= TAIL_BYTES:
+ projected = candidate
+ break
+ else:
+ omitted += 1
+ else:
+ projected, omitted = _limited_value(value), 0
+ content = _json_text(projected)
+ if len(content.encode('utf-8')) > TAIL_BYTES or not projected:
+ return '', {'status': 'json_projection_limit', 'truncated': True}
+ details = {'status': 'included', 'truncated': True, 'projected': True, 'omitted_fields': omitted}
+ if isinstance(value, dict):
+ details['collection_counts'] = {key: len(item) for key, item in islice(value.items(), 64)
+ if isinstance(item, (dict, list))}
+ else:
+ details['collection_count'] = len(value)
+ return content, details
+ except (ValueError, UnicodeDecodeError):
+ return '', {'status': 'unreadable_json', 'truncated': False}
+ except RecursionError:
+ return '', {'status': 'json_depth_limit', 'truncated': False}
+
+
+def _structured_jsonl(stream, size):
+ start = max(0, size - TAIL_BYTES)
+ stream.seek(max(0, start - 1))
+ raw = stream.read(TAIL_BYTES + (1 if start else 0))
+ if start:
+ boundary, raw = raw[:1], raw[1:]
+ if boundary != b'\n':
+ raw = raw.partition(b'\n')[2]
+ lines, skipped, output_bytes = [], 0, 0
+ for line in reversed(raw.splitlines()):
+ if not line.strip():
+ continue
+ try:
+ value = json.loads(line)
+ if not isinstance(value, (dict, list)):
+ raise ValueError('invalid record shape')
+ content = _json_text(_processing_value(value))
+ except (ValueError, UnicodeDecodeError, RecursionError):
+ skipped += 1
+ continue
+ length = len(content.encode('utf-8'))
+ if output_bytes + length > TAIL_BYTES:
+ skipped += 1
+ continue
+ lines.append(content)
+ output_bytes += length
+ return ''.join(reversed(lines)), {
+ 'status': 'included' if lines else 'no_complete_records' if size else 'empty_jsonl',
+ 'truncated': bool(start or skipped), 'skipped_records': skipped}
def redact_log(text: str) -> str:
@@ -88,16 +172,23 @@ def _archive_files(archive, directory, candidates, prefix, entries, *, structure
continue
with path.open('rb') as stream:
size = stream.seek(0, os.SEEK_END)
- stream.seek(max(0, size - TAIL_BYTES))
- raw = stream.read(TAIL_BYTES)
- text = raw.decode('utf-8', errors='replace')
- if size > TAIL_BYTES:
- text = text.partition('\n')[2]
- content = _processing_log(text) if structured else redact_log(text)
+ if structured:
+ stream.seek(0)
+ content, details = (_structured_jsonl(stream, size) if path.suffix == '.jsonl'
+ else _structured_json(stream))
+ else:
+ stream.seek(max(0, size - TAIL_BYTES))
+ raw = stream.read(TAIL_BYTES)
+ text = raw.decode('utf-8', errors='replace')
+ if size > TAIL_BYTES:
+ text = text.partition('\n')[2]
+ content = redact_log(text)
+ details = {'status': 'included', 'truncated': size > TAIL_BYTES}
name = path.relative_to(directory).as_posix()
- archive.writestr(f'{prefix}/{name}', content)
- entries.append({'name': name, 'section': prefix, 'truncated': size > TAIL_BYTES,
- 'status': 'included' if content or not raw else 'unreadable_json'})
+ if not structured or content:
+ archive.writestr(f'{prefix}/{name}', content)
+ entries.append({'name': name, 'section': prefix, 'source_bytes': size,
+ 'exported_bytes': len(content.encode('utf-8')), **details})
except OSError as error:
entries.append({'name': path.name, 'status': type(error).__name__})
diff --git a/tests/test_error_reporting.py b/tests/test_error_reporting.py
index e77c97504..82084474b 100644
--- a/tests/test_error_reporting.py
+++ b/tests/test_error_reporting.py
@@ -103,6 +103,112 @@ class ErrorReportingTests(unittest.TestCase):
self.assertTrue(all(json.loads(line)['asset_id'] == 23 for line in text.splitlines()))
self.assertTrue(next(row for row in report['logs'] if row['name'] == path.name)['truncated'])
+ def test_processing_export_reads_complete_large_json_and_keeps_task_evidence(self):
+ state = self.root / 'state'
+ state.mkdir()
+ path = state / 'library-processing.json'
+ payload = {'local_metadata': {str(index): r'D:\private\movie.mp4' for index in range(10000)},
+ 'job_id': 'task-23', 'status': 'running', 'stage': 'previews', 'checked': 423,
+ 'issue_count': 1, 'issue_preview': [{'asset_id': 23, 'title': 'private-movie',
+ 'diagnostics': {'reason': 'timeout', 'stderr': 'token=private-token'}}]}
+ path.write_text(json.dumps(payload, indent=2), encoding='utf-8')
+ with mock.patch.object(error_reporting, 'log_directories', return_value=[]), \
+ zipfile.ZipFile(io.BytesIO(support_bundle.bundle_bytes())) as archive:
+ content = archive.read('processing/library-processing.json')
+ exported = json.loads(content)
+ report = json.loads(archive.read('report.json'))
+ self.assertLessEqual(len(content), support_bundle.TAIL_BYTES)
+ self.assertEqual((exported['job_id'], exported['status'], exported['stage'], exported['checked']),
+ ('task-23', 'running', 'previews', 423))
+ self.assertEqual(exported['issue_preview'][0]['diagnostics']['reason'], 'timeout')
+ self.assertNotIn(b'private-', content)
+ entry = next(row for row in report['logs'] if row['name'] == path.name)
+ self.assertEqual(entry['status'], 'included')
+ self.assertTrue(entry['truncated'])
+ self.assertTrue(entry['projected'])
+ self.assertEqual(entry['collection_counts']['local_metadata'], 10000)
+ self.assertEqual(len(exported['local_metadata']), 20)
+
+ def test_processing_export_keeps_large_compact_json_without_tail_loss(self):
+ state = self.root / 'state'
+ state.mkdir()
+ (state / 'library-processing.json').write_text(json.dumps({
+ 'status': 'paused', 'local_metadata': {str(index): r'D:\private\movie.mp4'
+ for index in range(5000)}}), encoding='utf-8')
+ with mock.patch.object(error_reporting, 'log_directories', return_value=[]), \
+ zipfile.ZipFile(io.BytesIO(support_bundle.bundle_bytes())) as archive:
+ self.assertEqual(json.loads(archive.read('processing/library-processing.json'))['status'], 'paused')
+
+ def test_processing_export_reports_invalid_empty_and_over_limit_json_without_empty_members(self):
+ state = self.root / 'state'
+ state.mkdir()
+ for name, content in [('library-processing.json', '{"status":'),
+ ('runtime-prepare.json', ''), ('standalone-update.json', 'x' * 200)]:
+ (state / name).write_text(content, encoding='utf-8')
+ with mock.patch.object(error_reporting, 'log_directories', return_value=[]), \
+ mock.patch.object(support_bundle, 'JSON_READ_BYTES', 100), \
+ zipfile.ZipFile(io.BytesIO(support_bundle.bundle_bytes())) as archive:
+ report = json.loads(archive.read('report.json'))
+ entries = {row['name']: row for row in report['logs']}
+ self.assertEqual(entries['library-processing.json']['status'], 'unreadable_json')
+ self.assertEqual(entries['runtime-prepare.json']['status'], 'empty_json')
+ self.assertEqual(entries['standalone-update.json']['status'], 'json_size_limit')
+ self.assertFalse(any(name.startswith('processing/') for name in archive.namelist()))
+
+ def test_processing_jsonl_export_keeps_record_at_exact_tail_boundary(self):
+ state = self.root / 'state'
+ state.mkdir()
+ first = json.dumps({'asset_id': 1}) + '\n'
+ last = json.dumps({'asset_id': 2}) + '\n'
+ path = state / 'library-processing-boundary.issues.jsonl'
+ path.write_bytes((first + last).encode('utf-8'))
+ with mock.patch.object(error_reporting, 'log_directories', return_value=[]), \
+ mock.patch.object(support_bundle, 'TAIL_BYTES', len(last.encode())), \
+ zipfile.ZipFile(io.BytesIO(support_bundle.bundle_bytes())) as archive:
+ self.assertEqual(json.loads(archive.read('processing/' + path.name))['asset_id'], 2)
+
+ def test_processing_json_export_bounds_reads_and_rejects_scalar_or_deep_documents(self):
+ stream = io.BytesIO(b' ' * 1000)
+ with mock.patch.object(support_bundle, 'JSON_READ_BYTES', 100):
+ content, details = support_bundle._structured_json(stream)
+ self.assertEqual((content, details['status'], stream.tell()), ('', 'json_size_limit', 101))
+ for raw, expected in [(b'false', 'invalid_json_shape'), (b'{"status":"\xff"}', 'unreadable_json'),
+ (b'[' * 2000 + b']' * 2000, 'json_depth_limit')]:
+ with self.subTest(expected=expected):
+ content, details = support_bundle._structured_json(io.BytesIO(raw))
+ self.assertEqual((content, details['status']), ('', expected))
+
+ def test_processing_jsonl_export_reports_skipped_records_and_bounds_redacted_output(self):
+ state = self.root / 'state'
+ state.mkdir()
+ path = state / 'library-processing-rows.issues.jsonl'
+ rows = [json.dumps({'asset_id': index, 'token': 'x'}) for index in range(1, 4)]
+ path.write_text('\n'.join([*rows, '{"partial":']), encoding='utf-8')
+ limit = path.stat().st_size
+ with mock.patch.object(error_reporting, 'log_directories', return_value=[]), \
+ mock.patch.object(support_bundle, 'TAIL_BYTES', limit), \
+ zipfile.ZipFile(io.BytesIO(support_bundle.bundle_bytes())) as archive:
+ content = archive.read('processing/' + path.name)
+ records = [json.loads(line) for line in content.splitlines()]
+ entry = next(row for row in json.loads(archive.read('report.json'))['logs'] if row['name'] == path.name)
+ self.assertLessEqual(len(content), limit)
+ self.assertEqual([row['asset_id'] for row in records], [2, 3])
+ self.assertEqual(entry['skipped_records'], 2)
+ self.assertEqual(entry['status'], 'included')
+ self.assertTrue(entry['truncated'])
+
+ def test_processing_jsonl_export_omits_members_without_complete_records(self):
+ state = self.root / 'state'
+ state.mkdir()
+ (state / 'library-processing-empty.issues.jsonl').write_bytes(b'')
+ (state / 'library-processing-invalid.issues.jsonl').write_bytes(b'{"partial":')
+ with mock.patch.object(error_reporting, 'log_directories', return_value=[]), \
+ zipfile.ZipFile(io.BytesIO(support_bundle.bundle_bytes())) as archive:
+ entries = {row['name']: row for row in json.loads(archive.read('report.json'))['logs']}
+ self.assertFalse(any(name.startswith('processing/') for name in archive.namelist()))
+ self.assertEqual(entries['library-processing-empty.issues.jsonl']['status'], 'empty_jsonl')
+ self.assertEqual(entries['library-processing-invalid.issues.jsonl']['status'], 'no_complete_records')
+
def test_support_bundle_contains_local_delivery_receipts_without_research_payloads(self):
from peach.settings_file import PeachConfig
config = PeachConfig(self.root, self.root / 'config.toml', present=True)