NEO.K / MSSP 開源專案考古008-cpython-logging-warn
專案CPython logging
授權PSF-2.0
檢視版本3.14.5
日期2026-08-08
來源upstream ↗

008 — CPython logging 3.14.5:第二種 host 介面沒有推翻那個想法,它推翻了那個欄位

原專案 CPython Lib/logging,PSF-2.0。本篇考察 3.14.5。 所有數字都是在這台機器上對這個直譯器量出來的。

python src/main.py          # 一份宣告的別名契約,逐通道回答
python src/island_test.py   # 26 項檢查,其中 10 項直接量 CPython 本體

為什麼選它

mssp-d-001 裡 Metron 指定了兩項驗證,這是第一項:

下一個最小驗證不是再找二十個名稱,而是找第二種 host 介面的一個改名案例,看看同一份記錄能不能描述它。

第一個案例(eslint-plugin-import)的 host 是一個 { 規則名: 規則物件 } 映射。logging.warn → warning 的 host 完全不同:類別與模組上的屬性存取。沒有任何註冊表會去讀一列映射——呼叫端寫 logger.warn(...),Python 直接解析屬性。所以「把改名記成目錄的一列」在這裡連可以被誰讀都沒有,舊名字必須是一個真的可呼叫物。

如果那份記錄只在有註冊表的地方成立,它就不是方法,是 eslint 的一個技巧。

原專案的結構地圖

logging 的別名是手寫三份

位置 形狀
Logger.warn warnings.warn(...) 然後 self.warning(...)
LoggerAdapter.warn 同上
模組級 logging.warn warnings.warn(...) 然後 warning(...)

三份都用 stacklevel=2,三份都委派而不是重寫。這是第三種別名形狀——考古 006 的 eslint 是展開物件Object.assign({}, first, …)),範例 008 的反例是重寫,這裡是呼叫過去

委派這件事有一個直接的結構後果:舊名字的行為不可能漂移,因為它沒有自己的行為。 範例 008 那個反例之所以能漂移,正是因為它重寫了。這是三種形狀裡唯一一種讓漂移在結構上不可能發生的。

三份手寫複本彼此有沒有漂移?量了,沒有——三個通道上的 delta 形狀一致,訊息措辭一致。所以這是一個維護面,不是缺陷;按新治理裡 Pragma 的檢查順序,沒有可觀察後果的重複不該被預設成問題,所以它記成觀察。

MSSP 重切

量測

三通道觀察器(handler 輸出、發出的警告、回傳值):

  ok  output    identical
  ok  warnings  differs, declared: one DeprecationWarning naming the replacement
        old: [('DeprecationWarning', "The 'warn' name is deprecated, use 'warning' instead")]
        new: []
  ok  return    identical

別名成立。mssp-d-001 草案的記錄形狀說不出這件事。

壞掉的是哪一個欄位

草案寫的是:

equivalence:
  observer: eslint-rule-contract-v1
  allowed_deltas:
    - meta.deprecated
    - meta.docs.description

allowed_deltas點分欄位路徑。那個寫法假設被比較的東西是一個有欄位的物件——在 eslint 那裡成立,因為兩邊都是 rule 物件,差在 meta.deprecated

這裡兩個可呼叫物作為物件是無法區分的。孤島測試第 5 節把草案的兩個路徑拿來解析,兩個都解析不到任何東西。唯一被允許的差異是「舊名字會多發一個 DeprecationWarning」——那是一個通道,不是一個欄位。

修正很小,而且是證據逼出來的:

allowed_deltas 要命名觀察器底下的觀察,而觀察器要列出自己的通道。欄位路徑是觀察的一種,不是唯一一種。

"equivalence": {
  "observer": "three-channel-v1",
  "allowed_deltas": [
    { "channel": "warnings", "permit": "one DeprecationWarning naming the replacement" }
  ]
}

第二種 host 介面沒有推翻那個想法,它推翻了那個欄位。 這正是 Metron 要這項驗證的用途——不是為了確認候選可行,是為了讓它在便宜的時候壞一次。

SCL 拿回一件記錄不該決定的事

SCL/policy.jsonchannels_that_must_never_differ: ["output", "return"]。孤島測試第 3 節驗過:一個被政策保留的通道,記錄裡寫 allowed_deltas 也放行不了。 這是 mssp-d-002 正在問的那條界線的一個具體樣本——契約可以宣告什麼可以不同,政策可以宣告哪些從來不行,而後者勝出。

同一節還驗了反方向:把 accept_channel_deltas 翻成 false同一份觀察立刻變成失敗。證據沒變,結論翻了。

DMS 多報一件事

報告會說哪些被授予的許可這次沒有被用到。一個沒被行使的許可,這次執行完全沒有說它是不是需要的——那是改良點 7 第三條在契約層的樣子。

什麼不適合拆

三份手寫複本不該現在就合併。 合併需要一個所有 host 形狀都能讀的機制,而 LoggerLoggerAdapter 與模組層級的呼叫路徑不同(一個有 self,一個要轉發 adapter 的 extra,一個要處理 root logger 的初始化)。目前重複的成本是三段五行的函式且沒有漂移;一個統一機制的成本是所有呼叫路徑都要繞過它。在量到漂移之前,這個交換是虧的。

warnings.warn 不該換成回傳值或旗標。 它是 Python 生態系裡宣告棄用的標準通道,測試框架、linter、-W 旗標都認它。換掉會讓一個所有人都在讀的通道變成只有這個模組懂的東西。

委派不該換成「舊名字指向新函式」的別名賦值warn = warning)。那樣就沒有地方放 DeprecationWarning 了——能發出那個警告,正是委派這個形狀在買的東西。

這次沒有解決什麼

改良點 8,每一項要說出把它變成量測需要多少。

重切原始碼

FMS

FMS/__init__.py
FMS/architecture.json
{
  "name": "logging-warn-recut",
  "what_it_is": "A compatibility alias whose permitted difference is on a channel, not on a field — and a record shape that can say so.",
  "examined": {
    "project": "CPython logging",
    "version": "3.14.5",
    "license": "PSF-2.0",
    "why_this_one": "mssp-d-001 asked for a rename under a SECOND host interface, to test whether one record shape describes both. eslint's host is a { name: object } map. This host is attribute access on a class and on a module — nothing reads a data row, so a declared mapping has nothing to be read by.",
    "measured": {
      "copies_of_the_alias": 3,
      "where": [
        "Logger.warn",
        "LoggerAdapter.warn",
        "module-level logging.warn"
      ],
      "implementation_shape": "delegation - warnings.warn(...) then self.warning(...) / warning(...)",
      "stacklevel_used_by_each": 2,
      "do_the_three_copies_agree": "three confirmed statically (present, delegate, stacklevel=2); TWO measured behaviourally on all three channels (Logger, LoggerAdapter); module-level logging.warn NOT isolated for behavioural measurement"
    },
    "contract_run": {
      "observer": "three-channel-v1",
      "channels": [
        "handler output",
        "warnings raised",
        "return value"
      ],
      "output": "SAME",
      "return": "SAME",
      "warnings": "DIFFERS - the old name raises DeprecationWarning(\"The 'warn' method is deprecated, use 'warning' instead\")",
      "note": "measured on Logger and LoggerAdapter; module-level warn triggers root basicConfig and was not isolated"
    }
  },
  "the_finding": "The alias holds, and the record shape from mssp-d-001 cannot say so. allowed_deltas was written as dotted field paths (meta.deprecated). Here the one permitted difference is an emitted warning — a channel, not a field of an object. A second host interface did not break the idea; it broke the schema.",
  "the_amendment": "allowed_deltas must name OBSERVATIONS under the named observer, and the observer must enumerate its channels. A field path is then just one kind of observation, not the only kind.",
  "the_second_observation": "Three hand-written copies of one relation, with nothing tying them together. Two of the three were measured behaviourally and agree; the third was only confirmed statically. So this is a maintenance surface with partial evidence, recorded as an observation rather than a problem.",
  "compatibility_aliases": [
    {
      "kind": "compatibility_alias",
      "old_name": "warn",
      "replacement": "warning",
      "host_constraint": "attribute access on a class and on a module; no registry reads a mapping, so the old name must be a real callable",
      "shim": "authored - delegation, not reimplementation",
      "valid_from": "3.3",
      "equivalence": {
        "observer": "three-channel-v1",
        "allowed_deltas": [
          {
            "observation": "warnings",
            "predicate": "one-deprecation-warning-naming-replacement-v1"
          }
        ]
      },
      "evidence": "src/island_test.py — the sections measuring CPython and the schema; section numbers deliberately not cited, they drifted once already",
      "sunset": "unstated by upstream - see README"
    }
  ],
  "observers": {
    "three-channel-v1": {
      "channels": {
        "output": "everything the call writes through the handler",
        "warnings": "every warning raised during the call, as (category, message)",
        "return": "the returned value"
      },
      "what_it_cannot_see": "stacklevel correctness, timing, anything reached through a handler this fixture does not install, and — found by archaeology 009 on 2026-08-09 — the channel's own MEMORY: warnings are delivered once per (text, category, lineno) per module, and catch_warnings resets that registry as a side effect of isolating filters. This observer therefore reports a frequency no caller experiences."
    }
  },
  "sets": {
    "FMS": "this file: the record, the observer and its channels",
    "SCL": "whether this deployment accepts a channel-level delta at all",
    "SMS": "the observer - runs a callable and collects all three channels",
    "TMS": "two emitters, each importing nothing",
    "DMS": "which channels agreed, which differed, and whether the difference was declared"
  },
  "non_goals": [
    "Being a logging library. Two emitters and a fixture.",
    "Claiming CPython should have a sunset. It has not stated one, and this entry does not treat an absent field as a defect - see the README."
  ],
  "the_finding_correction": "\"Delegation makes drift impossible\" was too strong — Metron, 2026-08-08. Delegation removes the RE-IMPLEMENTATION drift of the core logic, because there is no second copy of it. The wrapper still has behaviour of its own: warning class, message, stacklevel, argument transformation, and whether it delegates on every path. This entry already notes that stacklevel is outside the observer, which is exactly such a case.",
  "the_correction_from_009": "Archaeology 009 measured that five calls from one site emit ONE warning without an instrument and FIVE when each is wrapped in catch_warnings. The permit here is not wrong about what it saw, but the honest statement is \"one on the first call from a given site in a process\" — the observer was resetting the channel it was measuring."
}

SCL

SCL/__init__.py
SCL/policy.json
{
  "policy_version": "1.0",
  "_comment": [
    "A deployment can refuse channel-level deltas entirely - a library that",
    "promises warning-for-warning parity is a different product from one that",
    "does not. Flipping this turns the same observation into a failure."
  ],
  "accept_channel_deltas": true,
  "channels_that_must_never_differ": ["output", "return"]
}
SCL/policy.py
"""What this deployment will accept as a permitted difference."""
import json
import pathlib

_C = json.loads((pathlib.Path(__file__).parent / "policy.json").read_text(encoding="utf-8"))


def accepts_channel_deltas():
    return bool(_C["accept_channel_deltas"])


def never_differ():
    return list(_C["channels_that_must_never_differ"])

SMS

SMS/__init__.py
SMS/contract.py
"""Checking a declared equivalence whose permitted differences are channels."""


from . import predicates


def check(alias, observer, before, after, accepts_channel_deltas, never_differ):
    permitted = {d["observation"]: d.get("predicate") for d in alias["equivalence"]["allowed_deltas"]}
    channels = list(observer["channels"])
    clauses = []

    for channel in channels:
        same = before[channel] == after[channel]
        if same:
            clauses.append((channel, True, "identical", None))
            continue
        if channel in never_differ:
            clauses.append((channel, False, f"differs, and policy forbids any delta on {channel}", None))
            continue
        if channel not in permitted:
            clauses.append((channel, False, "differs and is not in allowed_deltas", (before[channel], after[channel])))
            continue
        if not accepts_channel_deltas:
            clauses.append((channel, False, "declared as permitted, but this deployment refuses channel deltas",
                            (before[channel], after[channel])))
            continue

        # The permit is executed, not read. An id that does not resolve, or a
        # difference the predicate rejects, is not a permitted difference.
        predicate, problem = predicates.resolve(permitted[channel])
        if problem:
            clauses.append((channel, False, problem, (before[channel], after[channel])))
            continue
        verdict = predicate(before, after, alias)
        if verdict:
            clauses.append((channel, False, f"declared permit not satisfied: {verdict}",
                            (before[channel], after[channel])))
            continue
        clauses.append((channel, True, f"differs, and the permit holds: {permitted[channel]}",
                        (before[channel], after[channel])))

    # A channel named in allowed_deltas that never actually differed is worth
    # reporting: the permission was never exercised, so this run says nothing
    # about whether it was needed.
    unexercised = [c for c in permitted if before.get(c) == after.get(c)]
    return {"clauses": clauses, "unexercised_permissions": unexercised,
            "holds": all(ok for _, ok, _, _ in clauses)}
SMS/observe.py
"""The observer: run a callable and collect every channel it is defined over.

The amendment this entry produced. mssp-d-001's draft record wrote
allowed_deltas as dotted field paths, which can describe `meta.deprecated` on an
object and cannot describe "the old name raises a DeprecationWarning". A field
path assumes the thing being compared IS an object with fields. Here the two
callables are indistinguishable as objects and differ only in what they emit.
"""
import io
import warnings


def observe(call):
    """Return {channel: observation} for one call."""
    buffer = io.StringIO()
    with warnings.catch_warnings(record=True) as caught:
        warnings.simplefilter("always")
        try:
            returned = call(buffer)
            raised = None
        except Exception as exc:  # noqa: BLE001 - the class is part of the observation
            returned, raised = None, type(exc).__name__
    return {
        "output": buffer.getvalue(),
        "warnings": [(w.category.__name__, str(w.message)) for w in caught],
        "return": repr(returned) if raised is None else f"raised {raised}",
    }
SMS/predicates.py
"""Executable predicates for allowed deltas.

Metron ran this entry on 2026-08-08 and replaced the real difference with
`RuntimeWarning("not a deprecation and does not name replacement")`. The
contract still returned holds: true, because the record's

    permit: one DeprecationWarning naming the replacement

was prose. The check only asked whether the `warnings` channel appeared in
allowed_deltas — it never read the sentence. **The declaration looked precise
and the verdict read a wider layer**, which is the exact shape this field lab
keeps finding in other people's code.

A permit is now an id resolved here. An id that does not resolve fails closed:
an unverifiable declaration is not a permitted difference, it is an unchecked
one.
"""


def _one_deprecation_warning_naming_replacement(before, after, alias):
    """The old name raises exactly one DeprecationWarning that names the new name."""
    old = before.get("warnings", [])
    new = after.get("warnings", [])
    if new:
        return f"the replacement raised {len(new)} warning(s); it must raise none"
    if len(old) != 1:
        return f"the old name raised {len(old)} warning(s); the permit allows exactly one"
    category, message = old[0]
    if category != "DeprecationWarning":
        return f"the warning is a {category}; the permit allows only DeprecationWarning"
    if alias["replacement"] not in message:
        return (f"the warning does not name the replacement "
                f"({alias['replacement']!r} not in {message!r})")
    return None


REGISTRY = {
    "one-deprecation-warning-naming-replacement-v1": _one_deprecation_warning_naming_replacement,
}


def resolve(name):
    """Return (predicate, problem). A missing id is a problem, never a pass."""
    if not name:
        return None, "the allowed delta names no predicate"
    if name not in REGISTRY:
        return None, f'predicate "{name}" does not resolve — fail closed'
    return REGISTRY[name], None

TMS

TMS/__init__.py
TMS/emitters/__init__.py
TMS/emitters/current.py
"""The current name. Imports nothing."""

NAME = "warning"


def emit(buffer, message):
    buffer.write(f"WARNING:{message}\n")
    return None
TMS/emitters/legacy.py
"""The old name: delegates and announces itself.

This is CPython's shape, not eslint's. It does not spread an object and it does
not reimplement — it calls through, after raising a warning. Imports nothing:
the delegation target is passed in, so this unit names no sibling.
"""
import warnings

NAME = "warn"


def emit(buffer, message, delegate):
    warnings.warn("The 'warn' name is deprecated, use 'warning' instead",
                  DeprecationWarning, stacklevel=2)
    return delegate(buffer, message)

DMS

DMS/__init__.py
DMS/report.py
"""Which channels agreed, which differed, and whether the difference was declared."""


def render(alias, observer, result, policy_note):
    lines = ["", f"== {alias['old_name']} -> {alias['replacement']}  (observer {alias['equivalence']['observer']})"]
    lines.append(f"   host: {alias['host_constraint']}")
    lines.append("")
    for channel, ok, why, values in result["clauses"]:
        lines.append(f"  {'ok ' if ok else '!! '} {channel:<9} {why}")
        if values:
            lines.append(f"        old: {values[0]!r}")
            lines.append(f"        new: {values[1]!r}")
    lines.append("")
    if result["unexercised_permissions"]:
        lines.append(f"  permissions granted but never needed on this run: "
                     f"{', '.join(result['unexercised_permissions'])}")
    else:
        lines.append("  every declared permission was exercised by this run")
    lines.append(f"  {policy_note}")
    lines.append("")
    lines.append(f"  the declaration {'HOLDS' if result['holds'] else 'DOES NOT HOLD'} under this observer,")
    lines.append("  and 'this observer' is three named channels a person chose.")
    return "\n".join(lines) + "\n"

root

island_test.py
"""The island test, and the live measurement of CPython's own warn alias.

    python src/island_test.py

Section 4 is why this entry exists: mssp-d-001 asked for a rename under a
second host interface, to find out whether one record shape describes both.
It does not — and section 5 shows exactly which field of the schema breaks.
"""
import io
import inspect
import json
import logging
import pathlib
import re
import sys
import warnings

HERE = pathlib.Path(__file__).parent
sys.path.insert(0, str(HERE))

from DMS import report  # noqa: E402
from SCL import policy  # noqa: E402
from SMS import contract, observe  # noqa: E402
from TMS.emitters import current, legacy  # noqa: E402

RECORD = json.loads((HERE / "FMS" / "architecture.json").read_text(encoding="utf-8"))
ALIAS = RECORD["compatibility_aliases"][0]
OBSERVER = RECORD["observers"][ALIAS["equivalence"]["observer"]]

FAILURES = []


def check(label, ok, detail=""):
    print(f"  {'PASS' if ok else 'FAIL'}  {label}{' - ' + detail if detail else ''}")
    if not ok:
        FAILURES.append(label)


def run_pair():
    before = observe.observe(lambda buf: legacy.emit(buf, "disk almost full", current.emit))
    after = observe.observe(lambda buf: current.emit(buf, "disk almost full"))
    return before, after


print("\n== 1. each emitter is an island")
for name in ("current", "legacy"):
    source = (HERE / "TMS" / "emitters" / f"{name}.py").read_text(encoding="utf-8")
    reaches = re.findall(r"^\s*(?:from|import)\s+(\S+)", source, re.M)
    external = [r for r in reaches if r not in ("warnings",)]
    check(f"emitters/{name} names no sibling", not external, ", ".join(external) or "only the stdlib")
check("the legacy emitter takes its delegate as an argument",
      "delegate" in inspect.signature(legacy.emit).parameters,
      "so the old name calls through without naming the unit it calls")

print("\n== 2. the declaration holds, and for the reason it declared")
before, after = run_pair()
result = contract.check(ALIAS, OBSERVER, before, after,
                        policy.accepts_channel_deltas(), policy.never_differ())
check("the alias holds", result["holds"])
check("output is identical", before["output"] == after["output"], repr(before["output"]))
check("return is identical", before["return"] == after["return"])
check("warnings differ, and the record said they would",
      before["warnings"] != after["warnings"]
      and any(d["observation"] == "warnings" for d in ALIAS["equivalence"]["allowed_deltas"]))
check("and the permission was actually exercised",
      not result["unexercised_permissions"],
      "a permission nothing used would say nothing about whether it was needed")

print("\n== 3. the checks can fail")
strict = contract.check(ALIAS, OBSERVER, before, after,
                        accepts_channel_deltas=False, never_differ=policy.never_differ())
check("a deployment that refuses channel deltas turns the same run into a failure",
      not strict["holds"],
      "same observation, different policy, opposite verdict")
forbidden = contract.check(ALIAS, OBSERVER, before, after,
                           accepts_channel_deltas=True, never_differ=["output", "return", "warnings"])
check("a channel listed as never-differ cannot be waived by allowed_deltas",
      not forbidden["holds"],
      "policy outranks the record for the channels it reserves")
drifted = dict(after)
drifted["output"] = "WARNING:something else\n"
broken = contract.check(ALIAS, OBSERVER, before, drifted,
                        policy.accepts_channel_deltas(), policy.never_differ())
check("an output difference fails, because output is never waivable",
      not broken["holds"],
      [why for ch, ok, why, _ in broken["clauses"] if ch == "output"][0])

print("\n== 4. measured against CPython logging 3.14.5 itself")
check("this interpreter is the examined version", sys.version.split()[0] == "3.14.5",
      sys.version.split()[0])

src = pathlib.Path(inspect.getsourcefile(logging)).read_text(encoding="utf-8")
copies = re.findall(r"def warn\(", src)
check("the alias is hand-written three times", len(copies) == 3,
      "Logger.warn, LoggerAdapter.warn, module-level warn")
stacklevels = set(re.findall(r"DeprecationWarning,\s*(\d+)\)", src))
check("every copy uses the same stacklevel", stacklevels == {"2"}, ", ".join(sorted(stacklevels)))
check("every copy delegates rather than reimplements",
      len(re.findall(r"(?:self\.)?warning\(msg, \*args, \*\*kwargs\)", src)) >= 3,
      "warnings.warn(...) then warning(...)")


def cpython_pair(make_old, make_new):
    def observed(make):
        buf = io.StringIO()
        handler = logging.StreamHandler(buf)
        handler.setFormatter(logging.Formatter("%(levelname)s:%(name)s:%(message)s"))
        log = logging.getLogger("island")
        log.handlers[:] = [handler]
        log.setLevel(logging.DEBUG)
        log.propagate = False
        with warnings.catch_warnings(record=True) as caught:
            warnings.simplefilter("always")
            returned = make(log)
        return {"output": buf.getvalue(),
                "warnings": [(w.category.__name__, str(w.message)) for w in caught],
                "return": repr(returned)}
    return observed(make_old), observed(make_new)


observations = {}
for label, old, new in (
    ("Logger", lambda lg: lg.warn("m %s", 1), lambda lg: lg.warning("m %s", 1)),
    ("LoggerAdapter",
     lambda lg: logging.LoggerAdapter(lg, {}).warn("m %s", 1),
     lambda lg: logging.LoggerAdapter(lg, {}).warning("m %s", 1)),
):
    o, n = cpython_pair(old, new)
    observations[label] = (o, n)
    differing = [c for c in ("output", "warnings", "return") if o[c] != n[c]]
    check(f"{label}: exactly one channel differs", differing == ["warnings"], ", ".join(differing))
    check(f"{label}: and it is the deprecation notice",
          o["warnings"] and o["warnings"][0][0] == "DeprecationWarning" and not n["warnings"],
          o["warnings"][0][1] if o["warnings"] else "none")

# The first version of this line was `check(..., True, ...)` — a hardcoded pass
# in the section measuring whether three hand-written copies had drifted, which
# is the one thing this section exists to find out. Compute it.
logger_delta = {c: observations["Logger"][0][c] != observations["Logger"][1][c]
                for c in ("output", "warnings", "return")}
adapter_delta = {c: observations["LoggerAdapter"][0][c] != observations["LoggerAdapter"][1][c]
                 for c in ("output", "warnings", "return")}
# Metron: the FMS said all three copies were measured on all three channels.
# Two were. The module-level one triggers root basicConfig and was not isolated,
# and the README always said so — the record was the thing overclaiming.
check("the record no longer claims all three were measured behaviourally",
      "TWO measured behaviourally" in RECORD["examined"]["measured"]["do_the_three_copies_agree"],
      "three confirmed statically, two measured")
check("the two hand-written copies produce the same delta shape",
      logger_delta == adapter_delta,
      f"Logger {logger_delta} vs LoggerAdapter {adapter_delta}")
check("and their deprecation messages are worded identically",
      observations["Logger"][0]["warnings"][0][1].replace("method", "X")
      == observations["LoggerAdapter"][0]["warnings"][0][1].replace("method", "X"),
      "the duplication has not drifted — measured, not assumed")

print("\n== 5. the schema from mssp-d-001 cannot express this")
draft_allowed_deltas = ["meta.deprecated", "meta.docs.description"]


def resolve(dotted, obj):
    cursor = obj
    for key in dotted.split("."):
        if not isinstance(cursor, dict) or key not in cursor:
            return None
        cursor = cursor[key]
    return cursor


check("the draft's allowed_deltas are dotted FIELD paths",
      all("." in d for d in draft_allowed_deltas), ", ".join(draft_allowed_deltas))
check("and neither resolves against anything here",
      all(resolve(d, before) is None for d in draft_allowed_deltas),
      "the two callables are indistinguishable as objects")
check("the one permitted difference is an observation, not a field",
      isinstance(ALIAS["equivalence"]["allowed_deltas"][0], dict)
      and "observation" in ALIAS["equivalence"]["allowed_deltas"][0],
      json.dumps(ALIAS["equivalence"]["allowed_deltas"][0], ensure_ascii=False))
# Metron, 2026-08-08: the permit was prose and a RuntimeWarning with the wrong
# message still passed. It is a predicate id now, and an unresolvable one fails
# closed.
from SMS import predicates  # noqa: E402
_bad = dict(ALIAS); _bad["equivalence"] = dict(ALIAS["equivalence"],
    allowed_deltas=[{"observation": "warnings", "predicate": "no-such-predicate"}])
_r = contract.check(_bad, OBSERVER, before, after, True, policy.never_differ())
check("an unresolvable predicate id fails closed", not _r["holds"],
      [t for c, ok, t, _ in _r["clauses"] if c == "warnings"][0])
_wrong = dict(before, warnings=[("RuntimeWarning", "not a deprecation and does not name replacement")])
_r2 = contract.check(ALIAS, OBSERVER, _wrong, after, True, policy.never_differ())
check("Metron's exact counter-case now fails", not _r2["holds"],
      [t for c, ok, t, _ in _r2["clauses"] if c == "warnings"][0][:72])
_unnamed = dict(before, warnings=[("DeprecationWarning", "this is old, stop using it")])
_r3 = contract.check(ALIAS, OBSERVER, _unnamed, after, True, policy.never_differ())
check("a right-class warning that does not name the replacement also fails", not _r3["holds"],
      "the predicate reads the message, not just the channel")
check("so the second host interface amended the schema rather than breaking the idea",
      RECORD["the_amendment"].startswith("allowed_deltas must name OBSERVATIONS"),
      "a field path is one kind of observation, not the only kind")

print("\n== 6. what this entry does not claim")
check("upstream states no sunset, and that is recorded as absent rather than wrong",
      ALIAS["sunset"].startswith("unstated"), ALIAS["sunset"])
check("the observer names its own blind spot",
      "stacklevel" in OBSERVER["what_it_cannot_see"], OBSERVER["what_it_cannot_see"])

print()
if FAILURES:
    print(f"  {len(FAILURES)} check(s) failed: {', '.join(FAILURES)}")
    raise SystemExit(1)
print("  island test passed")
main.py
"""Check the declared alias against what the two emitters actually do.

    python src/main.py
"""
import json
import pathlib
import sys

sys.path.insert(0, str(pathlib.Path(__file__).parent))

from DMS import report  # noqa: E402
from SCL import policy  # noqa: E402
from SMS import contract, observe  # noqa: E402
from TMS.emitters import current, legacy  # noqa: E402

HERE = pathlib.Path(__file__).parent
RECORD = json.loads((HERE / "FMS" / "architecture.json").read_text(encoding="utf-8"))


def main():
    alias = RECORD["compatibility_aliases"][0]
    observer = RECORD["observers"][alias["equivalence"]["observer"]]

    before = observe.observe(lambda buf: legacy.emit(buf, "disk almost full", current.emit))
    after = observe.observe(lambda buf: current.emit(buf, "disk almost full"))

    result = contract.check(alias, observer, before, after,
                            policy.accepts_channel_deltas(), policy.never_differ())
    note = (f"SCL: channel deltas {'accepted' if policy.accepts_channel_deltas() else 'REFUSED'}; "
            f"never-differ channels: {', '.join(policy.never_differ())}")
    sys.stdout.write(report.render(alias, observer, result, note))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())