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.
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
dict[str, str] clew.tiers.DocumentResolution.as_meta(self, str option)
Flatten this resolution into build_meta rows for one option.
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
Requirements
canonical_document
str clew.tiers.canonical_document(str|Mapping[str, Any] value)
Serialise a stated document to the byte-stable form build_meta stores.
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
Requirements
options_meta
dict[str, str] clew.tiers.options_meta(**LayeredResolution|DocumentResolution resolutions)
Flatten resolved options into the build_meta section they are stamped as.
Called by _build_stages, _stamp, _stamp_manifest
Tested by 9 tests
test_a_multi_value_statement_round_trips_through_the_stored_form, test_a_stated_data_model_records_its_tier, test_nothing_is_stated_and_nothing_replays_for_a_target_that_states_nothing, test_only_a_tier_one_statement_is_recorded_for_replay, test_options_meta_refuses_a_bare_manifest_mapping, test_options_meta_refuses_values_whose_tier_was_discarded, test_status_names_the_options_an_operator_stated, test_the_alias_tier_is_stamped_beside_the_entry_pattern_tier, test_the_stored_document_is_byte_STABLE_across_key_orderings
Calls none
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
Requirements
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.
Called by _replay_manifest_statements, stated_declaration
Tested by 6 tests
test_a_corrupt_record_refuses_rather_than_reverting_silently, test_a_declared_manifest_is_not_replayed_from_the_record, test_a_stated_manifest_survives_a_rebuild_and_a_withdrawal_undoes_it, test_a_withdrawn_manifest_statement_is_not_replayed_from_a_stale_row, test_an_empty_document_withdraws_the_record_rather_than_ignoring_it, test_the_stored_document_is_byte_STABLE_across_key_orderings
Calls _decoded_document
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
Requirements
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.
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
Requirements
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.
Called by _build_stages, _manifest_option_tiers
Tested by 8 tests
test_a_declared_manifest_is_not_replayed_from_the_record, test_a_manifest_statement_survives_a_later_build_that_states_nothing, test_a_stated_path_replays_as_a_path, test_a_statement_made_on_this_call_is_not_overwritten_by_the_record, test_a_withdrawn_manifest_statement_is_not_replayed_from_a_stale_row, test_an_empty_document_withdraws_the_record_rather_than_ignoring_it, test_status_names_the_options_an_operator_stated, test_the_stored_document_is_byte_STABLE_across_key_orderings
Calls none
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
Requirements
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.
Called by _build_stages, _entry_patterns, _test_paths, resolve_key_alias_prefixes
Tested by 8 tests
test_a_declaration_displaces_the_guesses_and_keeps_the_facts, test_a_multi_value_statement_round_trips_through_the_stored_form, test_a_restated_fact_is_not_duplicated, test_a_target_stating_nothing_gets_facts_and_guesses_together, test_an_empty_explicit_list_withdraws_rather_than_states, test_an_explicit_statement_displaces_the_guesses_and_keeps_the_facts, test_only_a_tier_one_statement_is_recorded_for_replay, test_tier_one_beats_tier_two
Calls _ordered_unique, _stated_layer
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
Requirements
stated_options
tuple[str, ...] clew.tiers.stated_options(Mapping[str, str] section)
Which options the index carries an operator's own statement for.
Called by db_status, stated_declaration
Tested by 5 tests
test_a_stated_configuration_survives_export_declare_rebuild, test_a_stated_manifest_survives_a_rebuild_and_a_withdrawal_undoes_it, test_a_stated_predefined_survives_a_rebuild_and_a_withdrawal_undoes_it, test_nothing_is_stated_and_nothing_replays_for_a_target_that_states_nothing, test_status_names_the_options_an_operator_stated
Calls none
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