tiers.py

clew/tiers.py

Five-tier precedence for every layered build option — ONE combination rule.

as_meta

dict[str, str] clew.tiers.LayeredResolution.as_meta(self, str option)

Flatten this resolution into build_meta rows for one option.

clew/tiers.py:149

Show on the map →

Called by none

Calls none

Source · 19 lines
    def as_meta(self, option: str) -> dict[str, str]:
        """The tier is ALWAYS recorded; the stated layer only when tier 1 won.

        Writing `explicit` unconditionally would make the read-back replay a
        declaration or the built-in guesses as though an operator had typed them,
        which is the failure `_operator_excludes` avoids by recording only what the
        operator actually stated. An absent key honestly reads as "nothing to
        replay", matching the writer's rule that falsy values are dropped.

        @brief Build the build_meta fragment for this resolution.
        @return Unprefixed key/value mapping.
        @version 1
        """
        meta = {f"{option}.{TIER_KEY}": self.tier}
        if self.tier == TIER_EXPLICIT and self.stated:
            meta[f"{option}.{EXPLICIT_KEY}"] = VALUE_SEPARATOR.join(self.stated)
        return meta

Activity · 4 steps
lines 162–162meta = {f"{option}.{TIER_KEY}": self.tier}lines 163–163◇ if self.tier == TIER_EXPLICIT and self.statedlines 164–164meta[f"{option}.{EXPLICIT_KEY}"] = VALUE_SEPARATOR.join(self.stated)lines 165–165return meta
dict[str, str] clew.tiers.DocumentResolution.as_meta(self, str option)

Flatten this resolution into build_meta rows for one option.

clew/tiers.py:230

Source · 22 lines
    def as_meta(self, option: str) -> dict[str, str]:
        """THE TIER IS ALWAYS WRITTEN, exactly as `LayeredResolution.as_meta` writes
        it, and for the reason `recorded_explicit` documents: the tier row is what
        makes a withdrawal unreplayable. `write_build_signature` upserts and never
        deletes, so a retracted statement can survive beside a fresh tier row, and the
        reader resolves that contradiction by trusting the tier. Skip the tier row for
        a withdrawal and that guard has nothing to compare against.

        The DOCUMENT is written only for a tier-1 win. A tier-2 declaration re-derives
        itself from a file that may have changed since, so replaying a stored copy
        would freeze a stale declaration.

        @brief Build the build_meta fragment for this resolution.
        @return Unprefixed key/value mapping.
        @version 1
        """
        meta = {f"{option}.{TIER_KEY}": self.tier}
        if self.tier == TIER_EXPLICIT and self.stated:
            meta[f"{option}.{EXPLICIT_KEY}"] = canonical_document(self.stated)
        return meta

Activity · 4 steps
lines 246–246meta = {f"{option}.{TIER_KEY}": self.tier}lines 247–247◇ if self.tier == TIER_EXPLICIT and self.statedlines 248–248meta[f"{option}.{EXPLICIT_KEY}"] = canonical_document(self.stated)lines 249–249return meta

Requirements

REQ-DDB-CONFIG-006

canonical_document

str clew.tiers.canonical_document(str|Mapping[str, Any] value)

Serialise a stated document to the byte-stable form build_meta stores.

clew/tiers.py:173

Source · 20 lines
def canonical_document(value: str | Mapping[str, Any]) -> str:
    """CANONICAL MEANS BYTE-STABLE ACROSS PROCESSES, and that is a correctness
    property here rather than tidiness. Two builds of one unchanged tree must produce
    an identical `build_meta`, which is what `test_warm_rebuild_is_deterministic`
    asserts; a dump that preserved insertion order would make the stored row a
    function of how the caller happened to spell its mapping, so re-stating an
    equal document would read as a change.

    A PATH and a DOCUMENT share this one row and JSON tells them apart for free — a
    path serialises as a JSON string, a document as a JSON object — so the reader
    needs no second key to say which form was stated, and cannot get that answer
    wrong.

    @brief Canonically serialise a stated manifest document or path.
    @return The stored representation.
    @version 1
    """
    return json.dumps(value, sort_keys=True, separators=DOCUMENT_SEPARATORS)

Activity · 1 steps
lines 190–190return json.dumps(value, sort_keys=True, separators=DOCUMENT_SEPARATORS)

Requirements

REQ-DDB-CONFIG-006

options_meta

dict[str, str] clew.tiers.options_meta(**LayeredResolution|DocumentResolution resolutions)

Flatten resolved options into the build_meta section they are stamped as.

clew/tiers.py:394

Source · 32 lines
def options_meta(**resolutions: LayeredResolution | DocumentResolution) -> dict[str, str]:
    """THE ONLY PRODUCER of the `options.*` rows, and it accepts only resolutions.

    That refusal is what makes "record the tier" structural rather than a habit. A
    caller cannot stamp a layered option from a bare list, because there is no code
    path from a list to these rows; it has to hold the object that knows which tier
    won. Raising `TypeError` rather than coercing follows the repo's fail-closed
    rule — a silently skipped option would present exactly as an older index that
    never recorded one.

    A DOCUMENT-VALUED OPTION goes through the same door (gh#364). The five manifest
    options state a whole document rather than a list, and routing them through a
    second producer would give the `options.*` section two writers free to disagree
    about the key layout the reader depends on.

    @brief Build the `options` build_meta section from resolutions.
    @return Unprefixed key/value mapping.
    @version 2
    """
    meta: dict[str, str] = {}
    for option, resolution in resolutions.items():
        if not isinstance(resolution, RESOLUTION_TYPES):
            raise TypeError(
                f"options_meta({option}=...) needs a LayeredResolution or "
                f"DocumentResolution carrying its winning tier, got "
                f"{type(resolution).__name__}. Resolve the option through "
                f"resolve_layered() or resolve_document() rather than passing bare values."
            )
        meta.update(resolution.as_meta(option))
    return meta

Activity · 6 steps
lines 413–413meta: dict[str, str] = {}lines 414–414◇ for option, resolution in resolutions.items()lines 415–415◇ if not isinstance(resolution, RESOLUTION_TYPES)lines 416–421raise TypeError( f"options_meta({option}=...) needs a LayeredResolution or " f"DocumentResolution carrying its winning tier, got " f"{type(resolution).__name__}. Resolve the option through " f"resolve_layered() or resolve_document() rather than passing bare values." )lines 422–422meta.update(resolution.as_meta(option))lines 423–423return meta

Requirements

REQ-DDB-CONFIG-006

recorded_document

str | dict[str, Any] | None clew.tiers.recorded_document(Mapping[str, str] section, str option)

Read back the tier-1 manifest DOCUMENT a previous build recorded for one option.

clew/tiers.py:474

Source · 27 lines
def recorded_document(section: Mapping[str, str], option: str) -> str | dict[str, Any] | None:
    """THE SAME TIER CROSS-CHECK `recorded_explicit` DOES, and it is checked here for
    the document form rather than assumed to carry over: the guard lives in the READER,
    so a second reader that skipped it would replay a withdrawn statement while the
    first one refused to. `write_build_signature` upserts and never deletes, so a
    retracted `<option>.explicit` row can outlive the statement it recorded; the tier
    row is written on every stamp, so the tier is authoritative and a statement that
    disagrees with it resolves to "nothing to replay".

    A CORRUPT RECORD RAISES rather than reading as "no statement". Reverting silently
    to the target's own declaration is precisely the defect this whole read-back
    exists to remove — a build that cannot honour the recorded policy must not report
    success over a different one. Nothing but this module writes the row, so reaching
    the raise means the database was edited by hand.

    @brief Read one option's recorded manifest statement, if the tier agrees.
    @return The recorded document, the recorded path, or None.
    @version 1
    """
    if section.get(f"{option}.{TIER_KEY}") != TIER_EXPLICIT:
        return None
    raw = section.get(f"{option}.{EXPLICIT_KEY}", "")
    if not raw:
        return None
    return _decoded_document(option, raw)

Activity · 6 steps
lines 493–493◇ if section.get(f"{option}.{TIER_KEY}") != TIER_EXPLICITlines 494–494return Nonelines 495–495raw = section.get(f"{option}.{EXPLICIT_KEY}", "")lines 496–496◇ if not rawlines 497–497return Nonelines 498–498return _decoded_document(option, raw)

Requirements

REQ-DDB-CONFIG-006

recorded_explicit

tuple[str, ...] clew.tiers.recorded_explicit(Mapping[str, str] section, str option)

Read back the tier-1 statement a previous build recorded for one option.

clew/tiers.py:432

Source · 36 lines
def recorded_explicit(section: Mapping[str, str], option: str) -> tuple[str, ...]:
    """ONLY tier 1 is replayable, and this CROSS-CHECKS the tier rather than
    trusting the statement key alone.

    The first version read the statement key by itself, on the argument that the
    policy lived in the writer so the reader had no decision to get wrong. A
    control written in the awkward direction — stamp an explicit statement, then
    stamp its WITHDRAWAL onto the same database — showed that wrong.
    `write_build_signature` upserts and never deletes, so the retracted
    `<option>.explicit` row survived beside a fresh `<option>.tier = heuristic` and
    this function replayed a statement the operator had just withdrawn.

    The real pipeline does not reach it today, because every build stamps a fresh
    temp database that then replaces the live one — but that is an invariant in a
    DIFFERENT module, and depending on it silently means a later caller stamping
    onto a live database (which `_stamp_refresh_metrics` already does, for another
    section) turns a retraction into a replay with nothing to notice it.

    So the TIER is authoritative: it is written on every stamp, and a statement
    that disagrees with it is a contradictory record, which resolves to "nothing to
    replay" rather than to the more interesting of the two readings.

    Same defect this closes as `_operator_excludes`: a resolution that is applied
    and recorded but never read back is discarded by the next refresh, which then
    reports success over exactly the shape the operator asked for.

    @brief Read one option's recorded explicit statement, if the tier agrees.
    @return The recorded values, or ().
    @version 2
    """
    if section.get(f"{option}.{TIER_KEY}") != TIER_EXPLICIT:
        return ()
    raw = section.get(f"{option}.{EXPLICIT_KEY}", "")
    return tuple(part for part in raw.split(VALUE_SEPARATOR) if part)

Activity · 4 steps
lines 462–462◇ if section.get(f"{option}.{TIER_KEY}") != TIER_EXPLICITlines 463–463return ()lines 464–464raw = section.get(f"{option}.{EXPLICIT_KEY}", "")lines 465–465return tuple(part for part in raw.split(VALUE_SEPARATOR) if part)

Requirements

REQ-DDB-CONFIG-006

resolve_document

DocumentResolution clew.tiers.resolve_document(*str|Mapping[str, Any]|None explicit=None, Mapping[str, Any]|None declared=None)

Resolve one manifest option: an operator's statement, else the declaration.

clew/tiers.py:258

Source · 33 lines
def resolve_document(
    *,
    explicit: str | Mapping[str, Any] | None = None,
    declared: Mapping[str, Any] | None = None,
) -> DocumentResolution:
    """THE SAME THREE-WAY CHOICE `_stated_layer` makes, on a document instead of a
    list, so `cli._declared_or_flag`'s precedence and this label cannot disagree about
    which tier won.

    AN EMPTY DOCUMENT IS A WITHDRAWAL, not a statement — `{}` is falsy, so it falls
    through to the declaration and then to the floor, and no statement is recorded.
    That is one spelling doing both jobs on purpose (owner decision, gh#364): clearing
    an option means "stop overriding", which is the same intent as "fall back to the
    target's own declaration".

    THE FLOOR IS LABELLED `heuristic` AND THAT NEEDS READING CAREFULLY. It does NOT
    say the built-in lock, spawn and accessor patterns are guesses — those are tier-3
    and tier-4 layers that ACCUMULATE underneath and no stated tier can displace them.
    It says nobody stated a document, so the replaceable layer is empty and the
    resolved set is exactly what accumulates. That is the identical meaning
    `_stated_layer` gives the label when no list is stated either.

    @brief Resolve which tier supplied one manifest document.
    @return The resolution for that option.
    @version 1
    """
    if explicit:
        return DocumentResolution(TIER_EXPLICIT, explicit)
    if declared:
        return DocumentResolution(TIER_DECLARED)
    return DocumentResolution(TIER_HEURISTIC)

Activity · 5 steps
lines 284–284◇ if explicitlines 285–285return DocumentResolution(TIER_EXPLICIT, explicit)lines 286–286◇ if declaredlines 287–287return DocumentResolution(TIER_DECLARED)lines 288–288return DocumentResolution(TIER_HEURISTIC)

Requirements

REQ-DDB-CONFIG-006

resolve_layered

LayeredResolution clew.tiers.resolve_layered(*Iterable[str] facts, Sequence[str]|None explicit=None, Sequence[str]|None declared=None, Iterable[str] ecosystem=(), Iterable[str] heuristics=())

Resolve one layered option: (tier1 or tier2 or tier5) union tier3 union tier4.

clew/tiers.py:300

Source · 38 lines
def resolve_layered(
    *,
    facts: Iterable[str],
    explicit: Sequence[str] | None = None,
    declared: Sequence[str] | None = None,
    ecosystem: Iterable[str] = (),
    heuristics: Iterable[str] = (),
) -> LayeredResolution:
    """KEYWORD-ONLY, because five same-typed sequence arguments in a row is a
    transposition waiting to happen and transposing `facts` with `heuristics` would
    invert the whole rule silently — the accumulating layer would become
    discardable and the guesses would become permanent, with every count still
    looking legitimate.

    THE ACCUMULATING LAYERS COME FIRST in the resolved order, so a target that
    states nothing resolves to exactly `(*facts, *ecosystem, *heuristics)` — the
    built-in default set, unchanged and comparable by equality rather than by set
    membership. That makes the success-path control a strict assertion instead of a
    loose one, which matters here: this repo has shipped a check that tested only
    its failure path.

    AN EMPTY `explicit` IS A WITHDRAWAL, not a statement. `[]` is falsy, so it
    falls through to the declaration and then to the guesses, which is what lets an
    operator undo a recorded flag without deleting the database. `None` means the
    flag was absent.

    @brief Combine the five tiers into one resolved option.
    @return The resolution, carrying the winning stated tier.
    @version 1
    """
    tier, stated = _stated_layer(explicit, declared, heuristics)
    return LayeredResolution(
        values=_ordered_unique((*facts, *ecosystem, *stated)),
        tier=tier,
        stated=stated,
    )

Activity · 2 steps
lines 330–330tier, stated = _stated_layer(explicit, declared, heuristics)lines 331–335return LayeredResolution( values=_ordered_unique((*facts, *ecosystem, *stated)), tier=tier, stated=stated, )

Requirements

REQ-DDB-CONFIG-006

stated_options

tuple[str, ...] clew.tiers.stated_options(Mapping[str, str] section)

Which options the index carries an operator's own statement for.

clew/tiers.py:540

Source · 25 lines
def stated_options(section: Mapping[str, str]) -> tuple[str, ...]:
    """THE VISIBLE STAMP, and the owner's condition for allowing a statement to be
    replayed at all (gh#364). A replayed statement makes this index a function of what
    an operator once said as well as of the commit, so two operators of one commit can
    legitimately hold different indexes — acceptable ONLY because it is deliberate and
    recorded. This is what makes it findable without reading seven option rows and
    knowing which tier name matters.

    DERIVED FROM THE STORED SECTION, never stamped as a row of its own. A stored
    summary is a second source of truth that can disagree with the rows it summarises,
    which is exactly where a silent wrong answer hides — the same reason the per-target
    state directory was rejected as a home for the record itself.

    @brief Name the options carrying a tier-1 statement.
    @return Sorted option names.
    @version 1
    """
    suffix = f".{TIER_KEY}"
    return tuple(
        sorted(
            key[: -len(suffix)]
            for key, value in section.items()
            if key.endswith(suffix) and value == TIER_EXPLICIT
        )
    )

1 more lines, not shown

Activity · 2 steps
lines 557–557suffix = f".{TIER_KEY}"lines 558–564return tuple( sorted( key[: -len(suffix)] for key, value in section.items() if key.endswith(suffix) and value == TIER_EXPLICIT ) )

Requirements

REQ-DDB-CONFIG-006

Flows