日志批量导出教学材料 / 第一阶段

全部背景与源码为虚构教学项目，不是公司资料或真实网络服务。
来源：维护者于 2026-10-28 在 Python 3.13.14 本机执行探针；下面的结果不代表阅读者已经在本机执行。
源码中的列表和接收端只模拟输出，未验证真实网络或持久化。

===== materials/v1/batchpub_after.py =====
SHA-256: 31a38f06f439318cec9450ec58eb990a81abed2f0d84b3edae233019efbca3ac

"""Fictional BatchPub protocol fixture; unrelated to any real product."""


def flush(pending, published, closed=False):
    for item in pending:
        published.append(item)
    pending.clear()

===== materials/v1/batchpub_before.py =====
SHA-256: 517567bc6059fe03fc7326759b33b4fd9d67b2d474ea2ffe639eea7998460c89

"""Fictional BatchPub protocol fixture; unrelated to any real product."""


def flush(pending, published, closed=False):
    if closed:
        return
    for item in pending:
        published.append(item)
    pending.clear()

===== materials/v1/observations.json =====
SHA-256: 27cd67e5ccd63eaa908164b95fc9d3e2a12eed23e66134252f81e2d6999984a9

{
  "scope": "Executed locally against fictional Python fixtures; no devices or real product source.",
  "files": {
    "batchpub_after.py": "31a38f06f439318cec9450ec58eb990a81abed2f0d84b3edae233019efbca3ac",
    "batchpub_before.py": "517567bc6059fe03fc7326759b33b4fd9d67b2d474ea2ffe639eea7998460c89",
    "probe_batchpub.py": "b74424e01766f3537b9bc5ae9c6de8017f9d8449b60ff28ec73b7145eb58a66e"
  },
  "before": [
    {
      "case": "normal_flush",
      "pending": [],
      "published": [
        "A",
        "B"
      ],
      "passed": true
    },
    {
      "case": "close_drain",
      "pending": [
        "A",
        "B"
      ],
      "published": [],
      "passed": false
    },
    {
      "case": "repeat_close_flush",
      "pending": [
        "A",
        "B"
      ],
      "published": [],
      "passed": false
    }
  ],
  "after": [
    {
      "case": "normal_flush",
      "pending": [],
      "published": [
        "A",
        "B"
      ],
      "passed": true
    },
    {
      "case": "close_drain",
      "pending": [],
      "published": [
        "A",
        "B"
      ],
      "passed": true
    },
    {
      "case": "repeat_close_flush",
      "pending": [],
      "published": [
        "A",
        "B"
      ],
      "passed": true
    }
  ],
  "after_failure_probe": {
    "case": "partial_publish_then_retry",
    "after_failure": {
      "pending": [
        "A",
        "B"
      ],
      "published": [
        "A"
      ],
      "exception": "simulated sink rejection on B"
    },
    "after_retry": {
      "pending": [],
      "published": [
        "A",
        "A",
        "B"
      ]
    },
    "duplicate_free": false
  }
}

===== materials/v1/probe_batchpub.py =====
SHA-256: b74424e01766f3537b9bc5ae9c6de8017f9d8449b60ff28ec73b7145eb58a66e

"""Capture real observations from two tiny, explicitly fictional source fixtures."""

import hashlib
import importlib.util
import json
from pathlib import Path


ROOT = Path(__file__).parent


def load(name):
    path = ROOT / f"batchpub_{name}.py"
    spec = importlib.util.spec_from_file_location(name, path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def normal_cases(module):
    results = []
    for closed in (False, True):
        pending, published = ["A", "B"], []
        module.flush(pending, published, closed=closed)
        results.append({
            "case": "close_drain" if closed else "normal_flush",
            "pending": list(pending),
            "published": list(published),
            "passed": pending == [] and published == ["A", "B"],
        })
    pending, published = ["A", "B"], []
    module.flush(pending, published, closed=True)
    module.flush(pending, published, closed=True)
    results.append({
        "case": "repeat_close_flush",
        "pending": list(pending),
        "published": list(published),
        "passed": pending == [] and published == ["A", "B"],
    })
    return results


class FailOnceOnB(list):
    def __init__(self):
        super().__init__()
        self.failed = False

    def append(self, value):
        if value == "B" and not self.failed:
            self.failed = True
            raise RuntimeError("simulated sink rejection on B")
        super().append(value)


def failure_probe(module):
    pending, published = ["A", "B"], FailOnceOnB()
    caught = None
    try:
        module.flush(pending, published, closed=True)
    except RuntimeError as error:
        caught = str(error)
    after_failure = {"pending": list(pending), "published": list(published), "exception": caught}
    module.flush(pending, published, closed=True)
    return {
        "case": "partial_publish_then_retry",
        "after_failure": after_failure,
        "after_retry": {"pending": list(pending), "published": list(published)},
        "duplicate_free": list(published) == ["A", "B"],
    }


if __name__ == "__main__":
    before, after = load("before"), load("after")
    print(json.dumps({
        "scope": "Executed locally against fictional Python fixtures; no devices or real product source.",
        "files": {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(ROOT.glob("*.py"))},
        "before": normal_cases(before),
        "after": normal_cases(after),
        "after_failure_probe": failure_probe(after),
    }, indent=2, ensure_ascii=False))

