Skip to content

impl(070): extraction rules 2 contract: the /2 document, rules_first with required, and the skipped request outcome (increment 1) - #577

Merged
bartekus merged 1 commit into
mainfrom
impl/070-inc1
Nov 8, 2026
Merged

bartekus merged 1 commit into
mainfrom
impl/070-inc1

Conversation

@bartekus

@bartekus bartekus commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Spec 070 (rustev.extract-rules/2, #572), increment 1 of 3: the contract. Based on main after #574 (the spec) and #568 (0.7.0).

What changes

  • rustev-contract: ExtractRules reads rustev.extract-rules/1 and /2 with one type (versioned_document!, as definition, evidence and judgment do); its identity is tagged with the document's own schema, so every /1 identity is unchanged. Added for /2 (3.1): month_tables; conditions equals and one_of over a Scalar (string, integer, boolean); values token_after, token_matching (ShapeElement, ByteClass), date (DateFormat) and vocabulary_after. Every parse-time bound of 3.1.2 is checked; a /1 document holding any /2 member or variant is refused as an unknown member (3.1.3).
  • Fill::RulesFirst and the optional fallback.required (3.7.1); the plan 3 BoundExtractionFallback::Bound carries required only when declared (3.7.7, 3.10.1); ExtractionRequestOutcome::Skipped { reason: rules_filled } (3.9.1).
  • Schemas: rustev.extract-rules-1.schema.json keeps its bytes (the /2 members are removed from its emission and the test asserts it); rustev.extract-rules-2.schema.json is new; definition 1/2, plan 2/3, evidence 2 and run 3 regenerate with the added members; both bindings' declarations regenerate through gen-types (all review-excluded, checked by tests/schemas.rs and gen-types --check).
  • rustev-core (transitional, until increments 2 and 3): bind refuses each /2 construct and compilation refuses rules_first, category invalid_extraction, "not supported by this build"; required is checked now (only with rules_first, 1 to 32 distinct declared top-level fields; 3.5.6).
  • Tests: crates/rustev-contract/tests/extract_rules_2.rs (round trips, /2 identity, /1 refusal of each /2 construct, every 3.1.2 bound and its maximum, required and skipped wire forms, /1 schema free of /2 members); two tests in crates/rustev-core/tests/extraction_compile.rs.
  • Spec 070: implementation: in-progress, increment 1 recorded.

Evidence

  • No golden, plan or PlanId changed (I-1); rustev.extract-rules-1.schema.json is byte-identical.
  • No new source file in a published crate (archive policy unchanged).
  • Local: contract suite, core extraction and golden suites, gen-types --check, make gate and spec-spine couple pass after the rebase; wasm 4,881,670 bytes raw in the earlier bindings run.

@bartekus bartekus added the statecraft:stacked-ci Run the full CI matrix on a stacked pull request label Nov 8, 2026
@bartekus
bartekus force-pushed the spec/070-extract-rules-2 branch from 667b2cf to 34542d3 Compare November 8, 2026 20:13
@github-actions

github-actions Bot commented Nov 8, 2026

Copy link
Copy Markdown

AI review (findings)

Reviewing the diff carefully for bugs, security problems, and inconsistencies against the governance context.

Lifecycle (specs/070-extract-rules-2/spec.md): pending → in-progress on an approved spec is a valid transition per the contract lifecycle table. No issue.

Schema versioning / tagged identity (extraction_documents.rs): The id() override uses tagged_digest(&self.schema, ...), so a /1 document produces the same identity it always had and a /2 document produces a schema-scoped identity. Correct.

v2-member rejection in /1 documents: The validate() check in ExtractRules and both v2_member() helpers traverse All/Any/Not and Record recursively. The extract_rules_v1 schema emitter removes each added key and asserts the removal count matches — a compile-time safety net. Both look correct.

shape() minimum-length guard: min_len is u32; maximum possible value is 16 elements × 16 min-repeat = 256 — no overflow. The guard min_len == 0 correctly catches an all-min=0 shape; the test covers it.

Scalar untagged ordering: JSON booleans, integers, and strings are distinct JSON types; serde tries Bool → Integer → Text in declaration order and fails cleanly on floats (tested with 1.5). The BTreeSet distinctness check in one_of uses the derived Ord, which treats cross-variant comparisons as unequal — Integer(1) and Text("1") are distinct, confirmed by the accepted [1, "1", true] test case.

required compile-time check: The check runs before the rules_first refusal, so the validated → refused ordering is correct; tests cover all branches.

Unreachable arms in extraction_eval.rs and extraction_fallback.rs: Skipped in eval and the stub None returns for v2 value arms in fallback are defended by the bind-time refusal of v2 constructs; acceptable for an incremental approach.

One concrete defect found:

In extraction_documents.rs, the error message produced when a month table does not have exactly 12 entries reads:

return Err(format!("month table {name} has 12 entries"));

This fires precisely when months.len() != 12, so the message asserts that the table has 12 entries at the moment it is being rejected for not having them. A consumer seeing this error (e.g. when providing 11 months) will receive a message that says the table already has 12 entries, which is the opposite of the problem. The validation logic itself is correct; only the diagnostic text is wrong.

{"head": "f1256c6acbb82a233c5ae9afa1ab7442b1d2d10a", "verdict": "findings", "findings": [{"path": "crates/rustev-contract/src/extraction_documents.rs", "line": null, "severity": "low", "category": "correctness", "summary": "The error message `\"month table {name} has 12 entries\"` fires when the table does not have 12 entries, telling the caller the opposite of the actual problem; it should read something like \"must have exactly 12 entries\"."}]}

Subject: 34542d3...f1256c6, diff digest f57ca7fe9666a097ad4db6fc4c44aefb03b1aad788da1ff48b106b48acc5a4b8, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus temporarily deployed to statecraft-review-exception November 8, 2026 20:19 — with GitHub Actions Inactive
@bartekus
bartekus force-pushed the spec/070-extract-rules-2 branch from 34542d3 to 353d41f Compare November 8, 2026 20:21
@bartekus

bartekus commented Nov 8, 2026

Copy link
Copy Markdown
Contributor Author

Head ec4dc1a (rebased onto the spec at 353d41f):

  • Fixed CI's clippy large_enum_variant on BoundExtractionFallback (the plan's program is now Box<ExtractRules>; wire and schema bytes unchanged).
  • Fixed the AI review finding: the month-table errors now say "must have exactly 12 entries" and "must have 1 to 4 names".
  • Local: make code on the previous head passed apart from one rustev-otel tests/sink.rs timing assertion under load (unrelated to this change; it passes on rerun, 16/16). After the fixes: workspace clippy -D warnings clean; rustev-contract and rustev-core full suites pass; gen-types --check passes; make gate passes.

@github-actions

github-actions Bot commented Nov 8, 2026

Copy link
Copy Markdown

AI review (findings)

Reviewing the diff for bugs, security problems, and inconsistencies against the governance context and the stated intent of spec 070 increment 1.

Review

Scope and lifecycle

specs/070-extract-rules-2/spec.md advances implementation from pending to in-progress with status: approved. Under the contract table (approved + in-progress = schedulable), this is a valid lifecycle transition. The spec is approved, so ratification is an owner act that the review neither grants nor confirms; no inconsistency is visible in the supplied evidence.

New types and validation (extraction_documents.rs)

Scalar untagged enum — Bool declared before Integer. With serde's untagged, true/false match Bool before Integer is tried; integers match Integer only. Order is correct.

printable_byte — 0x21–0x7E inclusive, one-byte string; multi-byte UTF-8 or out-of-range bytes are None. Range enforcement in classes() matches.

shape() minimum-length guard — accumulates u32 min contributions and rejects zero-length matches. Edge cases (all-zero min repeats, single OptionalSpace) are handled and covered by tests.

terms_v2 — delegates the upper-bound check to the pre-existing terms(). The acceptance test at exactly 64 items (json!(vec!["é".repeat(32); 64])) verifies terms() allows 64; the rejection test at 65 verifies it refuses 65. Consistent.

Month-table deduplication — to_ascii_lowercase() for case-insensitive dedup. Only ASCII letters are folded; non-ASCII bytes pass through unchanged, so "März" and "März" with identical bytes are caught while "März" and "Marz" are treated as distinct. Consistent with the character set restriction (only specific ASCII bytes forbidden).

extract_rules_v1 schema pruning — removes v2 members from the emitted v1 JSON Schema by key-matching properties. The assertion that exactly added.len() variants were removed (before - variants.len() == added.len()) makes the pruning auditable.

Identity override (Identified for ExtractRules)

The override tags the digest with self.schema, so a /1 document produces tagged_digest("rustev.extract-rules/1", ...) — the same value the previous default produced, satisfying spec 070, 3.10.1. The test every_version_1_construct_is_valid_in_version_2 asserts one.id() equals tagged_digest(schema::EXTRACT_RULES, ...). Correct.

Guard ordering in extraction_compile.rs

required() is checked before the rules_first guard. When fill == RulesFirst and required is out-of-range, required() correctly errors first. When required is valid but fill == RulesFirst, required() succeeds and the subsequent guard fires "not supported by this build." Test cases cover both paths.

v2-construct blocking in extraction_fallback.rs

v2_value recurses into Expr::Record, so constructs nested inside records are caught. v2_condition recurses into All/Any/Not. condition_sources and value_sources are updated for all new variants so that source-projection checks remain complete. The unreachable branches for v2 constructs in condition() / value() are consistent with the bind-time guard.

Box<ExtractRules> in BoundExtractionFallback

Box<T> serialises identically to T in serde_json, so the wire format is unchanged. The corresponding deref fix (**program).clone() in compile.rs is correct.


Finding

shape() error message is logically inverted (extraction_documents.rs)

if matches!(v.first(), Some(ShapeElement::OptionalSpace))
    || matches!(v.last(), Some(ShapeElement::OptionalSpace))
{
    return Err("optional_space is neither the first nor the last element".into());
}

The guard fires when OptionalSpace is the first or last element, but the message reads "is neither the first nor the last element" — describing the valid state rather than the violation. A caller receiving this error is told optional_space occupies neither boundary position, which is the opposite of what happened. The correct message would be something like "optional_space cannot be the first or last element."

{"head": "ec4dc1a96a11ef964081b337b4654cceb7d7c6d6", "verdict": "findings", "findings": [{"path": "crates/rustev-contract/src/extraction_documents.rs", "line": null, "severity": "low", "category": "correctness", "summary": "The shape() validation error message 'optional_space is neither the first nor the last element' is logically inverted: it describes the valid state, but fires when OptionalSpace IS the first or last element, misleading callers about the actual constraint violation."}]}

Subject: 353d41f...ec4dc1a, diff digest e42c8a599ff7c0ae3a795878f0a36dad5615c9a9a0251cf052786dcff5d36506, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus temporarily deployed to statecraft-review-exception November 8, 2026 20:35 — with GitHub Actions Inactive
@bartekus
bartekus force-pushed the spec/070-extract-rules-2 branch 2 times, most recently from db10414 to 34b8f6f Compare November 8, 2026 20:36
@github-actions

github-actions Bot commented Nov 8, 2026

Copy link
Copy Markdown

AI review (no-findings)

Reviewing the diff across all twelve changed paths.

Contract types (extraction.rs, extraction_documents.rs, extraction_results.rs, lib.rs)

  • Scalar uses #[serde(untagged)] with Bool before Integer before Text; JSON booleans and numbers are distinct wire types so no ambiguity exists. BTreeSet deduplication in one_of is correct because Scalar derives Ord with discriminant ordering.
  • BoundExtractionFallback::Bound.program is boxed; the double-deref in compile.rs ((**program).clone()) is correct given the match binds by reference.
  • The /1 document validation in ExtractRules::validate correctly checks month_tables, then recurses into when/then via v2_member(). required on ExtractionRules (plan-level config, not the document) is unrelated — no /1 document field is missed.
  • occurrence refactor to a shared helper is correct; DateIso and Date share the same 1–2 bound.

Schema emission (schema_emit.rs)

  • extract_rules_v1 removes all v2 members and asserts the removed count equals the added-key count; correct at generation time. The /2 schema is emitted from the full struct without adjustment.

Compile-time checks (extraction_compile.rs)

  • required is validated before the rules_first rejection, which surfaces the more specific error first. The BTreeSet-based duplicate check is correct; any with set-insert side effect is well-defined in Rust.
  • bind in extraction_fallback.rs checks field rules for v2 constructs but not for month_tables alone. A /2 document with only month_tables (no Date or other v2 values) would bind; month_tables without any referencing Date rule is dead data, not incorrect behavior, since any Date construct is independently caught.

Runtime stubs (extraction_eval.rs, extraction_fallback.rs)

  • unreachable!() covering Skipped is semantically correct: this arm is reached only when producing an absent-field reason, and Skipped signals rules resolved the fields (not absent). Both Succeeded and Skipped are equally impossible in this context.
  • Condition::Equals | OneOf => Err(Reason::SourceUnavailable) and Expr::TokenAfter | … => None are dead paths guarded by bind; the safe fallbacks are appropriate.
  • condition_sources / value_sources correctly add v2 source-name extraction for future increments; the additions are dead code for this build but not incorrect.

Spec lifecycle (specs/070-extract-rules-2/spec.md)

  • pending → in-progress on an approved spec is a valid transition per the contract table; the spec is schedulable at both states.

Tests (tests/extract_rules_2.rs, tests/extraction_compile.rs)

  • Round-trip, refusal, and schema-content tests cover the stated bounds. The local_maxima_are_accepted test confirms boundary values parse. Cross-version identity tagging is verified.

No concrete defects found.

{"head": "da66512877097f5adbfcda6fca9c889f64711c0b", "verdict": "no-findings", "findings": []}

Subject: 34b8f6f...da66512, diff digest 1d344533f54e051437245ad1e5e61678c5cb63cee7dc6080241709520c02f694, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus force-pushed the spec/070-extract-rules-2 branch from 34b8f6f to 1bd58b5 Compare November 8, 2026 20:59
Base automatically changed from spec/070-extract-rules-2 to main November 8, 2026 21:53
@bartekus
bartekus enabled auto-merge November 8, 2026 21:57
@github-actions

github-actions Bot commented Nov 8, 2026

Copy link
Copy Markdown

AI review (findings)

Review of head 3c45fdd2c751e3772378ac6839b41c7979139232

Lifecycle change

specs/070-extract-rules-2/spec.md moves implementation from pending to in-progress. Spec 070 is approved; both pending and in-progress are schedulable states for an approved spec (contract.md lifecycle table). The change accurately reflects that increment 1 is partially landed. No ratification concern.

Contract layer (rustev-contract)

  • Versioned-document macro accepting two schemas, identity overridden to tag with self.schema (spec 070, 3.1.1 / 3.10.1): correctly implemented and tested.
  • extract_rules_v1 strips every v2 member from the emitted /1 schema via expect/assert_eq!; these panics fire at schema-generation time and are caught by the the_version_1_schema_holds_no_version_2_member test. No runtime risk.
  • Scalar is #[serde(untagged)] with Bool before Integer; JSON true/false deserialize as Bool, integers as i64, floats (1.5) and null are rejected. Test coverage confirms all four cases.
  • Month-table duplicate detection is ASCII-case-insensitive (to_ascii_lowercase), which is correct for the ASCII-only letter set that passes the byte filter; multi-byte UTF-8 continuation bytes are not filtered by ASCII character class checks, allowing "März" etc. as intended.
  • Boxing BoundExtractionFallback::Bound.program to Box<ExtractRules> and the compensating (**program).clone() in compile.rs:478 are correct.

Core layer (rustev-core)

  • required validation in extraction_compile.rs runs before the rules_first guard, correctly ordering the checks (test cases show both orderings verified).
  • The v2_condition / v2_value guards in extraction_fallback.rs::bind recurse into All/Any/Not and Record respectively, so nested v2 constructs are caught.
  • Source-tracking match arms in condition_sources and value_sources are updated for all new types. ✓

Low-severity inconsistency: dead-code defensive arms

In extraction_fallback.rs, the two defensive arms reached only if bind's v2 guard somehow fails use different mechanisms:

  • Conditions (Equals, OneOf): return Err(Reason::SourceUnavailable) (extraction_fallback.rs, around line 255)
  • Values (TokenAfter, TokenMatching, Date, VocabularyAfter): => None (around line 318)

Both produce an absent field, but through different code paths. unreachable!() would be a more defensive choice for genuinely dead code, and would surface any regression in the guard rather than silently producing absent fields. This cannot be triggered given the bind guard, so the severity is low.

{"head": "3c45fdd2c751e3772378ac6839b41c7979139232", "verdict": "findings", "findings": [{"path": "crates/rustev-core/src/extraction_fallback.rs", "line": 318, "severity": "low", "category": "correctness", "summary": "Dead-code defensive arms for v2 value types return None (silent absent field) while the equivalent condition arms return Err(Reason::SourceUnavailable); both are guarded by the bind check but unreachable!() would surface any future regression in that guard."}]}

Subject: 706a5de...3c45fdd, diff digest c2cee9eea70b52f288c616c4df35f4012f779807e8ac0395c82a85d1cd55635c, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus had a problem deploying to statecraft-review-exception November 8, 2026 22:01 — with GitHub Actions Error
…with required, and the skipped request outcome (increment 1)
@github-actions

github-actions Bot commented Nov 8, 2026

Copy link
Copy Markdown

AI review (no-findings)

Reviewing the diff against spec 070 and the governance documents.

Spec lifecycle change (specs/070-extract-rules-2/spec.md line 5): pending → in-progress on an approved spec. This is a valid lifecycle transition per the contract table; no owner ratification is required.

Contract types (crates/rustev-contract/src/extraction_documents.rs): The new Scalar, ByteClass, ShapeElement, and DateFormat types are consistent with spec 070 §3.1–3.3. Scalar uses #[serde(untagged)] with variants in order Bool → Integer → Text; serde_json's bool deserializer rejects numeric input, so 1 correctly maps to Integer(1) and not Bool. Floats and null fall through all three arms and are refused, matching the test cases.

Validation bounds (extraction_documents.rs): All checked against the test cases in extract_rules_2.rs:

  • terms_v2: 1–64 non-empty terms of 1–64 bytes — correct.
  • classes: 1–8 entries, range requires two single printable-ASCII bytes with lo ≤ hi — correct.
  • shape: 1–16 elements, optional_space banned at first/last, minimum length ≥ 1 — correct. The min=0,max=4 single-element shape is correctly refused because min_len stays 0.
  • occurrence: 1–2, using screening::present to refuse explicit null — correct.
  • month_tables: case-insensitive cross-month duplicate detection, name pattern [a-z][a-z0-9_]{0,15}, 12 entries per table, 1–4 names per month — correct.
  • /1 document with any /2 construct in fields or month_tables is refused as unknown member — consistent with spec 070 §3.1.3.

Incremental bind guard (crates/rustev-core/src/extraction_fallback.rs): v2_condition and v2_value walk nested All/Any/Not/Record correctly and refuse /2 constructs before the plan is committed. condition and value eval arms for the new variants return Err(Reason::SourceUnavailable) rather than unreachable!() — a safe defensive posture consistent with the incremental strategy.

required and rules_first ordering (extraction_compile.rs): required() runs first (validates names against declared top-level fields, 1–32 distinct), then the hard refusal of rules_first fires. The test fixture walks all six failure cases including duplicate names and undeclared field names.

Boxing of ExtractRules (extraction_results.rs): The BoundExtractionFallback::Bound.program field is boxed; the deref in compile.rs ((**program).clone()) is correct.

Tagged identity (extraction_documents.rs): The Identified::id override uses tagged_digest(&self.schema, …), which differentiates /1 and /2 documents with identical content. The implementation note says "No golden, plan or PlanId changed," consistent with the spec requirement that the /1 identity is preserved.

Skipped arm in extraction_eval.rs: Grouped with Succeeded under unreachable!(). Since bind refuses rules_first, no plan in this build produces a skipped outcome; the grouping is correct.

No concrete defects found.

{"head": "42a418a2b87e443f2a7da04db921153e8ae1c9d6", "verdict": "no-findings", "findings": []}

Subject: 706a5de...42a418a, diff digest 22f63b86a7f8d9249a5b3c012afe31cd6ceff82034f18f5ce7bd3d800e292076, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus added this pull request to the merge queue Nov 8, 2026
Merged via the queue into main with commit cb12bdf Nov 8, 2026
49 checks passed
@bartekus
bartekus deleted the impl/070-inc1 branch November 8, 2026 23:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

statecraft:stacked-ci Run the full CI matrix on a stacked pull request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant