蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

让失败清零、状态重开和事件去重可观察

PYTHONCPython 3.12、临时 SQLite、临时 Git 仓库和本地 MCP stdio。control_lab.py
control_lab.py147 行
"""Run a restartable evidence gate on a small local CI fixture."""
from contextlib import closing
from datetime import datetime, timezone
from hashlib import sha256
import json
from pathlib import Path
import sqlite3
from tempfile import TemporaryDirectory

CASES = []


def observe(name, inputs, operation, expected, actual):
    assert actual == expected, (name, expected, actual)
    CASES.append(dict(name=name, input=inputs, operation=operation, expected=expected, actual=actual))


def fixture_hash(file):
    return sha256(file.read_bytes()).hexdigest()


def write_report(folder, expected_source, action="write_report", destination="TODO.md"):
    if action != "write_report" or destination != "TODO.md":
        return "denied"
    source = folder / "ci.json"
    if fixture_hash(source) != expected_source:
        return "stale"
    rows = json.loads(source.read_bytes())
    failed = sorted({row["id"] for row in rows if row["status"] == "failed"})
    scratch = folder / "TODO.tmp"
    scratch.write_bytes(("# 巡检失败清单\n" + "".join(f"- {item}\n" for item in failed)).encode("utf8"))
    scratch.replace(folder / "TODO.md")
    return "written"


def due(now):
    if now.tzinfo != timezone.utc:
        raise ValueError("Use a UTC datetime in this exercise")
    return now.weekday() < 5 and (now.hour, now.minute) == (9, 0)


def initialize(db):
    with db:
        db.execute("CREATE TABLE state (phase TEXT, streak INTEGER, attempts INTEGER)")
        db.execute("INSERT INTO state VALUES ('active', 0, 0)")
        db.execute("CREATE TABLE events (id TEXT PRIMARY KEY)")
        db.commit()


def status(db):
    return list(db.execute("SELECT phase, streak, attempts FROM state").fetchone())


def tick(db, event_id, passed, required=5, budget=10):
    if type(passed) is not bool:
        raise TypeError("Pass or fail must be a Boolean observation")
    with db:
        db.execute("BEGIN IMMEDIATE")
        phase, streak, attempts = status(db)
        if phase != "active":
            return phase
        event = db.execute("INSERT OR IGNORE INTO events VALUES (?)", (event_id,))
        if event.rowcount == 0:
            return "duplicate"
        attempts += 1
        streak = streak + 1 if passed else 0
        if streak >= required:
            phase = "done"
        elif attempts >= budget:
            phase = "blocked_budget"
        db.execute("UPDATE state SET phase=?, streak=?, attempts=?", (phase, streak, attempts))
    return phase


def stop(db):
    with db:
        db.execute("UPDATE state SET phase='stopped' WHERE phase='active'")


def exercise_reports(root):
    source = root / "ci.json"
    source.write_bytes(b'[{"id":"C3","status":"failed"},{"id":"B1","status":"passed"},{"id":"A2","status":"failed"},{"id":"A2","status":"failed"}]')
    initial = fixture_hash(source)
    denied = [write_report(root, initial, action="publish"), write_report(root, initial, destination="../patch.py")]
    state = write_report(root, initial)
    report = root / "TODO.md"
    original = report.read_text(encoding="utf8")
    observe("loop_report_scope", ["fixed CI records", "allow TODO.md only"], "分类失败项、去重、检查原始数据未被修改",
            [["denied", "denied"], "written", "# 巡检失败清单\n- A2\n- C3\n", True],
            [denied, state, original, fixture_hash(source) == initial])
    source.write_bytes(b'[{"id":"D4","status":"failed"}]')
    stale = write_report(root, initial)
    unchanged = report.read_text(encoding="utf8") == original
    refreshed = write_report(root, fixture_hash(source))
    observe("loop_refresh_stale", "CI 证据在读取后变化", "使用旧快照拒写,刷新后再写并核对结果",
            ["stale", True, "written", "# 巡检失败清单\n- D4\n"],
            [stale, unchanged, refreshed, report.read_text(encoding="utf8")])


def exercise_state(root):
    file = root / "streak.sqlite3"
    with closing(sqlite3.connect(file)) as db:
        initialize(db)
        for event, passed in (("a", True), ("b", True), ("c", False)):
            assert tick(db, event, passed) == "active"
    with closing(sqlite3.connect(file)) as db:
        before = status(db)
        observed = [tick(db, f"retry-{index}", True) for index in range(5)]
        after = status(db)
        terminal = tick(db, "extra", True)
        observe("loop_consecutive_resume", [True, True, False, "reopen", True, True, True, True, True],
                "重开持久状态,验证失败清零、五次连续通过和终止",
                [["active", 0, 3], ["active", "active", "active", "active", "done"], ["done", 5, 8], "done"],
                [before, observed, after, terminal])
    with closing(sqlite3.connect(root / "budget.sqlite3")) as db:
        initialize(db)
        states = [tick(db, event, passed, budget=2) for event, passed in (("a", False), ("a", True), ("b", False), ("c", True))]
        observe("loop_duplicate_budget", ["first failure", "duplicate with different payload", "second failure", "late pass"],
                "重复事件不计入额度,两次失败后拦截新轮次",
                [["active", "duplicate", "blocked_budget", "blocked_budget"], ["blocked_budget", 0, 2]],
                [states, status(db)])
    file = root / "stopped.sqlite3"
    with closing(sqlite3.connect(file)) as db:
        initialize(db)
        stop(db)
    with closing(sqlite3.connect(file)) as db:
        observe("loop_stop_persists", "主动停止后重开数据库", "尝试投递新事件并检查计数",
                ["stopped", ["stopped", 0, 0]], [tick(db, "late", True), status(db)])


def main():
    with TemporaryDirectory(prefix="mbsky-loop-lab-") as temporary:
        root = Path(temporary)
        exercise_reports(root)
        exercise_state(root)
    day = datetime(2026, 6, 15, 9, 0, tzinfo=timezone.utc)
    weekend = day.replace(day=20)
    inputs = [day.replace(hour=8, minute=59), day, weekend]
    observe("loop_utc_schedule", [point.isoformat() for point in inputs],
            "检查固定 UTC 工作日和时间边界,不创建系统任务",
            [False, True, False], [due(point) for point in inputs])
    print(json.dumps(CASES, ensure_ascii=False))


if __name__ == "__main__":
    main()
本例需在 CPython 3.12、临时 SQLite、临时 Git 仓库和本地 MCP stdio。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:CPython 3.12、临时 SQLite、临时 Git 仓库和本地 MCP stdio。

入口文件:projects/ai-agent-loop/control_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 control_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 CPython 3.12、临时 SQLite、临时 Git 仓库和本地 MCP stdio。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:AI Agent(智能体)

课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a3073.zip

下载课程关联工程包:AI Agent(智能体)

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3090.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习