lawref.evaluator
Оракул L0 — первый инкремент (WP-07-срез): support-семантика assertions, тривиальная epistemic acceptance, halt-политика E-0001, календарные операции, schema-валидный результат с proof graph и детерминированными хэшами.
Ещё не реализовано (по вехам WP-07): strict rules (naive fixpoint), closure §70, collect/агрегаты §51–52.1, relation keys §45.1/KEY_CONFLICT §196 — оракул наращивается вертикальными срезами, каждый закрывает конкретные векторы.
Хэш-конвенции v1 (кандидаты в errata при расхождении с будущей нормой):
- manifest.semanticHash = sha256 канонических байтов манифеста без semanticHash;
- proofGraph.proofHash = sha256 канонических байтов графа без proofHash;
- resultHash = sha256 канонических байтов документа без resultHash и executionReceipt (§2.18/AUDIT §2.13: receipt вне semantic result);
- оракул receipt не эмитит (поле опционально) — выход детерминирован байтово.
Модуль вырос в пакет: границы совпадают с секциями law-eval/src/lib.rs, с
которым оракул сверяется байтово (FND §5.4). Публичная поверхность прежняя —
from lawref.evaluator import evaluate продолжает работать.
Attributes
| Name | Description |
|---|---|
ACCEPTED_ORIGINS | No description. |
NORM_STD | No description. |
SCHEMA_VERSION | No description. |
Classes
| Name | Description |
|---|---|
EvaluationRequest | Типизированный единственный вход evaluation (DECISION-0111 §2.2). |
EvaluationRequestError | No description. |
LimitExceeded | §238: превышение семантического лимита — детерминированный отказ RESOURCE_LIMIT. |
ProofRegistry | Единый реестр proof-узлов: support-id → proof-node-id (детерминированно). |
SupportStore | Пара поддержки (t, f) на ground-атом (SPEC §62); стороны хранятся раздельно (§61). |
UnsupportedLanguageVersionError | LDC-E1401 на evaluation boundary для отозванной семантики. |
Functions
| Name | Description |
|---|---|
evaluate | Публичная граница исполнения (DECISION-0111 §2.2). |
literal_key | Ключ ground-атома: predicate + канонические args (полярность отдельно, §61–§62). |
run_vector | Исполнение evaluate-вектора: ('result', doc) | ('error', {'error': {...}}). |
Modules
argumentationПрофиль structured argumentation §274.1–§274.7 (law.argumentation/0.2,constants§54: разыменование ссылок на константы пакета перед исполнением.constraintsNon-derivational constraints §93.1–§93.3 (errata E-0086).defeasibleL1: defeasible/defeater, приоритеты и defeat — SPEC §104–§115.documentМанифест входа §170 и канонический документ результата §208.editions§92.3: применимость редакции на дату права — проекция §31 ВНУТРИ evaluate.effectsEffect materialization §127–§128 — второй шаг power-runtime.engineКонвейер вычисления: порядок фаз и запуск вектора.eventsСобытие как исполнимое значение — SPEC §79.1, §81.1, §82.1 (DECISION-0156).evidenceAcceptance-фаза EvidencePolicy — SPEC §78.1/§78.2, DECISION-0126.factsФакты дела в support: приём, ключи, замыкание домена.focusfocused_truth — полнота относительно вопроса (SPEC §181.3, DECISION-0368).interpretationsInterpretations §152–§157 — выбор альтернатив и изоляция теорий.limitsСемантические лимиты — SPEC §238.normconflict§105.1/§105.2: конфликт нормативных ПОЗИЦИЙ — образцы, доказательство, исход.normsL2: жизненный цикл норм — SPEC §134–§143 (DECISION-0003).precedentПрофиль прецедента §276.1–§276.9 (law.precedent/0.2, DECISION-0090).preparedПодготовленная программа: анализы, зависящие только от IR, — один раз на объект.proceduresСвёртка истории процедур — SPEC §160.1–§164.2, §180.2, §201.1 (DECISION-0156).proofРеестр proof-узлов — SPEC §180.queriesВетви запроса: результат и корневой proof-узел на каждый вид query.query_shapeФорма ВОПРОСА до вычисления — errata E-0102 (§172, spec/schema/query.schema.json).rulesСтатический анализ правил, общий для strict и defeasible замыканий.solverРешатель: подстановка, свёртка термов и перебор — SPEC §103/§190/§204.strictStrict closure — SPEC §103, и temporal scope правила — §87.supportПара поддержки (t, f) на ground-атом — SPEC §61–§63.whynot§185 why_not(P) — blocker graph вида «тело правила не выполнено».
ACCEPTED_ORIGINSattributemodule attribute#
lawref.evaluator.factsView sourceACCEPTED_ORIGINS = {'case_input', 'source_asserted', 'external_snapshot', 'adjudicated', 'derived'}NORM_STDattributemodule attribute#
lawref.evaluator.normsView sourceNORM_STD = 'urn:law:std#'SCHEMA_VERSIONattributemodule attribute#
lawref.evaluator.documentView sourceSCHEMA_VERSION = 'law.core.evaluation/0.1'EvaluationRequestclassdataclass#
lawref.evaluator.engineView sourceclass EvaluationRequest(ir: dict, case: dict, query: dict, calendar_resource: bytes | None = None, external_snapshots: tuple[dict, ...] = tuple(), receipt: dict | None = None, semantic_version: str = '', editions_as_presented: str | None = None, proof_graph: bool = True)Типизированный единственный вход evaluation (DECISION-0111 §2.2).
Семантические options живут только в case["options"]. Calendar,
external snapshots и receipt — transport-поля запроса и не входят в
caseHash. Неизвестный верхнеуровневый ключ wire-формы отклоняет схема.
calendar_resourceattributeclass attributeinstance attribute#
calendar_resource: bytes | None = Nonecaseattributeinstance attribute#
case: dicteditions_as_presentedattributeclass attributeinstance attribute#
editions_as_presented: str | None = Noneexternal_snapshotsattributeclass attributeinstance attribute#
external_snapshots: tuple[dict, ...] = field(default_factory=tuple)irattributeinstance attribute#
ir: dictproof_graphattributeclass attributeinstance attribute#
proof_graph: bool = Truequeryattributeinstance attribute#
query: dictreceiptattributeclass attributeinstance attribute#
receipt: dict | None = Nonesemantic_versionattributeclass attributeinstance attribute#
semantic_version: str = ''buildmethodclassmethod#
def build(ir: dict, case: dict, query: dict, options: dict | None = None, external_snapshots: list[dict] | tuple[dict, ...] | None = None, *, semantic_version: str | None = None, editions_as_presented: str | None = None) -> 'EvaluationRequest'Собрать typed request из внутренних объектов хоста.
options здесь — лишь адаптер старых хостовых переменных на
единственное нормативное место case.options. Несемантические
calendar/receipt извлекаются из него и в caseHash не попадают.
Если хост не передал версию явно, она наследуется из закреплённого IR.
Отозванная ветвь 0.1 отклоняется по обеим осям: ни IR, ни явная
версия request не могут вернуть её в active evaluation.
Публичная граница исполнения всё равно одна: evaluate(request).
from_dictmethodclassmethod#
def from_dict(document: dict) -> 'EvaluationRequest'from_wire_bytesmethodclassmethod#
def from_wire_bytes(raw: bytes) -> 'EvaluationRequest'Build a request from the exact bytes admitted to the verdict cache.
The cache key is safe only when this method itself parsed raw into
the object passed to validation. Object callers use :meth:from_dict.
EvaluationRequestErrorclass#
lawref.evaluator.engineView sourceclass EvaluationRequestError(detail: str)Bases: ValueError
LimitExceededclass#
lawref.evaluator.limitsView sourceclass LimitExceeded(counter: str, limit: int)Bases: Exception
§238: превышение семантического лимита — детерминированный отказ RESOURCE_LIMIT.
ProofRegistryclass#
lawref.evaluator.proofView sourceclass ProofRegistry(assertions: dict[str, dict])Единый реестр proof-узлов: support-id → proof-node-id (детерминированно).
assertionsattributeinstance attribute#
assertions = assertionsby_supportattributeinstance attribute#
by_support: dict[str, str] = {}last_application_idattributeinstance attribute#
last_application_id: str | None = Nonenodesattributeinstance attribute#
nodes: list[dict] = []add_applicationmethod#
def add_application(rule_id: str, seq: int, subst: dict[str, dict], conclusion: dict, premises: list[str]) -> strannotate_a3_applicationmethod#
def annotate_a3_application(rule: dict, calls: Iterable[dict] = ()) -> NoneAttach A3 row provenance to the just-created ordinary rule proof.
annotate_definition_applicationmethod#
def annotate_definition_application(rule: dict) -> NoneDECISION-0151 / §180: применение правила, порождённого определением
§144, несёт attributes.definition — понятие (символ-цель ребра
provenance), режим, половину и номер альтернативы. Объяснение §183
читает это поле и говорит «по определению», а не «по правилу».
В content-id узла §180 поле не входит: тождество применения —
правило, подстановка, посылки и вывод.
for_supportmethod#
def for_support(support_id: str) -> strSupportStoreclass#
lawref.evaluator.supportView sourceclass SupportStore()apply_countersattributeinstance attribute#
apply_counters: dict[str, int] = {}atomsattributeinstance attribute#
atoms: dict[str, dict] = {}closures_doneattributeinstance attribute#
closures_done: set[str] = set()derived_seenattributeinstance attribute#
derived_seen: set[tuple[str, bytes]] = set()derived_type_errorsattributeinstance attribute#
derived_type_errors: set[tuple[str, str, int, str]] = set()dnegativeattributeinstance attribute#
dnegative: dict[str, list[str]] = {}dpositiveattributeinstance attribute#
dpositive: dict[str, list[str]] = {}negativeattributeinstance attribute#
negative: dict[str, list[str]] = {}norm_countersattributeinstance attribute#
norm_counters: dict[str, int] = {}norm_seenattributeinstance attribute#
norm_seen: set[tuple[str, bytes]] = set()positiveattributeinstance attribute#
positive: dict[str, list[str]] = {}predicate_versionsattributeinstance attribute#
predicate_versions: dict[str, int] = {}rule_stampsattributeinstance attribute#
rule_stamps: dict[str, int] = {}sig_aliasesattributeinstance attribute#
sig_aliases: dict[str, str] = {}sig_basesattributeinstance attribute#
sig_bases: dict[str, str] = {}sig_constantsattributeinstance attribute#
sig_constants: dict[str, str | None] = {}signaturesattributeinstance attribute#
signatures: dict[str, list[tuple[str, str | None]]] = {}stampattributeinstance attribute#
stamp: int = 0stampsattributeinstance attribute#
stamps: dict[str, int] = {}term_errorsattributeinstance attribute#
term_errors: set[tuple[str, str]] = set()warned_rulesattributeinstance attribute#
warned_rules: set[str] = set()accepted_positive_keysmethod#
def accepted_positive_keys(predicate: str) -> list[str]Ключи атомов предиката, у которых есть ВХОДНАЯ positive-опора (assertion или strict-вывод), в возрастающем порядке ключа.
Отличие от established_positive — не фильтр статуса, а сторона:
§45.1/§196 смотрят на positive, как halt E-0001 и closure §70, и
defeasible-опоры (dpositive) в счёт не идут. Индекс _by_predicate
держит объединение сторон, поэтому отбор по positive остаётся.
Множество и порядок те же, что давал sorted(self.positive) с отбором
по предикату: порядок ключей тотален, и фильтрация глобально
отсортированной последовательности совпадает с сортировкой
отфильтрованного подмножества (тот же аргумент, что у индекса выше).
addmethod#
def add(literal: dict, assertion_id: str) -> Noneadd_defeasiblemethod#
def add_defeasible(literal: dict, proof_id: str) -> Noneconflictsmethod#
def conflicts() -> list[str]Ключи атомов с одновременной accepted-поддержкой обеих полярностей.
established_positivemethod#
def established_positive(predicate: str, bound: tuple[tuple[int, bytes], ...] = (), min_stamp: int = -1) -> list[dict]established_sidemethod#
def established_side(literal: dict) -> list[str]Опоры БЕЗ defeasible (§107 правило 1: только strict/assertions побеждают кандидата безусловно).
status_onlymethod#
def status_only(literal: dict) -> strsupport_sidesmethod#
def support_sides(literal: dict) -> tuple[list[str], list[str]]supported_positivemethod#
def supported_positive(predicate: str, bound: tuple[tuple[int, bytes], ...] = (), min_stamp: int = -1) -> list[dict]Ground-атомы предиката с ЛЮБОЙ positive-опорой (§65 supported —
монотонный перечислитель: BOTH не исключается; §103 разрешает
рекурсию строгих правил только через такие рёбра). min_stamp ≥ 0 —
только атомы, получившие опору позже этого штампа (semi-naive);
подсписок того же упорядоченного списка, порядок цел.
term_bytesmethod#
def term_bytes(term: dict) -> bytestruth_statusmethod#
def truth_status(literal: dict) -> tuple[str, list[str]]UnsupportedLanguageVersionErrorclass#
lawref.evaluator.engineView sourceclass UnsupportedLanguageVersionError(version: str)Bases: EvaluationRequestError
LDC-E1401 на evaluation boundary для отозванной семантики.
codeattributeclass attributeinstance attribute#
code = 'UNSUPPORTED_LANGUAGE_VERSION'diagnostic_codeattributeclass attributeinstance attribute#
diagnostic_code = 'LDC-E1401'messageattributeinstance attribute#
message = revision.withdrawn_evaluation_message(version)evaluatefunction#
lawref.evaluator.engineView sourcedef evaluate(request: EvaluationRequest) -> dictПубличная граница исполнения (DECISION-0111 §2.2).
Отчёт acceptance-фазы §78.2.7 вкладывается ЗДЕСЬ, одним владельцем на все
девять ветвей запроса: _evaluate кладёт его в sink, а attach_acceptance
вкладывает и пересчитывает resultHash. Без выбранной политики sink
пуст и документ возвращается тем же объектом — байты прежние (§78.2.8).
literal_keyfunction#
lawref.evaluator.supportView sourcedef literal_key(literal: dict) -> strrun_vectorfunction#
lawref.evaluator.engineView sourcedef run_vector(vector_dir, layer: str | None = None, semantic_version: str | None = None) -> tuple[str, dict]Исполнение evaluate-вектора: (‘result’, doc) | (‘error’, {‘error’: {…}}).
Артефакты: ir.json (hand-authored CLIR до появления парсера M3 — G-M1b заменит их выходом компилятора), case.json (интерим-JSON вместо .lawcase до M3), query.json, calendar.resource.json (для calendar_op), expected.json.
Documentation for Arxo. Writings — blog.arxo.io.
Anonymous visit counts on stats.arxo.io, no cookies.