Skip to content

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

NameDescription
ACCEPTED_ORIGINSNo description.
NORM_STDNo description.
SCHEMA_VERSIONNo description.

Classes

NameDescription
EvaluationRequestТипизированный единственный вход evaluation (DECISION-0111 §2.2).
EvaluationRequestErrorNo description.
LimitExceeded§238: превышение семантического лимита — детерминированный отказ RESOURCE_LIMIT.
ProofRegistryЕдиный реестр proof-узлов: support-id → proof-node-id (детерминированно).
SupportStoreПара поддержки (t, f) на ground-атом (SPEC §62); стороны хранятся раздельно (§61).
UnsupportedLanguageVersionErrorLDC-E1401 на evaluation boundary для отозванной семантики.

Functions

NameDescription
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#

ACCEPTED_ORIGINS = {'case_input', 'source_asserted', 'external_snapshot', 'adjudicated', 'derived'}

NORM_STDattributemodule attribute#

NORM_STD = 'urn:law:std#'

SCHEMA_VERSIONattributemodule attribute#

SCHEMA_VERSION = 'law.core.evaluation/0.1'

EvaluationRequestclassdataclass#

class 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 = None

caseattributeinstance attribute#

case: dict

editions_as_presentedattributeclass attributeinstance attribute#

editions_as_presented: str | None = None

external_snapshotsattributeclass attributeinstance attribute#

external_snapshots: tuple[dict, ...] = field(default_factory=tuple)

irattributeinstance attribute#

ir: dict

proof_graphattributeclass attributeinstance attribute#

proof_graph: bool = True

queryattributeinstance attribute#

query: dict

receiptattributeclass attributeinstance attribute#

receipt: dict | None = None

semantic_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#

class EvaluationRequestError(detail: str)

Bases: ValueError

codeattributeclass attributeinstance attribute#

code = 'EVALUATION_REQUEST_INVALID'

messageattributeinstance attribute#

message = EvaluationRequest не соответствует evaluation-request.schema.json: {detail} (DECISION-0111 §2.2)

LimitExceededclass#

class LimitExceeded(counter: str, limit: int)

Bases: Exception

§238: превышение семантического лимита — детерминированный отказ RESOURCE_LIMIT.

codeattributeinstance attribute#

code = 'RESOURCE_LIMIT'

counterattributeinstance attribute#

counter = counter

limitattributeinstance attribute#

limit = limit

ProofRegistryclass#

class ProofRegistry(assertions: dict[str, dict])

Единый реестр proof-узлов: support-id → proof-node-id (детерминированно).

assertionsattributeinstance attribute#

assertions = assertions

by_supportattributeinstance attribute#

by_support: dict[str, str] = {}

last_application_idattributeinstance attribute#

last_application_id: str | None = None

nodesattributeinstance attribute#

nodes: list[dict] = []

add_applicationmethod#

def add_application(rule_id: str, seq: int, subst: dict[str, dict], conclusion: dict, premises: list[str]) -> str

annotate_a3_applicationmethod#

def annotate_a3_application(rule: dict, calls: Iterable[dict] = ()) -> None

Attach A3 row provenance to the just-created ordinary rule proof.

annotate_definition_applicationmethod#

def annotate_definition_application(rule: dict) -> None

DECISION-0151 / §180: применение правила, порождённого определением §144, несёт attributes.definition — понятие (символ-цель ребра provenance), режим, половину и номер альтернативы. Объяснение §183 читает это поле и говорит «по определению», а не «по правилу». В content-id узла §180 поле не входит: тождество применения — правило, подстановка, посылки и вывод.

for_supportmethod#

def for_support(support_id: str) -> str

SupportStoreclass#

class SupportStore()

Пара поддержки (t, f) на ground-атом (SPEC §62); стороны хранятся раздельно (§61).

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 = 0

stampsattributeinstance 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) -> None

add_defeasiblemethod#

def add_defeasible(literal: dict, proof_id: str) -> None

conflictsmethod#

def conflicts() -> list[str]

Ключи атомов с одновременной accepted-поддержкой обеих полярностей.

established_positivemethod#

def established_positive(predicate: str, bound: tuple[tuple[int, bytes], ...] = (), min_stamp: int = -1) -> list[dict]

Ground-атомы предиката со статусом TRUE_ONLY (established, §65/§66) — база для grounding строгих правил (§103). Порядок детерминирован. min_stamp — как у supported_positive.

established_sidemethod#

def established_side(literal: dict) -> list[str]

Опоры БЕЗ defeasible (§107 правило 1: только strict/assertions побеждают кандидата безусловно).

status_onlymethod#

def status_only(literal: dict) -> str

truth_status без списков опор: та же §62-проекция, §63-зеркало для negative-литерала. Байтам документа не виден — оба пути обязаны давать один статус (сверяется в selftest).

support_sidesmethod#

def support_sides(literal: dict) -> tuple[list[str], list[str]]

Стороны пары §62 литерала — опоры t и f, отсортированные; §63: у negative-литерала стороны зеркалятся. Одна сборка для truth_status и для составного условия цели (errata E-0218).

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) -> bytes

truth_statusmethod#

def truth_status(literal: dict) -> tuple[str, list[str]]

§62: (t,f) → TRUE_ONLY | FALSE_ONLY | BOTH | NEITHER; §63: запрос negative- литерала — это neg(t,f), т.е. статусы зеркалятся. Пары считаются по объединению established и surviving defeasible supports (§108/§111.7).

UnsupportedLanguageVersionErrorclass#

class 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#

def evaluate(request: EvaluationRequest) -> dict

Публичная граница исполнения (DECISION-0111 §2.2).

Отчёт acceptance-фазы §78.2.7 вкладывается ЗДЕСЬ, одним владельцем на все девять ветвей запроса: _evaluate кладёт его в sink, а attach_acceptance вкладывает и пересчитывает resultHash. Без выбранной политики sink пуст и документ возвращается тем же объектом — байты прежние (§78.2.8).

literal_keyfunction#

def literal_key(literal: dict) -> str

Ключ ground-атома: predicate + канонические args (полярность отдельно, §61–§62).

run_vectorfunction#

def 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.