diff --git a/.gitignore b/.gitignore index c923b2d393c..04798c956b1 100644 --- a/.gitignore +++ b/.gitignore @@ -202,3 +202,7 @@ src/v2/test/claim/manual/sg2_scratch_probe.dag /docs/plans/v2-complexity-capability-parity.md /docs/plans/v2-corpus-self-host.md /docs/plans/import-namespace-program.md + +# scratch probe corpora — never part of the tree under measurement +.probe_src/ +.probe_wt/ diff --git a/ROADMAP.md b/ROADMAP.md index 648a4e1b962..ce13b146b47 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -13,65 +13,14 @@ The graph has sixteen lanes: SCM compatibility · namespace · P-derive · obser **Focused view — the compute fabric + the infrastructure stabilisation lanes + fleet convergence from main.** 106 active deliverable(s) in other lanes are declared in the authority and hidden here; nothing is deleted or parked by focusing. Clear `roadmap_focus_selection` in `dag/gunbc/roadmap/roadmap_authority.dag` to restore the full page. 6 of the rows below are NOT lane deliverables — they are prerequisites pulled in from other lanes because lane work is blocked on them: observation-scoped-run-consumer, observation-scoped-run-seed-growth-justification, observation-scoped-run-seed-growth-justification-closing-contract, shell-gate-migration, shell-effectplan-to-bash, shell-typed-invocation. Hidden lanes remain readable through their carriers: [docs/plans/dag-scm-design.md](docs/plans/dag-scm-design.md) · [docs/plans/namespace-unique-on-chain-operational-plan.md](docs/plans/namespace-unique-on-chain-operational-plan.md) · [docs/plans/v2-self-hosting.md](docs/plans/v2-self-hosting.md) · [src/v2/compiler/05_emit.dag](src/v2/compiler/05_emit.dag) · [docs/plans/progress-observation-design.md](docs/plans/progress-observation-design.md) · [src/v2/compiler/self_host/candidate_generation.dag](src/v2/compiler/self_host/candidate_generation.dag) · [src/v2/compiler/self_host/wet_receipt_enrollment.dag](src/v2/compiler/self_host/wet_receipt_enrollment.dag) · [src/v2/compiler/self_host/v2_emitter_direct_rust_door_contract.dag](src/v2/compiler/self_host/v2_emitter_direct_rust_door_contract.dag) · [dag/gunbc/v1/v1_deletion_plan.dag](dag/gunbc/v1/v1_deletion_plan.dag) · [dag/gunbc/stage0/stage0_rust_host_observation.dag](dag/gunbc/stage0/stage0_rust_host_observation.dag) · [docs/plans/witness-realization-plan.md](docs/plans/witness-realization-plan.md) · [src/v1/05_emit_rust.dag](src/v1/05_emit_rust.dag) · [dag/gunbc/v1/v1_interpreter_primitive_surface.dag](dag/gunbc/v1/v1_interpreter_primitive_surface.dag) · [docs/plans/shell-to-dag-residual-census-and-arc-completion.md](docs/plans/shell-to-dag-residual-census-and-arc-completion.md) · [docs/plans/roadmap-workspace-ux-plan.md](docs/plans/roadmap-workspace-ux-plan.md) · [docs/plans/provider-control-interface-audit.md](docs/plans/provider-control-interface-audit.md) · [docs/plans/enforcement-intent-design.md](docs/plans/enforcement-intent-design.md) · [docs/plans/hermetic-tool-provisioning-design.md](docs/plans/hermetic-tool-provisioning-design.md) · [dag/gunbc/capability_binding.dag](dag/gunbc/capability_binding.dag) · [dag/gunbc/roadmap/roadmap_component.dag](dag/gunbc/roadmap/roadmap_component.dag) · [dag/gunbc/design_document.dag](dag/gunbc/design_document.dag) · [docs/plans/compiler-guarantee-recovery-gap-analysis.md](docs/plans/compiler-guarantee-recovery-gap-analysis.md) · [docs/plans/cardinality-refinement.md](docs/plans/cardinality-refinement.md). - [ ] **Describe what a command should do, instead of writing shell text** — Callers say which operation and which arguments; nobody hands over an opaque string of shell as the instruction. Why: Shell syntax embedded in decision-making code cannot be checked before it runs, and cannot be reused anywhere else. [authority](docs/plans/shell-to-dag-residual-census-and-arc-completion.md) - - [ ] **Turn a described plan into shell through one translator** — One place turns a described plan into a shell script, preserving order, captured output, and failure behaviour. Why: Deletes the per-workflow shell writers and the scripts assembled by gluing strings together. [authority](docs/plans/shell-to-dag-residual-census-and-arc-completion.md) - - [ ] **Move the build and commit checks onto described plans** — The checks choose described operations and the translator produces the shell; the shell pasted into workflow files stops being a separate source of truth. Why: Lets us test what a check does before it runs, and use it outside of GitHub Actions. [authority](docs/plans/shell-to-dag-residual-census-and-arc-completion.md) - [ ] **Write the closing check for: Account for the five hand-written files that progress output still needs** — One executable check states when this is done, transcribed from the node's own bar: Any new hand-written code for this outside those five files, or without this plan, is refused. The plan: Move this reach-through into a described operation, then hollow out the corresponding part of the command-line tool so generated code does the work; the hand-written bridge is deleted at that point. Why: Turns a prose bar into a runnable verdict, so the node it gates can be dispatched and its completion checked rather than judged. [authority](dag/gunbc/plans/cli_run_hollowing_plan.dag) - - [ ] **Account for the five hand-written files that progress output still needs** — Showing progress while a command runs still relies on hand-written code, in exactly these five files and no others: dag/gunbc/observation_seed_render.dag; dag/test/claim/observation_seed_scoped_run_witness_test.dag; src/v1/stage0/src/cli_run.rs; src/v1/stage0/src/v1_interpreter.rs; src/v1/stage0/tests/scoped_run_observation.rs Why: Why it is needed: Showing progress while a command runs has to reach the point where the old runner starts a program. It needs to know which piece of code was chosen, hold back error output until it can be shown in the right order, and report exactly one ending — and the rules for all of that live in the substrate, not in Rust. [authority](dag/gunbc/plans/cli_run_hollowing_plan.dag) - - [ ] **Show honest progress while a command runs** — Running a command announces that it started and reports exactly one ending. In a terminal it updates in place; piped to a file it appends plain lines. Why: Progress is printed raw today, so a terminal shows a mess and a log file shows something different again. [authority](docs/plans/progress-observation-design.md) - - [ ] **Get the full list of build jobs before deciding where they run** — Assemble all 48 jobs by stable identity and refuse if any is missing, duplicated, or has never been measured. Why: Deciding placement from a partial list produces a confident answer to the wrong question. [authority](docs/plans/ci-two-tier-placement-redesign.md) - - [ ] **Measure both machines instead of assuming they are alike** — Each kind of job earns the right to run on a machine by being measured there, warmed up, with its time and resource use recorded. Why: Assuming the two machines are interchangeable is how work lands on the one that cannot do it well. [authority](docs/plans/ci-two-tier-placement-redesign.md) - - [ ] **Run the new placement alongside the old one and compare** — Both make a decision for the same jobs; they must agree before the new one takes over. The new one does not control anything yet. Why: Finds disagreements while they are harmless instead of after they have moved real work. [authority](docs/plans/ci-two-tier-placement-redesign.md) - - [ ] **Switch over in one step and delete the old path** — A single change makes the new placement the only one and removes the shadow and the old selector together. Why: Ends the period where two things decide placement and nobody is sure which one acted. [authority](docs/plans/ci-two-tier-placement-redesign.md) - - [ ] **Derive the process, compiler and memory limits from one envelope per machine** — Shared compilation runs in its own managed place rather than inside whichever job slot happened to start it. How many processes a slot may hold, how wide the compiler may fan out, and how much memory the shared pool may take are all derived from one declared envelope for that machine instead of being three numbers anyone can set independently. Every limit is read back as the machine actually holds it. Why: The immediate outage — jobs unable to start processes against a cap far below the packaged one — and the fault behind it, where every machine's cache-miss compiles are charged to one job slot's budget and on one machine a retired slot's, are both consequences of these limits being separately writable. Two distinct failure kinds were charged to whatever code happened to be under test for a whole day: jobs dying unable to start a process at all, and jobs killed from an outer budget while sitting far under their own — across four independent measurements at 8.8 percent of the visible limit, with the peak identical on every attempt. Neither is a defect in any change under review, and both arrive looking exactly like one. [authority](docs/plans/srvn-buildcache-provisioning-design.md) - [ ] **Write the closing check for: Serve every required CI operation with the bare minimum computation; five minutes is the distress ceiling, not the contract** — One executable check states when this is done, transcribed from the node's own bar: A sub-lane that widens to whole-corpus work, silently falls through from an incomplete materialization artifact to cold recompute, or claims the five-minute envelope without Stage C fleet receipts refuses rather than greens. Why: Turns a prose bar into a runnable verdict, so the node it gates can be dispatched and its completion checked rather than judged. [authority](docs/plans/five-minute-ci-gate-design.md) - - [ ] **Serve every required CI operation with the bare minimum computation; five minutes is the distress ceiling, not the contract** — Every required operation performs only the computation its inputs require — no semantic fact recomputed whose inputs did not change (re-anchored by operator ruling 2026-08-02: five minutes is the distress ceiling — the Stage C checkpoint bound, not the contract). Sub-lanes (unordered roster — dispatch order follows the graph edges): #7522 warm-merge-admission net receipt; #7534 materialization substrate; union closed → per-entry assembly; the mechanism chain (discovery snapshot, scoped substrate, early selection, streaming); this registration. THE NATIVE ROW NO LONGER PRECEDES THIS GATE (2026-08-10): that edge is deleted, so this gate is schedulable without waiting on a self-host frontier. Why: MEASURED DECOMPOSITION, which relocates the whole lane: a 3,290s floor is 1,422s discovery/setup, 690s scoped worker, and 97s of actual witness evaluation. CI is not running tests — it is repeatedly reconstructing an understanding of the repository so that millisecond tests can run. Three consequences follow and each is a row rather than an opinion: ordinary and scoped discovery duplicate the same walk at 295.7s + 284.3s; selection is sharp about meaning and blunt about cost, deciding what matters only AFTER roster, index and closure are already paid for; and cache hits are effectively all-or-nothing, one missing typed key costing 82-96 percent of a full cold symbol-index build. The unit being reused is too small — values are cached while the world that gives them meaning is rebuilt. [authority](docs/plans/five-minute-ci-gate-design.md) - - [ ] **Admit merges from warm stamped receipts, not cold recomputation** — #7522 in flight (dispatch order follows the graph edges): fold resolve and materialization receipt gates into merge admission so the pull-request path stamps once and admits from warm receipts. Operator expectation: probable net recovery ~1–1.5 min (not ~3 min) — final-head run decides; not transcribed as receipt until measured. Why: Merge admission and the floor tail currently pay separate cold paths for facts already fixed when the run started. [authority](docs/plans/five-minute-ci-gate-design.md) - - [ ] **Recompute only the edited module and its semantic dependents** — NEXT (sequence step 4, #7534 continues): shared materialization substrate — hierarchy module parse/type/interface → resolved entry → selected native witness bundle. No default CI savings credited until ordinary invocations consume hits. FIRST RUNG: exact-tree cross-process cache (#7534, opt-in) — verified serve, not default CI activation. Why: Cross-entry typed-module work is repeated today even when module inputs are byte-identical across entries in one process. [authority](docs/plans/five-minute-ci-gate-design.md) - - [ ] **Probe materialization before corpus-scale index construction** — NEXT: a small persistent manifest lets a warm materialization hit occur before building the shared entry index and source-loading closure — serve and dashboard currently construct the index first and only then discover the cache. Why: Warm hits that still pay corpus index construction reproduce the measured startup outage on real dashboard entries. [authority](docs/plans/five-minute-ci-gate-design.md) — requires all: five-minute-ci-gate, module-grain-materialization - - [ ] **Share one initialized substrate across regen, floor, and admission** — NEXT: regen, floor, and admission run in one initialized process with phase boundaries and separate verdicts — regen still gates floor. NOT flattening into ordinary batches; duplicate prelude work is the target. Why: Each phase currently cold-starts its own substrate — paying resolve, index construction, and discovery more than once per pull request. [authority](docs/plans/five-minute-ci-gate-design.md) — requires all: five-minute-ci-gate, ci-scoped-worker-shared-substrate - - [ ] **Decompose per-entry assembly after the shared-typecheck hypothesis closed** — NEXT (sequence step 5, narrow lane): after #7533 closed entry-graph-union on zero repeated typecheck misses, attribute and reduce per-entry assembly/reconcile work — the remaining compiler term on the floor path. Why: Assembly and reconcile rows still scale with entry count even when typecheck is already shared across entries in one index. [authority](docs/plans/five-minute-ci-gate-design.md) — requires all: five-minute-ci-gate, module-grain-materialization - - [ ] **One ledger for what the CI-speed work actually bought** — One row per attempt made across this arc: what it predicted, what it changed, the exact subject it was measured on, the movement inside its own segment, the movement in the whole required path, whether memory stayed inside the fixed envelope, and a typed result — delivered, partial, falsified, confounded by infrastructure, or evidence invalid — with what each one implies next. Rows are read out of receipts that already exist; nothing is re-measured to fill this in. Why: Weeks of work bought real causal knowledge and several correctly killed hypotheses, but the required path is not meaningfully shorter. Without this ledger the next programme re-runs the attempts already falsified, and re-argues the ones that were only confounded by a machine failure. [authority](docs/plans/ci-performance-tanking-evidence.md) - - [ ] **Compile the compiler once per change, not once per job** — One expensive compiler build per change under test. Small checks stop dragging the whole compiler into a second build profile in order to run a few milliseconds of assertions: work that only observes the tree gets a small target that does not rebuild the monolith. Why: Building and testing is now the largest single cost of getting a change in, and a measured run spent minutes of compiler builds to execute a fraction of a second of checks. [authority](docs/plans/ci-performance-tanking-evidence.md) - - [ ] **Walk the corpus once and let both workers read the same result** — One complete discovery result is produced once and consumed by the second worker, instead of the same walk happening again in another process. It carries the whole typed result, never a pass-or-fail flag. A consumer that finds it absent, damaged, or belonging to a different subject refuses; it never quietly recomputes. Why: The ordinary worker and the scoped worker each perform effectively the same full walk in separate processes, and the second one measures around 284 seconds. It is the clearest several-minute target on the required path, and it is the first real use of computing something once and reusing it rather than a description of one. [authority](docs/plans/cross-worker-typecheck-share-design.md) — requires all: ci-cost-arc-reconciliation, module-grain-materialization - - [ ] **Stop building a second compiler world in order to run twenty-seven witnesses** — The scoped worker consumes an already-initialised substrate, or runs as a later stage inside the ordinary one, rather than constructing its own sources, indexes and environments. Staying in its own process remains allowed: isolation means separate mutable scratch and its own lifetime, never recomputing facts that are already fixed and immutable. Why: The scoped worker executes twenty-seven witnesses and pays for a whole second world to do it. The process boundary is being used as a way of handing memory back, and a cold start is the price currently paid for that. [authority](docs/plans/cross-worker-typecheck-share-design.md) - - [ ] **Decide what matters before paying to prepare everything** — Which computations a change affects is decided from source and module facts, ahead of broad roster, index, grouping and closure preparation. Only the views that decision actually needs are then prepared. Why: Selection is already sharp about meaning and blunt about cost: it can correctly conclude that most of the corpus is irrelevant, but only after the corpus has been discovered, named, rostered and indexed. The saving it reports is real while the work it claims to have avoided has largely already been done. [authority](docs/plans/ci-selection-vs-scheduling.md) - - [ ] **Start running as soon as the first thing is ready** — Preparation stops being a barrier standing in front of execution. A module's facts becoming ready makes an entry view ready, which makes a witness ready, which runs — while everything else is still being prepared. Why: Several hundred seconds are currently spent preparing every selected entry before the first one executes. That is a barrier, not work that had to finish first. [authority](docs/plans/floor-prep-tax-program.md) — requires all: ci-selection-before-preparation, ci-scoped-worker-shared-substrate - [ ] **Write the closing check for: Name the v2 self-host frontier that native witness execution actually requires, and close it stage by stage** — One executable check states when this is done, transcribed from the node's own bar: A member reported as a frontend GAP whose refusal is actually normalize's own retention contradicting itself refuses the classification — the two populations are separated by reading the rejection reason as a containment read, never by the first reason rendered, because rejected_with_pending prepends accepted-carrier diagnostics to a later rejection and the FIRST reason is systematically wrong. A cohort claimed as reaching Accepted whose closure contains no Accepted member refuses. A repair asserted separable from a description, without a cherry-pick onto main executed green, refuses. Why: Turns a prose bar into a runnable verdict, so the node it gates can be dispatched and its completion checked rather than judged. [authority](docs/plans/five-minute-ci-gate-design.md) - - [ ] **Name the v2 self-host frontier that native witness execution actually requires, and close it stage by stage** — STOPPED AND RE-CUT (operator ruling 2026-08-10, superseding the 2026-08-08 one-PR mandate this row carried). #8043/#8080 attempted the complete cutover in one PR and is closed as quarry; the row survives because the CAPABILITY is real and the SCOPE was wrong. Root, in the operator's words: v2 native execution entails a real self-host frontier and must be named as such, not carried as a CI-performance step. The frontier is gunbc.roadmap_authority native_selected_witness_bundle_frontier_note (historical) and native_selected_witness_bundle_exact_head_recut_note (current). Why: The stopped lane still paid for itself twice. It produced two merged frontend repairs (#8114: arrow-lambda grammar admission, and the graft dissolution guard — main accepted hollow-shell modules until it landed, proven by reverting only namespace_graft.dag and watching both RED witnesses fail), and it produced the frontier table that replaced an eleven-item guess with a three-item program — a table since superseded by the 2026-08-11 exact-head re-observation, under which the split is four normalize members and two independent lex walls, not five and three. What it disproved is equally load-bearing: this row no longer parents five-minute-ci-gate, because witness EVALUATION is 97s of a 3,290s floor — an infinitely fast evaluator leaves 97 percent of the floor standing, so native execution was never the CI-cost lever and CI cost must not wait on a self-host frontier. [authority](docs/plans/five-minute-ci-gate-design.md) - - [ ] **V2-LENS-0: every registered v2 lens executes over one exact corpus subject through the CI2 route** — BLOCKED, AND THE BLOCK IS HONEST (2026-08-10): the former trigger, CI2-0 terminal acceptance, is unreachable because that lane is stopped and its one-PR shape retired. This row keeps its dependency on the native row deliberately rather than being re-anchored around it: its own handback demands ZERO v1 lens-body executions, which is native execution by definition, so relaxing the trigger would only move the frontier into the handback. The underlying concern is DESIGN section 6's and does not expire with the lane: an inert lens is coverage by illusion. Residue, roster derivation and the per-lens execution contract are gunbc.roadmap_authority v2_lens_suite_execution_block_note. Why: Registry completeness proves metadata coherence, not execution: many LensContract rows carry NoConsumerWitness, and an inert lens is coverage by illusion. Binary acquisition, not lens logic, was the recurring execution failure; #8054 proved a whole-corpus query executes and its expense is corpus-fact construction, not lens evaluation. [authority](docs/plans/five-minute-ci-gate-design.md) - [ ] **Write the closing check for: Stop re-walking the string to read one character** — One executable check states when this is done, transcribed from the node's own bar: Identical output over the corpus is the equivalence half and is satisfied by changing nothing, so it does not stand alone: a long literal mixing non-ASCII text with escapes must separate the two implementations by cost, and a deliberately wrong escape decode must change the output. Why: Turns a prose bar into a runnable verdict, so the node it gates can be dispatched and its completion checked rather than judged. [authority](docs/plans/inner-cost-lanes-scoping.md) - - [ ] **Stop re-walking the string to read one character** — One function in the tokenizer still reads a string by counting from the start each time, while the rest of its file was already moved onto a pre-decoded form. Move it too, and collect its result into one buffer instead of a list of one-character pieces. Why: For text that is entirely plain ASCII this costs one allocation per character. For text containing any non-ASCII character at all, reading position N costs N steps and asking how long the string is re-counts the whole thing, on every pass — so the work grows with the square of the literal's length, and a single accented character anywhere flips the whole literal onto that path. [authority](docs/plans/inner-cost-lanes-scoping.md) - [ ] **Write the closing check for: One way to ask for work to be done, with the subject pinned exactly** — One executable check states when this is done, transcribed from the node's own bar: A request whose subject is a moving reference refuses. A provider that cannot serve the requested class of operation refuses before running rather than quietly answering a smaller question. The five endings stay five — a machine that killed the work cannot render as the work having failed. Why: Turns a prose bar into a runnable verdict, so the node it gates can be dispatched and its completion checked rather than judged. [authority](dag/gunbc/fabric/fabric_ci_program.dag) - - [ ] **One way to ask for work to be done, with the subject pinned exactly** — A request names the exact tree it applies to, the operation, the inputs it declares and the outputs it promises, the toolchain and environment it needs, its resource envelope, and which providers may serve it. The answer is one of a fixed set of endings: succeeded, failed, refused by the infrastructure, cancelled, or refused because what came back did not match the outputs declared. A branch name or a working directory is not a subject. Why: Building, checking, regenerating, changing machines, serving models and eventually judging changes are each growing a separate way of asking for work to be done. Four execution systems means four queues, four retry rules, four ideas of what success means, and nowhere to say where a piece of work actually ran. [authority](dag/gunbc/fabric/fabric_ci_program.dag) - - [ ] **Work that cannot hand back what it produced has not succeeded** — Every output a computation declared comes back identified by its content, with its size and what produced it, through a manifest the caller can read. Whether those bytes are then copied into a working tree is a separate and explicit step. Work that produces files may only run where its outputs can be returned; a provider that cannot return them offers checking only, and refuses producing work before it starts rather than after. Why: A remote run finished successfully and produced nothing locally; the stale binary left behind was then compared against itself and reported no difference. Every remote build in this environment currently has that shape, and it is silent. [authority](dag/gunbc/fabric/fabric_ci_program.dag) - - [ ] **Contain the remote build wrapper to its safe subset, then retire it into the compute contract** — This row is a migration, not a home. Until outputs can be handed back, the wrapper admits exactly one remote mode — checking something without producing anything the local tree then needs — and refuses any invocation that would write. Every result names the source it checked and the executable it checked with, so a stale local artefact can never stand in for a remote answer. When the compute contract can return outputs, the wrapper's remaining useful behaviour becomes one provider behind it and the wrapper is deleted rather than extended. Why: There is no stated rule for when this wrapper is the right thing, so it gets guessed at; a remote run meant to produce files can finish successfully having produced nothing locally, and that has already been consumed as a passing check. Every day it stays unclassified, more work is authored against a boundary that means two contradictory things. [authority](docs/plans/ci-process-end-to-end.md) - - [ ] **Identical work runs once and is handed to everyone who asked for it** — Two requests naming the same computation are the same work: one producer runs and everyone else attaches to its result as a consumer. The fabric decides what may run — how many cold builds a machine carries at once, what the compile pool's total demand may be, which host serves a request, and what order competing work is served in — and tells a caller which of those it is waiting on. A caller never starts something merely because it cannot tell whether somebody else is already producing it. Why: Ten agents needing the same binary for the same tree currently means ten builds, because nothing lets one of them discover the other nine. Moving the present arrangement onto our own machines WITHOUT this multiplies the load instead of sharing it, which is why this row comes before more consumers rather than after them. [authority](dag/gunbc/fabric/fabric_ci_program.dag) — requires all: compute-exact-work-contract, compute-artifact-return-and-materialization - - [ ] **Run the required checks on our own machines, from a subject we hold ourselves** — Seeing a new commit creates a durable piece of work of our own, identified by the exact base, head, and combined commit under test. One machine holds it under a lease for the whole run, and the run ends in one typed result we keep. Starting, queueing and handing out the work involve no third-party workflow and no registered runner. The old floor is quarry and shadow oracle, not the template: obligations port only when a disagreement proves they carry a real property, and its batches, ordering, settlement and status vocabulary are not inherited. Why: Starting, queueing, handing out, cancelling and reporting all belong to someone else today. When their side has a bad day our machines wedge, their re-runs test a stale combination, and every one of those failures arrives looking like a fault in our own code. [authority](dag/gunbc/fabric/fabric_ci_program.dag) — requires all: compute-exact-work-contract, compute-artifact-return-and-materialization, compute-deduplication-and-admission - - [ ] **The result shown on GitHub is a copy of ours, never the original** — Our stored result is published as the required check. No check present means not yet observed and never counts as satisfied. Cancelled, timed out, refused by the infrastructure, and genuinely failed stay four different things the whole way through. A queued merge is checked against the exact commit that queue built. If GitHub cannot be reached the publishing waits; the result itself is never lost. Why: NO LONGER A PREDICTION — three measured receipts, and the skew runs BOTH WAYS, so no single sign-correction fixes it. #7932 at 493de348 (2026-08-07): a CANCELLED required ci folded into PASS and the tally reported MERGE CRITERIA MET while GitHub held mergeStateStatus=BLOCKED. #8051 at b4a8d5d: two runs on one head, and the concurrency-cancelled one pinned checks_state at PENDING beside a SUCCESS row. #8059 (2026-08-10) is what that costs when the runners are also down — it merged on a cancelled run carrying a carrier rename whose call sites another merged PR had just added, putting 99 mechanically-detectable type errors on main across two files (18 SubstrateLongLaneRow fields, 81 uses of a HasTrigger constructor defined nowhere), so main could not derive its own generated artifacts and every PR adding an emitted module was blocked outright. Three sessions each found it believing their own branch was broken, and two independently wrote the same 81-row repair within a minute. A related trap on the same surface: mergeable: MERGEABLE is GitHub's conflict-freedom field, not a checks verdict, so it is never a second confirmation. None of this is a review gap and none of it is a review fix — every one of the 99 is a type error the compiler decides in milliseconds; the only thing that had to happen was for the checks to run. [authority](docs/plans/ci-process-end-to-end.md) — requires all: ci-owned-execution, ci-executed-coverage-receipt, ci-gate-contention-independent-verdict - - [ ] **Remove the hosted-runner path once we carry the required checks** — With our own path publishing the required checks, the workflow, the runner registrations and the recovery timer are removed together in one change, so there is never a period in which two things can hand out the same work. Why: Retires the vendor's dispatcher as something our fleet's health depends on — the reason the recovery timer has to exist at all, and the reason a bad day on their side becomes a wedged fleet on ours. [authority](docs/plans/ci-process-end-to-end.md) - [ ] **Write the closing check for: A check reports what it actually executed, not merely that it ran** — One executable check states when this is done, transcribed from the node's own bar: A run whose executed population is zero refuses rather than reporting either pass or fail. A failure ahead of the corpus is a different outcome from a corpus disagreement. A check that cannot say what it executed does not count as having executed. Why: Turns a prose bar into a runnable verdict, so the node it gates can be dispatched and its completion checked rather than judged. [authority](docs/plans/ci-process-end-to-end.md) - - [ ] **A check reports what it actually executed, not merely that it ran** — Every required check carries the population it executed — which witnesses, which corpus, how many — and a run that executed nothing cannot report a verdict of any kind. A build failure that stops the corpus from running is its own outcome, distinct from the corpus running and disagreeing. Why: A scheduled check spent days reporting failures while executing no corpus at all, because a step ahead of it failed and the result looked exactly like a real disagreement. Nobody could tell the difference from outside, so a genuine signal was ignored for days. [authority](docs/plans/ci-process-end-to-end.md) - [ ] **Write the closing check for: Host load cannot decide a semantic merge verdict** — One executable check states when this is done, transcribed from the node's own bar: Repeated runs of the same unchanged code land on the same semantic side. A timeout reports as ExecutionTimedOut or CoverageRefused, never as an assertion failure. Raising the limit, or moving the check somewhere it stops running per change, refuses as a way of closing this. A quiet-host pass is not accepted as the only evidence. Why: Turns a prose bar into a runnable verdict, so the node it gates can be dispatched and its completion checked rather than judged. [authority](docs/plans/ci-performance-tanking-evidence.md) - - [ ] **Host load cannot decide a semantic merge verdict** — A check that blocks merging decides something about the change. The semantic verdict derives from the executed assertion; a timeout or resource exhaustion is a distinct execution outcome, never projected into assertion failure, and never absorbed by widening the cutoff. Work that cannot fit its budget is decomposed or moved through the correct execution mechanism — the cutoff is not raised to admit it. Why: One check was measured ten times across four separate efforts with nothing in the code changing between them, and the readings ranged from well under its limit to well over it. It blocked one change outright, produced a false alarm on another whose own checks all passed, and sent three separate efforts hunting for a defect that was never there — an unchanged semantic subject passing or failing on host contention. [authority](docs/plans/ci-performance-tanking-evidence.md) - [ ] **Write the closing check for: One admission predicate that every commit writer must pass before it may write** — One executable check states when this is done, transcribed from the node's own bar: A merge with unmerged index entries refuses typed and located; the staged-marker-text variant refuses separately; an observation population that differs from the staged index refuses in both directions; a freely constructed provenance value whose path happens to match a staged file refuses; a clean tree admits. Why: Turns a prose bar into a runnable verdict, so the node it gates can be dispatched and its completion checked rather than judged. [authority](docs/plans/generated-file-conflict-policy.md) - - [ ] **One admission predicate that every commit writer must pass before it may write** — Admission consumes a complete staged-index observation whose population must equal the exact staged index, never a caller-selected list, with two independent refusal arms: any unmerged index stage refuses typed and located with the affected path, and the staged blobs are inspected for the complete conflict-marker grammar, so a file collapsed to stage zero with markers inside refuses. Text classification is observed, never caller-declared; a fixture exemption is a provenance receipt bound to the same staged path and blob, never a path allowlist. The pre-commit hook stays fast local feedback; the predicate at the writer's boundary is the enforcement. Why: An automated writer has already committed and pushed literal conflict-marker blocks to main by committing through an unresolved merge, and the refusing merge driver raised that class only to mechanically preventable — the repository's own config authority states that commit-writer admission remains the boundary a writer cannot pass. Until this lane lands, the other lanes shrink how many files can be caught by textual adjacency while every writer stays one absorbing fallback away from repeating the incident on the files that remain. [authority](docs/plans/generated-file-conflict-policy.md) - - [ ] **Stop writing the whole file registry into a generated file** — A generated artefact must not carry the full list of generated paths. The workflow asks Git which of the paths that actually conflicted are generated, reading that classification from both sides' committed state rather than from a list baked into the workflow text. Adding a generated file then changes the classification projection and leaves the workflow's own bytes alone. Why: One enormous line holding every generated path means any change to that population rewrites the same spot in a shared file, so two branches conflict over a list neither of them disagrees about. That has happened repeatedly, and each occurrence costs a manual resolution carrying no information. [authority](docs/plans/generated-file-conflict-policy.md) - - [ ] **Decide which generated files need to be in the repository at all** — For every generated file we commit, name the consumer that requires the bytes to be present: something outside reads it before our own tools can run, the build needs it to start at all, or a reviewer has to see the exact difference. Anything else is published or produced on demand instead of committed. Generated outputs that stay get their own directories, so what is generated is structural rather than a list someone maintains. Why: A large share of the merge pain comes from files nobody reads as bytes in the repository. Each one that leaves stops producing conflicts, review noise and drift checks permanently, rather than having its conflicts handled better. [authority](docs/plans/generated-file-conflict-policy.md) - [ ] **Write the closing check for: Write down which parts of our machines we actually manage** — One executable check states when this is done, transcribed from the node's own bar: An undeclared file, service, credential, or device refuses before anything is changed. Why: Turns a prose bar into a runnable verdict, so the node it gates can be dispatched and its completion checked rather than judged. [authority](docs/plans/host-converge-inventory.md) - - [ ] **Write down which parts of our machines we actually manage** — Every file, service, credential, and device is either derived by us, owned by us, or someone else's with an agreed contract. Anything unclassified refuses. Why: Shrinks the number of possible machine states our automation has to cope with. [authority](docs/plans/host-converge-inventory.md) - - [ ] **Manage the server firmware and cooling settings safely and repeatably** — Read the current firmware, board, fans, and temperature limits; plan a change, apply it, read it back, and roll back if anything looks wrong. Why: Replaces one-off manual fan tuning with something repeatable that checks itself. [authority](docs/runbooks/bmc-redfish-operator-access.md) - - [ ] **Change one machine setting and check it really changed** — State the desired setting, observe the current one, compare, apply, then independently read it back before calling it done. Why: Turns configuration that is merely written down into configuration that is actually applied and re-checkable. [authority](docs/plans/host-effect-orchestration.md) — requires all: fleet-state-frontier, shell-gate-migration - - [ ] **Keep re-checking, and notice things we did not put there** — Something runs periodically, re-observes everything we manage, and spots unmanaged state inside the areas we own. Why: Finds configuration drift and stale processes before the next deployment turns them into an incident. [authority](docs/plans/fleet-acceptance-criteria.md) - - [ ] **Only call the machines 'managed' once all of it has really run** — This closes when applying for real, reading back, re-running safely, undoing, and the periodic check have all actually happened. Why: Stops a tidy model or a single successful run from being mistaken for infrastructure you can rely on. [authority](docs/plans/fleet-acceptance-criteria.md) - - [ ] **A merge to main is the instruction, and nothing else applies it** — The state the machines should be in is the exact revision merged to main, held durably by whatever is applying it. A newer revision replaces an older one, an older or unrelated one refuses, and the same one again does nothing. The instruction survives a restart of the thing applying it and an outage at the hosting provider — an event from them may make it happen sooner but is never the only place the instruction lives. A machine that was unreachable or refused is tried again against the revision still held, with no new commit needed. Why: Every fleet-touching merge currently ends with the same question — is that actually on the machines — and the only way to answer it is to go and look. Somebody has to remember to apply things, and forgetting is invisible until it causes an incident. [authority](docs/plans/fleet-self-converge-enforcement-design.md) - - [ ] **The build machines' own limits and services converge from main like everything else** — The job slots' limits, where shared compilation runs, the recovery timer, and the values those actually take on each machine are all stated as desired state derived from main and converged everywhere. Editing the desired row and merging it is the whole operator action. Why: This is the configuration whose hand-drift produced the process-limit outage and left the shared build cache running inside a retired job slot. It is also the first subject worth proving the whole path on, because it is real, it is already wrong, and fixing it by hand is what created the drift. [authority](docs/plans/fleet-self-converge-enforcement-design.md) — requires all: fleet-main-revision-authority, fleet-atomic-convergence-verdict, placement-compile-pool-envelope, compute-exact-work-contract - - [ ] **Count every automatic job-runner recovery, and say what retires it** — The timer that restarts wedged job runners records each firing — which machine, which slot, what it observed, what it did, and whether it worked — and those counts reach the fleet's health. Deciding locally that a runner has stopped making progress is kept separate from asking the provider whether it is still registered, so recovery keeps working during the outage it exists for. Why: It fires roughly ten times a day across the fleet and nothing counts it, so the fleet looks healthy because something invisible is holding it up. The firing rate is the only thing separating a legitimate stopgap from a fault we have stopped noticing. [authority](docs/plans/fleet-self-converge-enforcement-design.md) - - [ ] **Bring the two new machines up as model-serving members, through the same path as everything else** — Both new machines join through the same standing-up sequence every other machine uses, reach a stated model and runtime, and serve requests on an endpoint. Which model is actually being served, and whether the endpoint is healthy, are read back independently, and each machine stays separately observable. They serve models — they are not job runners and not build caches. Why: Standing these up by hand would create two more machines nobody can answer questions about, which is the state this whole lane exists to end. Going through the convergence path also proves that path on a machine class it has never seen. [authority](dag/gunbc/spark/dgx_procurement.dag) — requires all: fleet-main-revision-authority, fleet-atomic-convergence-verdict, compute-exact-work-contract, fleet-spark-host-enrollment - - [ ] **One answer for the whole fleet, or exactly which machines are not there yet** — Each machine produces a receipt — what was wanted, what was there, what was planned, what was applied, and what was read back afterwards. Those fold into a single answer for the fleet, joined with the lifecycle cells enrollment constructs: every required host-and-phase cell is observed, refused, unreachable, drifted, or converged, and a required cell nobody has observed prevents convergence rather than defaulting green. Anything short of all of them is not converged, with the machines that refused, could not be reached, or have drifted each named separately. Why: One machine can hold the new value while the others hold the old one and nothing anywhere says so, which is exactly why the honest answer to whether something is applied is currently to go and check by hand. And the fleet phase matrix currently has exactly one real observation producer cell — one host, one phase, hard-coded — so every other lifecycle claim in the fleet is unobserved by construction; enrollment makes obligations countable, not satisfied. [authority](docs/plans/fleet-acceptance-criteria.md) - - [ ] **Deploy every copy of the dashboard through the one deployment mechanism** — Deploying a dashboard uses the same mechanism as everything else we deploy: work out what should be there, compare it to what is, and change only the difference. Which machine it goes to becomes a parameter, not a second copy of the logic. Why: There are currently two deployment engines for the same three files. The second one does not know what it owns, and reaches the machine outside the checked path — so it can tear down something that was never ours. [authority](docs/plans/gunbc-served-dashboard-design.md) - - [ ] **Serve the roadmap page from emitted native code, never the tree-walking interpreter** — The interpreted accept loop is a declared scaffold whose dissolution trigger has now fired in production: a two-hour page wedge, one core pinned in memcpy, thirteen connections queued behind a single thread. The fix is ordered. Wire roadmap_serve_handle through the existing emit-on-demand path FIRST — interpreted concat copies its accumulator on every call, quadratic; emitted concat moves, linear: a complexity-class change, not tuning. Then memoize page bodies by content hash of their inputs so a request is lookup-and-write. Concurrency only after bodies are immutable artifacts. A request deadline returns a typed refusal instead of eating the process. Why: The 2026-08-08 srv1 outage: gunbc serve wedged for two hours rendering the daily page, every route behind it dead, and it re-wedges on the next load of the same shape. The scaffold row already names emit-on-demand as its dissolution and the module carries zero references to it — declared and left standing. Separately, the belt reconcile has been dead as long as GcpProjectId has failed to resolve, burning about two minutes of CPU on every timer tick before exiting. [authority](docs/plans/gunbc-served-dashboard-design.md) - [ ] **Write the closing check for: Turn the two Spark machines from hand-managed boxes into exact fleet members** — One executable check states when this is done, transcribed from the node's own bar: A count witness multiplying enrolled hosts by the whole spine refuses — expected cells are the duplicate-free identity join of each enrollment's participation-derived program, and runner plus inference union exactly with no duplicated cell. An inference enrollment carrying BMC, OS-install, runner-slot, or build-cache obligations refuses. Changing one participation changes only the obligations that participation owns. An endpoint row re-typing the reserved address literal refuses; a reverse import into the network intent refuses. Any Spark cell presented as observed without a producer refuses. Why: Turns a prose bar into a runnable verdict, so the node it gates can be dispatched and its completion checked rather than judged. [authority](dag/gunbc/spark/dgx_procurement.dag) - - [ ] **Turn the two Spark machines from hand-managed boxes into exact fleet members** — srv5 and srv6 become fleet members: enrollment intents carrying InferenceServingParticipation, with endpoint rows derived downstream from the assigned reservation rows — re-typing the address literal refuses, a reverse import into the network intent refuses, and the join is a projection between the two existing authorities, never a second host-identity authority. Enrollment constructs their four required lifecycle cells — identity converge, reach, compute-fabric enrolment, assimilation complete — and every cell stays honestly Unobserved until an observation producer answers it. Enrolled is not converged: no identity convergence, reach satisfaction, capacity acceptance, or serving claim lives here. Why: Two machines are reserved, physically bound, and answerable by nobody: no fleet row knows they exist, so their state is whatever hands left there. The stale count witnesses still encode enrolled-hosts-times-whole-spine — every enrolled host presumed a runner, wrong since participation scoping landed and exposed by srv5. And the endpoint-derivation question already burned a session against an import cycle because the projection layer this row creates did not exist. [authority](dag/gunbc/spark/dgx_procurement.dag) - [ ] **Write the closing check for: Ask what depends on this exact thing, and get an explained, honest answer** — One executable check states when this is done, transcribed from the node's own bar: A query whose subject module does not exist refuses rather than answering empty. A planted unbound module appears in the standing, and no reading over a pool with unaccounted members reports itself closed. The result may not claim one-sided incompleteness while pool independence is unavailable — the standing carries the trigger. A second edge producer beside the declared single authority refuses. Forward-intent refusals (operator amendment 2026-08-08): a branch name without an exact revision is not a subject; a deleted declaration is never silently resolved against the head tree; an unresolved input never becomes an empty result; a partial universe cannot report that no relevant authority exists — no-matches and could-not-see-enough remain different answers. The deterministic layer never turns prose into repository identity: it returns the bounded universe, exact candidate declarations, consumers, explanation paths, and standing for a later mapper or judge. Why: Turns a prose bar into a runnable verdict, so the node it gates can be dispatched and its completion checked rather than judged. [authority](src/v2/lens/module_graph.dag) - - [ ] **Ask what depends on this exact thing, and get an explained, honest answer** — Given an exact graph subject and one or more semantic node identities, return direct and transitive dependencies or dependents, explanation paths, production and test consumers, and an explicit completeness standing. Git diffs, paths, line and column coordinates, and natural-language questions are adapters into this semantic query — they are not its identity grain. The reading consumes the existing single edge authority as data and never grows a second edge producer; where the finest grain is unavailable, the standing says so with its trigger rather than answering coarser and calling it fine. Why: Whether a concept already exists, who consumes it, what executes it, and what a deletion would break are today answered by grep, memory, or not at all — every session re-derives them, duplicates get minted beside existing authorities, and the reverse question is simulated with N forward closures. This deterministic layer is also the grounding packet the judgment service requires: without it, the machine judgement lane has nothing checkable to stand on. Acceptance standing (2026-08-08, post-rework): the reverse query is merged; the changed-surface rework closed departed-path consumption, the typed Complete/Partial/Refused outcome (unresolved input contaminates the whole result), the skip-authority wall (SkipAuthorityGranted reachable only from Complete AND exact), optional cycle analysis, the two-direction selector-parity control, and three real-diff receipts — one of which falsified a fixture assumption (git reports a deletion in both projections). OPEN: the base-graph population — a deleted subject resolves to typed BaseGraphUnavailable because every graph reader is head-only; building revision-scoped reading is an operator decision (new seed Rust or a heavy checkout). Measured correction: cycles were 28 percent of the wall, not most — the dominant cost is resolve and fact production. [authority](src/v2/lens/module_graph.dag) - - [ ] **Find subjects that may deserve one shared abstraction by how they are constructed and consumed** — Given an exact graph subject, a semantic universe, and a named lens over construction, consumption, effects, tests, lifecycle, or presentation, group observationally equivalent subjects into grounded abstraction candidates. The result is DESCRIPTIVE evidence only: it mints no authority, rewrites no code, and never decides a quotient is valid — similarity under a lens is evidence; 'these should share one authority' is a separate normative ruling crossing that bridge explicitly. Every candidate names its universe, lens, equivalent observations, the distinctions the quotient would erase, nearby authorities, the consumers that would use it, and its over-collapse and demand standing. Why: The grouping move — five things consumed the same way become one new layer — is how this repository forms layers at all, and today it happens only when a person notices: duplicates get minted beside existing authorities, boutique implementations accumulate until a consolidation pays the fork back at interest, and the judgment of which lens a similarity holds under is re-derived by hand every time. The candidate that is NOT an abstraction is half the value: the Spark endpoint question burned a session on topology surgery that a projection-missing classification — join the existing authorities downstream, mint nothing — would have answered in one line. [authority](src/v2/lens/module_graph.dag) diff --git a/dag/extdeps/bmc/types.dag b/dag/extdeps/bmc/types.dag index 6b7be354b77..ea93195a1b2 100644 --- a/dag/extdeps/bmc/types.dag +++ b/dag/extdeps/bmc/types.dag @@ -177,12 +177,13 @@ fn bmc_redfish_surface_for( ) -> BmcRedfishSurfaceDerivation { let matches = bmc_redfish_surface_matches(catalog: catalog, firmware: firmware) let count = list_length(matches) - if count == 0 { - SurfaceShapeUncatalogued { firmware: firmware } - } else if count == 1 { - SurfaceShapeKnown { shape: matches.first().shape } - } else { - SurfaceShapeAmbiguous { firmware: firmware, matches: count } + match matches.first() { + Absent => SurfaceShapeUncatalogued { firmware: firmware } + Present { value: only_or_first } => + match matches.skip(n: 1).first() { + Absent => SurfaceShapeKnown { shape: only_or_first.shape } + Present { value: _ } => SurfaceShapeAmbiguous { firmware: firmware, matches: count } + } } } diff --git a/dag/extdeps/container/oci/digest.dag b/dag/extdeps/container/oci/digest.dag index d8f9aa26e7a..55b66e7df20 100644 --- a/dag/extdeps/container/oci/digest.dag +++ b/dag/extdeps/container/oci/digest.dag @@ -185,11 +185,19 @@ fn oci_wire_digest_parts(raw: String) -> OciWireDigestParts? { if length(parts) != 2 { none } else { - Present { - value: oci_wire_digest_parts_from_split( - algorithm: parts.first(), - encoded: parts.skip(n: 1).first(), - ) + match parts.first() { + Absent => none + Present { value: algorithm } => + match parts.skip(n: 1).first() { + Absent => none + Present { value: encoded } => + Present { + value: oci_wire_digest_parts_from_split( + algorithm: algorithm, + encoded: encoded, + ) + } + } } } } diff --git a/dag/extdeps/container/oci/manifest.dag b/dag/extdeps/container/oci/manifest.dag index b69c8b83e7d..b78b01cbe2e 100644 --- a/dag/extdeps/container/oci/manifest.dag +++ b/dag/extdeps/container/oci/manifest.dag @@ -60,23 +60,16 @@ fn accept_image_manifest(m: ImageManifest) -> ManifestOutcome { } } -fn layer_at(layers: List, index: Int) -> OciDescriptor? { - match layers |> get(index) { - null => null - other => other - } -} - fn accept_image_manifest_layers(m: ImageManifest, index: Int) -> ManifestOutcome { if index >= count(m.layers) { ManifestAccepted { value: m } } else { - match layer_at(m.layers, index) { - null => + match m.layers |> get(index) { + Absent => ManifestRejected { reason: LayerMissing { index: index }, } - layer => + Present { value: layer } => match accept_descriptor(layer) { DescriptorRejected { reason } => ManifestRejected { diff --git a/dag/extdeps/github/expressions.dag b/dag/extdeps/github/expressions.dag index 13f5d036c75..80141d1db51 100644 --- a/dag/extdeps/github/expressions.dag +++ b/dag/extdeps/github/expressions.dag @@ -318,13 +318,17 @@ fn parse_function_call_atom(s: String, sp: ExpressionSpellings) -> Expression? { } else { after } - match function_from_name(name: segs.first()) { + match segs.first() { + Absent => none + Present { value: head_seg } => + match function_from_name(name: head_seg) { Absent => none Present { value: fn_variant } => match parse_args_with(args_str: args_str, sp: sp) { Absent => none Present { value: args } => Present { value: FunctionCall { function: fn_variant, args: args } } } } + } } } @@ -341,9 +345,13 @@ fn parse_function_call_atom(s: String, sp: ExpressionSpellings) -> Expression? { fn parse_context_access_atom(s: String, sp: ExpressionSpellings) -> Expression? { let dotted = replace(replace(s, sp.index_open, sp.path_sep), sp.index_close, "") let segs = split(s: dotted, delimiter: sp.path_sep) - match context_from_name(name: segs.first()) { + match segs.first() { Absent => none - Present { value: ctx } => Present { value: ContextAccess { context: ctx, path: segs.skip(n: 1) } } + Present { value: head_seg } => + match context_from_name(name: head_seg) { + Absent => none + Present { value: ctx } => Present { value: ContextAccess { context: ctx, path: segs.skip(n: 1) } } + } } } @@ -363,13 +371,17 @@ fn parse_expression_with(s: String, sp: ExpressionSpellings) -> Expression? { if parts.length() == 1 { parse_atom_with(s: s, sp: sp) } else { - fold(parts.skip(n: 1), init: parse_atom_with(s: parts.first(), sp: sp), f: (acc, part) => match acc { + match parts.first() { Absent => none - Present { value: left } => match parse_atom_with(s: part, sp: sp) { - Absent => none - Present { value: e } => Present { value: LogicalOr { left: left, right: e } } - } - }) + Present { value: head_part } => + fold(parts.skip(n: 1), init: parse_atom_with(s: head_part, sp: sp), f: (acc, part) => match acc { + Absent => none + Present { value: left } => match parse_atom_with(s: part, sp: sp) { + Absent => none + Present { value: e } => Present { value: LogicalOr { left: left, right: e } } + } + }) + } } } @@ -383,8 +395,10 @@ fn ingest_expression(src: String) -> Expression? { fn ingest_template_with(src: String, sp: ExpressionSpellings) -> ExpressionTemplate? { let parts = split(s: src, delimiter: sp.interp_open) - let lead = parts.first() - let lead_segs = if lead == "" { [] } else { [ LiteralText { text: lead } ] } + let lead_segs = match parts.first() { + Absent => [] + Present { value: lead } => if lead == "" { [] } else { [ LiteralText { text: lead } ] } + } let built = fold(parts.skip(n: 1), init: Present { value: lead_segs }, f: (acc, part) => match acc { Absent => none Present { value: sofar } => { @@ -393,7 +407,10 @@ fn ingest_template_with(src: String, sp: ExpressionSpellings) -> ExpressionTempl none } else { let trailing = join(halves.skip(n: 1), sp.interp_close) - match parse_expression_with(s: halves.first(), sp: sp) { + match halves.first() { + Absent => none + Present { value: head_half } => + match parse_expression_with(s: head_half, sp: sp) { Absent => none Present { value: e } => { let with_interp = concat(sofar, [ Interpolation { expression: e } ]) @@ -402,6 +419,7 @@ fn ingest_template_with(src: String, sp: ExpressionSpellings) -> ExpressionTempl } } } + } } } }) diff --git a/dag/extdeps/languages/html.dag b/dag/extdeps/languages/html.dag index 411aeaf6a0c..87290d00ee2 100644 --- a/dag/extdeps/languages/html.dag +++ b/dag/extdeps/languages/html.dag @@ -195,16 +195,34 @@ fn parse_attrs_with(attrs_str: String, sp: MarkupBracket) -> HtmlAttrFoldState { }) } +// THE Absent ARMS BELOW ARE UNREACHABLE, AND THEY REFUSE RATHER THAN SUBSTITUTE. +// Every optional here is `split(...).first()`, and `split` cannot return an empty +// list -- on the empty string it returns [""] -- so Absent cannot occur. That +// non-emptiness is a property of split's IMPLEMENTATION that its return type +// `List` does not carry, which is exactly why these positions are diagnosed at +// all: nothing enforces the property the code relies on. +// +// The arms therefore refuse instead of substituting a plausible value. The choice +// is only free while the unreachability argument holds, so it is made for the case +// where that argument is WRONG -- a reimplemented split, a different producer, a +// caller passing something that is not a split result. A refusal stops the line +// loudly and located; a fabricated empty value would be the absorbing fallback +// (DESIGN 5). Dissolves when split's return type carries non-emptiness AND these +// callers consume it -- see gunbc.guarantee_stall split_non_emptiness_unmodelled_stall. fn parse_one_with(s: String, sp: MarkupBracket) -> HtmlParseOneResult { if starts_with(s: s, prefix: sp.end_tag_open) { ParseOneRejected { reason: "unexpected end tag" } } else if starts_with(s: s, prefix: sp.tag_open) { let open_chunks = split(s: s, delimiter: sp.tag_close) - let open_content = open_chunks.first() + match open_chunks.first() { + Absent => ParseOneRejected { reason: "unterminated open tag" } + Present { value: open_content } => let after_open_tag = html_strip_prefix(s: s, prefix: join([open_content, sp.tag_close], "")) let tag_and_attrs = html_strip_prefix(s: open_content, prefix: sp.tag_open) let tag_parts = split(s: tag_and_attrs, delimiter: sp.attr_sep) - let tag = tag_parts.first() + match tag_parts.first() { + Absent => ParseOneRejected { reason: "open tag names no element" } + Present { value: tag } => let attrs_raw = join(tag_parts.skip(n: 1), sp.attr_sep) let attr_result = parse_attrs_with(attrs_str: attrs_raw, sp: sp) if attr_result.rejected { @@ -221,10 +239,17 @@ fn parse_one_with(s: String, sp: MarkupBracket) -> HtmlParseOneResult { } } } + } + } } else { - let text_raw = split(s: s, delimiter: sp.tag_open).first() - let rest = html_strip_prefix(s: s, prefix: text_raw) - ParsedOne { node: FragmentText { content: unescape_text(s: text_raw) }, rest: rest } + match split(s: s, delimiter: sp.tag_open).first() { + Absent => ParseOneRejected { reason: "no text content before tag open" } + Present { value: text_raw } => + ParsedOne { + node: FragmentText { content: unescape_text(s: text_raw) }, + rest: html_strip_prefix(s: s, prefix: text_raw), + } + } } } diff --git a/dag/extdeps/languages/markdown.dag b/dag/extdeps/languages/markdown.dag index b5ced2007e3..2fc8a523629 100644 --- a/dag/extdeps/languages/markdown.dag +++ b/dag/extdeps/languages/markdown.dag @@ -460,9 +460,20 @@ fn md_parse_code(block_lines: List) -> MarkdownBlock { } } +// THE Absent ARM IS UNREACHABLE AND, UNIQUELY HERE, CANNOT REFUSE. `lines` is a +// `split` result and split cannot return an empty list, so Absent cannot occur -- +// a property of split's implementation that its `List` return type does not +// carry. Elsewhere in this population the unreachable arm refuses; it cannot here, +// because MarkdownBlock declares no refusal variant and md_parse_block is total, +// so refusing would mean changing the return type of every caller. The arm +// therefore routes to the same ParagraphBlock fallthrough the function already +// produces when nothing else matches. Rostered as the weakest member of +// gunbc.guarantee_stall split_non_emptiness_unmodelled_stall. fn md_parse_block(block_src: String, sp: MarkdownSpellings) -> MarkdownBlock { let lines = split(s: block_src, delimiter: "\n") - let first = lines.first() + match lines.first() { + Absent => ParagraphBlock { inlines: md_parse_inline_rest(text: block_src, sp: sp) } + Present { value: first } => if starts_with(s: block_src, prefix: sp.code_fence) { md_parse_code(block_lines: lines) } else if md_is_heading(line: first, sp: sp) { @@ -477,6 +488,7 @@ fn md_parse_block(block_src: String, sp: MarkdownSpellings) -> MarkdownBlock { ParagraphBlock { inlines: md_parse_inline_rest(text: block_src, sp: sp) } } + } } fn ingest_markdown_source_with(src: String, sp: MarkdownSpellings) -> MarkdownDocument { @@ -628,14 +640,19 @@ type InlineSplitResult fn md_split_on_delim_pair(text: String, delim: String) -> InlineSplitResult { let parts = split(s: text, delimiter: delim) - if parts.length() >= 3 { - let before = parts.first() - let tail = parts.skip(n: 1) - let inner = tail.first() - let after = join(tail.skip(n: 1), delim) - FoundSplit { parts: InlineSplit { before: before, inner: inner, after: after } } - } else { - NoSplit + let tail = parts.skip(n: 1) + match parts.first() { + Absent => NoSplit + Present { value: before } => + match tail.first() { + Absent => NoSplit + Present { value: inner } => + if parts.length() >= 3 { + FoundSplit { parts: InlineSplit { before: before, inner: inner, after: join(tail.skip(n: 1), delim) } } + } else { + NoSplit + } + } } } @@ -689,20 +706,26 @@ fn md_parse_inline_link(text: String, sp: MarkdownSpellings) -> List [ TextInline { text: text } ] + Present { value: before_bracket } => { let after_bracket = join(open_parts.skip(n: 1), sp.link_text_open) let close_open_pat = join([sp.link_text_close, sp.link_url_open], "") let inner_parts = split(s: after_bracket, delimiter: close_open_pat) if inner_parts.length() < 2 { [ TextInline { text: text } ] } else { - let label_text = inner_parts.first() + match inner_parts.first() { + Absent => [ TextInline { text: text } ] + Present { value: label_text } => { let url_and_rest = join(inner_parts.skip(n: 1), close_open_pat) let url_parts = split(s: url_and_rest, delimiter: sp.link_url_close) if url_parts.length() < 2 { [ TextInline { text: text } ] } else { - let url = url_parts.first() + match url_parts.first() { + Absent => [ TextInline { text: text } ] + Present { value: url } => let after_link = join(url_parts.skip(n: 1), sp.link_url_close) concat( md_text_inline_if_nonempty(s: before_bracket), @@ -715,6 +738,11 @@ fn md_parse_inline_link(text: String, sp: MarkdownSpellings) -> List, index: Int, content_inde } } +// THE Absent ARMS BELOW ARE UNREACHABLE, AND THEY REFUSE RATHER THAN SUBSTITUTE. +// Every optional here is `split(...).first()`, and `split` cannot return an empty +// list -- on the empty string it returns [""] -- so Absent cannot occur. That +// non-emptiness is a property of split's IMPLEMENTATION that its return type +// `List` does not carry, which is exactly why these positions are diagnosed at +// all: nothing enforces the property the code relies on. +// +// The arms therefore refuse instead of substituting a plausible value. The choice +// is only free while the unreachability argument holds, so it is made for the case +// where that argument is WRONG -- a reimplemented split, a different producer, a +// caller passing something that is not a split result. A refusal stops the line +// loudly and located; a fabricated empty value would be the absorbing fallback +// (DESIGN 5). Dissolves when split's return type carries non-emptiness AND these +// callers consume it -- see gunbc.guarantee_stall split_non_emptiness_unmodelled_stall. fn yaml_parse_mapping_entry(lines: List, index: Int, indent: Int) -> YamlEntryResult { let content = yaml_strip_indent(line: yaml_line_at(lines: lines, index: index), indent: indent) let parts = split(s: content, delimiter: ": ") if parts.length() > 1 { - let key = parts.first() + match parts.first() { + Absent => YamlEntryRejected { reason: concat("malformed mapping entry: ", content) } + Present { value: key } => let rest = join(parts.skip(n: 1), ": ") if yaml_has_unmodeled_inline_comment(text: rest) { YamlEntryRejected { reason: "inline YAML comments after values are not modeled" } @@ -197,6 +213,7 @@ fn yaml_parse_mapping_entry(lines: List, index: Int, indent: Int) -> Yam } else { ParsedYamlEntry { entry: kv(key: key, value: yaml_parse_scalar_text(text: rest)), next_index: index + 1 } } + } } else if ends_with(s: content, suffix: ":") { let key = substring(s: content, start: 0, end: content.length() - 1) if yaml_has_line_at(lines: lines, index: index + 1) && (yaml_indent_at(lines: lines, index: index + 1) == indent + 2) { @@ -216,7 +233,9 @@ fn yaml_parse_mapping_entry(lines: List, index: Int, indent: Int) -> Yam fn yaml_parse_mapping_entry_from_text(text: String, lines: List, index: Int, indent: Int) -> YamlEntryResult { let parts = split(s: text, delimiter: ": ") if parts.length() > 1 { - let key = parts.first() + match parts.first() { + Absent => YamlEntryRejected { reason: concat("malformed mapping entry: ", text) } + Present { value: key } => let rest = join(parts.skip(n: 1), ": ") if yaml_has_unmodeled_inline_comment(text: rest) { YamlEntryRejected { reason: "inline YAML comments after values are not modeled" } @@ -228,6 +247,7 @@ fn yaml_parse_mapping_entry_from_text(text: String, lines: List, index: } else { ParsedYamlEntry { entry: kv(key: key, value: yaml_parse_scalar_text(text: rest)), next_index: index + 1 } } + } } else if ends_with(s: text, suffix: ":") { let key = substring(s: text, start: 0, end: text.length() - 1) if yaml_has_line_at(lines: lines, index: index + 1) && (yaml_indent_at(lines: lines, index: index + 1) == indent + 4) { diff --git a/dag/extdeps/linux/proc_self_cgroup.dag b/dag/extdeps/linux/proc_self_cgroup.dag index 790d798e59d..b1d8fea5f74 100644 --- a/dag/extdeps/linux/proc_self_cgroup.dag +++ b/dag/extdeps/linux/proc_self_cgroup.dag @@ -122,10 +122,9 @@ fn proc_self_cgroup_unified_hierarchy_paths_loop( lines: List, acc: List, ) -> List { - if list_length(items: lines) == 0 { - acc - } else { - let line = lines.first() + match lines.first() { + Absent => acc + Present { value: line } => { let rest = lines.skip(n: 1) match proc_self_cgroup_line_from_wire(line: line) { ProcSelfCgroupLineParsed { hierarchy_id: hid, controller_list: ctl, relative_path: path } => @@ -137,6 +136,7 @@ fn proc_self_cgroup_unified_hierarchy_paths_loop( ProcSelfCgroupLineRefused { cause: _ } => proc_self_cgroup_unified_hierarchy_paths_loop(lines: rest, acc: acc) } + } } } @@ -148,10 +148,9 @@ fn proc_self_cgroup_unified_hierarchy_paths(content: String) -> List) -> ProcSelfCgroupMalformedScan { - if list_length(items: lines) == 0 { - NoMalformedLine - } else { - let line = lines.first() + match lines.first() { + Absent => NoMalformedLine + Present { value: line } => match proc_self_cgroup_line_from_wire(line: line) { ProcSelfCgroupLineRefused { cause: c } => MalformedFound { cause: c } ProcSelfCgroupLineParsed { hierarchy_id: _, controller_list: _, relative_path: _ } => @@ -171,15 +170,14 @@ fn read_unified_cgroup_membership(content: String) -> ProcPidCgroupMembershipRec MalformedFound { cause: cause } => MembershipMalformed { cause: cause } NoMalformedLine => let paths = proc_self_cgroup_unified_hierarchy_paths(content: content) - if list_length(items: paths) == 0 { - MembershipMissing - } else if list_length(items: paths) == 1 { - CurrentCgroupObserved { relative_path: paths.first() } - } else { - MembershipAmbiguous { - first: paths.first(), - second: paths.skip(n: 1).first(), - } + match paths.first() { + Absent => MembershipMissing + Present { value: only_or_first } => + match paths.skip(n: 1).first() { + Absent => CurrentCgroupObserved { relative_path: only_or_first } + Present { value: second } => + MembershipAmbiguous { first: only_or_first, second: second } + } } } } @@ -229,10 +227,9 @@ fn proc_self_cgroup_unified_hierarchy_paths_drift_sketch_loop( lines: List, acc: List, ) -> List { - if list_length(items: lines) == 0 { - acc - } else { - let line = lines.first() + match lines.first() { + Absent => acc + Present { value: line } => { let rest = lines.skip(n: 1) match proc_self_cgroup_line_from_wire(line: line) { ProcSelfCgroupLineParsed { hierarchy_id: hid, controller_list: ctl, relative_path: path } => @@ -250,6 +247,7 @@ fn proc_self_cgroup_unified_hierarchy_paths_drift_sketch_loop( ProcSelfCgroupLineRefused { cause: _ } => proc_self_cgroup_unified_hierarchy_paths_drift_sketch_loop(lines: rest, acc: acc) } + } } } @@ -265,15 +263,14 @@ fn read_unified_cgroup_membership_drift_sketch(content: String) -> ProcPidCgroup MalformedFound { cause: cause } => MembershipMalformed { cause: cause } NoMalformedLine => let paths = proc_self_cgroup_unified_hierarchy_paths_drift_sketch(content: content) - if list_length(items: paths) == 0 { - MembershipMissing - } else if list_length(items: paths) == 1 { - CurrentCgroupObserved { relative_path: paths.first() } - } else { - MembershipAmbiguous { - first: paths.first(), - second: paths.skip(n: 1).first(), - } + match paths.first() { + Absent => MembershipMissing + Present { value: only_or_first } => + match paths.skip(n: 1).first() { + Absent => CurrentCgroupObserved { relative_path: only_or_first } + Present { value: second } => + MembershipAmbiguous { first: only_or_first, second: second } + } } } } diff --git a/dag/extdeps/transports/rest.dag b/dag/extdeps/transports/rest.dag index 80365319a5c..baae765bc87 100644 --- a/dag/extdeps/transports/rest.dag +++ b/dag/extdeps/transports/rest.dag @@ -237,10 +237,9 @@ fn rest_fixture_scan( invocation: RestBoundOperationInvocation, scan: RestFixtureScan, ) -> RestFixtureScan { - if fixtures.count() == 0 { - scan - } else { - let fixture = fixtures.first() + match fixtures.first() { + Absent => scan + Present { value: fixture } => let matches = fixture.store == store && rest_bound_invocation_eq(a: fixture.invocation, b: invocation) let next = if matches { diff --git a/dag/extdeps/version/semver.dag b/dag/extdeps/version/semver.dag index 12a8da1b64b..ae69cfc0f00 100644 --- a/dag/extdeps/version/semver.dag +++ b/dag/extdeps/version/semver.dag @@ -52,19 +52,25 @@ fn semver_compare_identifier(a: SemVerIdentifier, b: SemVerIdentifier) -> Orderi } fn semver_compare_identifiers(a: List, b: List) -> Ordering { - if a.count() == 0 && b.count() == 0 { Equal } - - else if a.count() == 0 { Less } - else if b.count() == 0 { Greater } - else { - match semver_compare_identifier(a: a.first(), b: b.first()) { - Equal => - semver_compare_identifiers( - a: a.skip(n: 1), - b: b.skip(n: 1) - ) - other => other - } + match a.first() { + Absent => + match b.first() { + Absent => Equal + Present { value: _ } => Less + } + Present { value: ah } => + match b.first() { + Absent => Greater + Present { value: bh } => + match semver_compare_identifier(a: ah, b: bh) { + Equal => + semver_compare_identifiers( + a: a.skip(n: 1), + b: b.skip(n: 1) + ) + other => other + } + } } } diff --git a/dag/gunbc/ci/ci_deploy_access.dag b/dag/gunbc/ci/ci_deploy_access.dag index e8464c1f067..7b4922a45a0 100644 --- a/dag/gunbc/ci/ci_deploy_access.dag +++ b/dag/gunbc/ci/ci_deploy_access.dag @@ -292,14 +292,21 @@ fn deploy_access_unprivileged_fixture_actor() -> DeployAccessActor { } fn deploy_access_sudo_miss_reason(access: DeployAccess) -> String { - let sample = access.privileged_commands.first() - concat( - concat( - concat(deploy_access_refusal_prefix, " — privileged commands not granted (sudo -n preflight miss)\n"), - concat(concat("Add to ", gunbc_deploy_sudoers_dropin), ":\n") - ), - deploy_access_sudoers_line(access: access, cmd: sample) - ) + match access.privileged_commands.first() { + Absent => + concat( + deploy_access_refusal_prefix, + " — a sudo -n preflight miss was reported for a DeployAccess that declares no privileged commands at all, so there is no sudoers line to add; the miss and the policy disagree about whether privilege was ever required" + ) + Present { value: sample } => + concat( + concat( + concat(deploy_access_refusal_prefix, " — privileged commands not granted (sudo -n preflight miss)\n"), + concat(concat("Add to ", gunbc_deploy_sudoers_dropin), ":\n") + ), + deploy_access_sudoers_line(access: access, cmd: sample) + ) + } } fn deploy_access_check(access: DeployAccess, actor: DeployAccessActor) -> AccessDecision { diff --git a/dag/gunbc/commit_workflow.dag b/dag/gunbc/commit_workflow.dag index 35953767851..6fd584942a0 100644 --- a/dag/gunbc/commit_workflow.dag +++ b/dag/gunbc/commit_workflow.dag @@ -451,22 +451,22 @@ fn conflict_marker_locations_from_lines_at( grammar: GitEffectiveConflictMarkerGrammar, parsed: ConflictMarkerParseFold, ) -> List { - if index >= count(lines) { - parsed.locations - } else { - conflict_marker_locations_from_lines_at( - lines: lines, - index: index + 1, - path: path, - grammar: grammar, - parsed: conflict_marker_parse_line( - fold_state: parsed, + match lines.skip(n: index).first() { + Absent => parsed.locations + Present { value: line_at_index } => + conflict_marker_locations_from_lines_at( + lines: lines, + index: index + 1, path: path, - line: lines.skip(n: index).first(), - line_number: index + 1, grammar: grammar, - ), - ) + parsed: conflict_marker_parse_line( + fold_state: parsed, + path: path, + line: line_at_index, + line_number: index + 1, + grammar: grammar, + ), + ) } } @@ -853,24 +853,23 @@ fn commit_writer_blob_coverage_refusals( path: blob.path, ) append( - if count(matching_index) == 0 { - [CommitWriterExtraBlobObservationRefusal { + match matching_index.first() { + Absent => [CommitWriterExtraBlobObservationRefusal { path: blob.path, indexed_oid: blob.indexed_oid, }] - } else if count(matching_index) > 1 { - [] - } else { - let index_entry = matching_index.first() - if git_object_id_eq(left: index_entry.oid, right: blob.indexed_oid) { - [] - } else { - [CommitWriterIndexBlobIdentityMismatchRefusal { - path: blob.path, - index_oid: index_entry.oid, - observed_index_oid: blob.indexed_oid, - }] - } + Present { value: index_entry } => + if count(matching_index) > 1 { + [] + } else if git_object_id_eq(left: index_entry.oid, right: blob.indexed_oid) { + [] + } else { + [CommitWriterIndexBlobIdentityMismatchRefusal { + path: blob.path, + index_oid: index_entry.oid, + observed_index_oid: blob.indexed_oid, + }] + } }, items: append( if git_object_id_eq(left: blob.indexed_oid, right: blob.content_oid) { @@ -2345,11 +2344,17 @@ fn witness_seam_eq(a: WitnessSeam, b: WitnessSeam) -> Bool { fn witness_seam_lists_eq(left: List, right: List) -> Bool { if left.count() != right.count() { false - } else if left.count() == 0 { - true } else { - witness_seam_eq(a: left.first(), b: right.first()) - && witness_seam_lists_eq(left: left.skip(n: 1), right: right.skip(n: 1)) + match left.first() { + Absent => true + Present { value: lh } => + match right.first() { + Absent => true + Present { value: rh } => + witness_seam_eq(a: lh, b: rh) + && witness_seam_lists_eq(left: left.skip(n: 1), right: right.skip(n: 1)) + } + } } } @@ -2469,13 +2474,13 @@ fn declaration_field_is_whole(field: DeclField) -> Bool { } fn declaration_refs_unique(declarations: List) -> Bool { - if declarations.count() == 0 { - true - } else { - !declaration_ref_in_list( - target: declarations.first(), - refs: declarations.skip(n: 1) - ) && declaration_refs_unique(declarations: declarations.skip(n: 1)) + match declarations.first() { + Absent => true + Present { value: head } => + !declaration_ref_in_list( + target: head, + refs: declarations.skip(n: 1) + ) && declaration_refs_unique(declarations: declarations.skip(n: 1)) } } @@ -2500,12 +2505,14 @@ fn demand_check_count(check: CommitCheckKind, rows: List) -> DuplicateCommitCheck { - if roster.count() == 0 { - NoDuplicateCommitCheck - } else if commit_check_count(check: roster.first().check, roster: roster) > 1 { - DuplicateCommitCheckFound { check: roster.first().check } - } else { - first_duplicate_commit_check(roster: roster.skip(n: 1)) + match roster.first() { + Absent => NoDuplicateCommitCheck + Present { value: head } => + if commit_check_count(check: head.check, roster: roster) > 1 { + DuplicateCommitCheckFound { check: head.check } + } else { + first_duplicate_commit_check(roster: roster.skip(n: 1)) + } } } @@ -2593,12 +2600,12 @@ fn project_named_declaration_demands( names: List, declarations: List, ) -> NamedDeclarationDemandOutcome { - if names.count() == 0 { - NamedDeclarationsQualified { declarations: [] } - } else { + match names.first() { + Absent => NamedDeclarationsQualified { declarations: [] } + Present { value: head_name } => let matching = filter( declarations, - declaration => declaration_matches_name(declaration: declaration, name: names.first()) + declaration => declaration_matches_name(declaration: declaration, name: head_name) ) if matching.count() == 0 { NamedDeclarationMissing { @@ -2616,13 +2623,19 @@ fn project_named_declaration_demands( NamedDeclarationMissing { cause } => NamedDeclarationMissing { cause: cause } NamedDeclarationAmbiguous { cause } => NamedDeclarationAmbiguous { cause: cause } NamedDeclarationsQualified { declarations: rest } => - let selected = concat([matching.first()], rest) - if declaration_refs_unique(declarations: selected) { - NamedDeclarationsQualified { declarations: selected } - } else { - NamedDeclarationAmbiguous { - cause: "named witness demand repeats one declaration identity" as NonEmptyStr + match matching.first() { + Absent => NamedDeclarationMissing { + cause: "named witness declaration is absent from complete discovery" as NonEmptyStr } + Present { value: selected_head } => + let selected = concat([selected_head], rest) + if declaration_refs_unique(declarations: selected) { + NamedDeclarationsQualified { declarations: selected } + } else { + NamedDeclarationAmbiguous { + cause: "named witness demand repeats one declaration identity" as NonEmptyStr + } + } } } } @@ -2729,10 +2742,10 @@ fn project_enrollment_witness_demands_unchecked( roster: List, discoveries: List, ) -> EnrollmentDemandOutcome { - if roster.count() == 0 { - DemandQualified { rows: [] } - } else { - let check = roster.first().check + match roster.first() { + Absent => DemandQualified { rows: [] } + Present { value: head_row } => + let check = head_row.check match project_one_enrollment_witness_demand( check: check, discoveries: discoveries @@ -2798,9 +2811,14 @@ fn project_enrollment_witness_demands( if demand_rows_match_roster(roster: roster, rows: rows) { DemandQualified { rows: rows } } else { - DemandIncomplete { - check: roster.first().check, - cause: "projected demand check set does not equal input roster" as NonEmptyStr + match roster.first() { + Absent => DemandRosterAmbiguous { + cause: "commit check roster is empty, so no check identity can carry the incompleteness" as NonEmptyStr + } + Present { value: head_row } => DemandIncomplete { + check: head_row.check, + cause: "projected demand check set does not equal input roster" as NonEmptyStr + } } } } @@ -2817,12 +2835,12 @@ fn seam_list_contains(seams: List, seam: WitnessSeam) -> Bool { } fn seams_wellformed_and_distinct(seams: List) -> Bool { - if seams.count() == 0 { - true - } else { - witness_seam_wellformed(seam: seams.first()) - && !seam_list_contains(seams: seams.skip(n: 1), seam: seams.first()) - && seams_wellformed_and_distinct(seams: seams.skip(n: 1)) + match seams.first() { + Absent => true + Present { value: head } => + witness_seam_wellformed(seam: head) + && !seam_list_contains(seams: seams.skip(n: 1), seam: head) + && seams_wellformed_and_distinct(seams: seams.skip(n: 1)) } } @@ -2893,24 +2911,40 @@ fn project_local_tidy_fmt_rows(roster: List) -> List, right: List) -> Bool { if length(left) != length(right) { false - } else if length(left) == 0 { - true - } else if !gate_eq(a: left.first(), b: right.first()) { - false } else { - gate_lists_eq(left: left.skip(n: 1), right: right.skip(n: 1)) + match left.first() { + Absent => true + Present { value: lh } => + match right.first() { + Absent => true + Present { value: rh } => + if !gate_eq(a: lh, b: rh) { + false + } else { + gate_lists_eq(left: left.skip(n: 1), right: right.skip(n: 1)) + } + } + } } } fn local_tidy_lists_eq(left: List, right: List) -> Bool { if length(left) != length(right) { false - } else if length(left) == 0 { - true - } else if !local_tidy_check_eq(a: left.first(), b: right.first()) { - false } else { - local_tidy_lists_eq(left: left.skip(n: 1), right: right.skip(n: 1)) + match left.first() { + Absent => true + Present { value: lh } => + match right.first() { + Absent => true + Present { value: rh } => + if !local_tidy_check_eq(a: lh, b: rh) { + false + } else { + local_tidy_lists_eq(left: left.skip(n: 1), right: right.skip(n: 1)) + } + } + } } } diff --git a/dag/gunbc/fleet/fleet_desired_observe.dag b/dag/gunbc/fleet/fleet_desired_observe.dag index 74ddeb359a3..666b3c7eb29 100644 --- a/dag/gunbc/fleet/fleet_desired_observe.dag +++ b/dag/gunbc/fleet/fleet_desired_observe.dag @@ -49,7 +49,10 @@ fn observe_fleet_desired_revision(repo: FilePath) -> FleetDesiredRevision { if line == "" { FleetDesiredAbsent } else { - match git_object_id_from_untagged_hex(hex: split(s: line, delimiter: "\t").first()) { + match (match split(s: line, delimiter: "\t").first() { + Absent => none + Present { value: hex } => git_object_id_from_untagged_hex(hex: hex) + }) { Present { value: oid } => FleetDesiredAdmitted { revision: oid } Absent => FleetDesiredUndecodable { advertised: line } } diff --git a/dag/gunbc/fleet/fleet_hardware_standing_panel.dag b/dag/gunbc/fleet/fleet_hardware_standing_panel.dag index 2cb502e9c68..edb10bf7dbc 100644 --- a/dag/gunbc/fleet/fleet_hardware_standing_panel.dag +++ b/dag/gunbc/fleet/fleet_hardware_standing_panel.dag @@ -151,7 +151,7 @@ fn hardware_axis_cell(standing: HardwareStanding, detail: String) -> List Fragment { el_class("div", "hardware-row", concat( [el_class("span", "hardware-subject", [txt(dimm_verdict_host(verdict: verdict) as String)]), - el_class("span", "hardware-axis", [txt(hardware_axis_labels().first())])], + el_class("span", "hardware-axis", [txt(hardware_axis_memory_label())])], hardware_axis_cell( standing: dimm_standing(verdict: verdict), detail: dimm_detail(verdict: verdict), @@ -162,7 +162,7 @@ fn dimm_row(verdict: DimmReconcileVerdict) -> Fragment { fn processor_row(verdict: ProcessorReconcileVerdict) -> Fragment { el_class("div", "hardware-row", concat( [el_class("span", "hardware-subject", [txt(processor_verdict_host(verdict: verdict) as String)]), - el_class("span", "hardware-axis", [txt(hardware_axis_labels().skip(n: 1).first())])], + el_class("span", "hardware-axis", [txt(hardware_axis_processor_label())])], hardware_axis_cell( standing: processor_standing(verdict: verdict), detail: processor_detail(verdict: verdict), @@ -244,7 +244,17 @@ fn hardware_longest_len(labels: List) -> Int { // wrong one; today that is merely wrong-looking, and it would silently truncate or over-reserve the // moment either population moved. The axis words now come from one list that both the rows and the // reservation read, so a third axis widens the column by derivation rather than by anyone noticing. -fn hardware_axis_labels() -> List { ["memory", "processor"] } +// The two axis labels are NAMED rather than indexed out of the list. Reaching a row's label as +// labels().first() / labels().skip(n: 1).first() made the list's ORDER the authority for which +// axis a row is on -- a positional naming scheme for something the axis already names, and one +// that silently mislabels every row if the list is ever reordered. +fn hardware_axis_memory_label() -> String { "memory" } + +fn hardware_axis_processor_label() -> String { "processor" } + +fn hardware_axis_labels() -> List { + [hardware_axis_memory_label(), hardware_axis_processor_label()] +} fn hardware_axis_reserved_width() -> String { let widest = hardware_longest_len(labels: hardware_axis_labels()) + hardware_column_ch_gutter diff --git a/dag/gunbc/fleet/fleet_host_budget.dag b/dag/gunbc/fleet/fleet_host_budget.dag index 65c7f6129af..a7c75602ef8 100644 --- a/dag/gunbc/fleet/fleet_host_budget.dag +++ b/dag/gunbc/fleet/fleet_host_budget.dag @@ -134,11 +134,15 @@ fn gunbc_fleet_oomd_evidence_for(host: HostIdentity) -> OomdEnforcementEvidence match session_admission_oomd_ceiling(p: gunbc_session_admission_policy) { Absent => OomdUnverified Present { value: ceiling } => - gunbc_oomd_fleet_evidence(req: OomdGroundingThresholds { - per_session_cap: ceiling, - parent_slice_cap: session_reservation_bytes(host: host), - pressure_limit: gunbc_oomd_sessions_policy.managed_oom_memory_pressure_limit, - }) + match gunbc_oomd_sessions_policy.managed_oom_memory_pressure_limit { + Absent => OomdUnverified + Present { value: pressure_limit } => + gunbc_oomd_fleet_evidence(req: OomdGroundingThresholds { + per_session_cap: ceiling, + parent_slice_cap: session_reservation_bytes(host: host), + pressure_limit: pressure_limit, + }) + } } } diff --git a/dag/gunbc/guarantee_stall/emitted_field_access_ignores_value_shape_stall.dag b/dag/gunbc/guarantee_stall/emitted_field_access_ignores_value_shape_stall.dag new file mode 100644 index 00000000000..ed2b2bafbfc --- /dev/null +++ b/dag/gunbc/guarantee_stall/emitted_field_access_ignores_value_shape_stall.dag @@ -0,0 +1,35 @@ +module gunbc.guarantee_stall.emitted_field_access_ignores_value_shape_stall + +import v2.std.algebra { Cons, Empty } +import gunbc.guarantee_rung { OutsideTheLadder, StructurallyGuaranteed } +import gunbc.guarantee_stall { GuaranteeStall, ClimbableButUnbuilt, BoundedPopulation } + +// ONE FieldSummary, TWO CONSUMERS, AND ONLY ONE OF THEM READS BOTH HALVES. The reconciler produces +// a FieldSummary carrying an access_style AND a value_shape; value_shape is the checker's decision +// about whether the field access yields an Optional or a plain value. The interpreter's +// eval_field_access now consumes both. v1.compiler.emit_rust emit_typed_field_access matches on +// access_style alone and never reads value_shape at all. +// +// THE CONSEQUENCE IS A SEMANTIC DIVERGENCE, NOT A COSMETIC ONE: a field access the checker marked +// OptionalValue emits byte-identical Rust to one marked PlainValue, so the interpreted and emitted +// arms of the same program can disagree about whether a value is present. That is precisely the +// self-host equivalence claim -- the emitted module must be behaviorally equivalent to the seed on +// a discriminating corpus -- failing on a fact the model already carries. +// +// WHY THIS IS OutsideTheLadder RATHER THAN A LOW RUNG: there is no evidence either way. The emitted +// arm has no discriminating test, so the divergence is neither refused, nor proven, nor measured. +// A rung would claim an executed observation that does not exist, and the honest report of an +// unobserved boundary is not the bottom of the ladder but off it. +// +// THIS IS A DIFFERENT SUBJECT FROM narrowing_arm_not_a_function_of_the_rendering_stall, which +// concerns which optional-narrowing arm fired and what its diagnostic renders. That row names +// neither emit_typed_field_access nor access_style/value_shape parity, and it must not be cited as +// covering this. +data emitted_field_access_ignores_value_shape_stall: GuaranteeStall = GuaranteeStall { + subject: "v1.compiler.emit_rust emit_typed_field_access branches on FieldSummary access_style and never reads value_shape, while the interpreter's eval_field_access consumes both, so one reconciled field-access fact has two consumers that can disagree -- an OptionalValue access emits identical Rust to a PlainValue one and the emitted program may differ from the interpreted one on whether a value is present", + current: OutsideTheLadder, + ceiling: StructurallyGuaranteed, + blocker: ClimbableButUnbuilt, + population: BoundedPopulation { members: Cons { head: "v1.compiler.emit_rust.emit_typed_field_access", tail: Empty {} } }, + next_rung_trigger: "emit_typed_field_access CONSUMES value_shape from the same FieldSummary the interpreter reads, demonstrated by a discriminating emitted test carrying BOTH controls -- a field access the checker marked OptionalValue whose emitted program observes the value ABSENT, and one marked PlainValue whose emitted program observes it PRESENT -- with the pair red today and green once the emitted arm reads the fact. A test exercising only the present case does NOT retire this row, because the current emitter already renders that case correctly and such a test is green by construction. Nor does routing value_shape into emit_typed_field_access without a control, because an unread field and a read one are indistinguishable from the emitted bytes alone" +} diff --git a/dag/gunbc/guarantee_stall/narrowing_arm_not_a_function_of_the_rendering_stall.dag b/dag/gunbc/guarantee_stall/narrowing_arm_not_a_function_of_the_rendering_stall.dag new file mode 100644 index 00000000000..2763e91e833 --- /dev/null +++ b/dag/gunbc/guarantee_stall/narrowing_arm_not_a_function_of_the_rendering_stall.dag @@ -0,0 +1,49 @@ +module gunbc.guarantee_stall.narrowing_arm_not_a_function_of_the_rendering_stall + +import gunbc.guarantee_rung { Mitigatable, StructurallyGuaranteed } +import gunbc.guarantee_stall { GuaranteeStall, AwaitsOneGrounding, UncountedNotEnumerable } + +// THE DISCRIMINATING FACT IS AN EQUALITY: two positions the checker renders IDENTICALLY took +// OPPOSITE arms. extdeps.github.app:112 and gunbc.auth.secret_rotation:341 were ACCUSED at a +// position rendered 'Node(fn)', while 114 of the 120 DECLINED lines in the same run rendered +// 'Node(fn)' too. No predicate over the shown text can separate arms whose shown text is equal, +// which is why this is an OBSERVABILITY defect and not a reach gap -- a reach gap would be closed +// by widening a predicate. +// +// WHERE THAT MEASUREMENT CAME FROM, stated because it decides how a reader can check it: a +// substitution-aware decline candidate that was built, measured, and WITHDRAWN. It is not in this +// tree. So the equality is NOT re-derivable from the committed corpus, and this row does not claim +// it is. Re-deriving it means rebuilding the candidate. The row is filed anyway because the defect +// it names is a property of the SURVIVING check -- what the narrowing diagnostic renders -- and +// that is unchanged by the candidate's withdrawal. +// +// ONE CITED SITE'S ARM MOVED TWICE, FOR TWO DIFFERENT REASONS, and the second move corrects a +// claim this row made in an earlier revision. Three measurements, each naming its tree: +// candidate present, before merging main -> extdeps.github.app:112 ACCUSED +// candidate absent, before merging main -> NOT accused +// candidate absent, after merging main -> ACCUSED again +// The first two differ only in the candidate, so the candidate did perturb an arm at a site it was +// never aimed at. But an earlier revision of this row went on to say that only +// gunbc.auth.secret_rotation:341 is still accused, and that is FALSE for the shipped tree: merging +// main re-accused app:112 for some third reason, without either the candidate or that file changing. +// +// So the site moved for a reason invisible in what the checker showed, TWICE, and the second time +// the invisible reason was somebody else's merge. That is the row's own subject arriving in the +// row's own evidence, and the correction is recorded rather than quietly applied because the false +// sentence was published and a reader may have carried it. +// +// THE MEASURED CONSEQUENCE, which is what makes the class real rather than a story: an attempt to +// predict the arms from source SHAPE -- fold_list cons: positions and Accepted { value: ... } +// positions -- named 17 sites and moved 0 of them. Recognizing a shape in the source is not knowing +// what the checker consumes, and a third group in that census rendered 'Primitive()' and was never +// a generic formal at all, so the census was mixing three mechanisms under one name. The count +// would have concealed all of it: accused fell 42 -> 17 and read as a win while zero intended sites +// moved and the entire drop came from unrelated repairs. Only a site-identity join refused it. +data narrowing_arm_not_a_function_of_the_rendering_stall: GuaranteeStall = GuaranteeStall { + subject: "the optional-into-required check decides its arm using facts its diagnostic does not render, so positions whose declared type prints identically can take opposite arms and no reader -- author, reviewer, or a later repair pass -- can predict from what the compiler shows them which arm a position will take", + current: Mitigatable, + ceiling: StructurallyGuaranteed, + blocker: AwaitsOneGrounding { grounding: "the narrowing diagnostic renders the FACT THE ARM WAS DECIDED ON -- whether the declared formal at this position was substituted, and by what -- rather than the post-hoc printing of a type whose rendering is equal across both arms" }, + population: UncountedNotEnumerable { reason: "the subject is every POSITION whose rendered declared type hides the fact its arm was decided on, and every reader exposed to one. That set cannot be enumerated from this tree for the same reason the row's own evidence cannot be re-derived from it: the arms were observed only under a decline candidate that was measured and then WITHDRAWN, one of the two positions cited above no longer takes the arm it took then, and the committed corpus produces no declines at all -- so there is no run against this tree that separates a position whose rendering hides the deciding fact from one whose rendering does not. Naming optional_into_required_mismatch and optional_narrowing_diags here would be naming the two MECHANISM CARRIERS, and a carrier cannot answer for the population it exposes: the same two functions serve every position in the corpus, including all the ones that are not affected. The exposure becomes enumerable by exactly the capability the blocker names -- once the diagnostic carries the deciding fact, the affected positions are the ones whose text changes" } + next_rung_trigger: "the diagnostic CARRIES the deciding fact and a reader CONSUMES it -- sufficient for two positions that render identically today to render differently once the deciding fact is carried, demonstrated by a fixture pair built to render identically and a run showing them distinguishable BY THE DIAGNOSTIC TEXT ALONE. A richer type rendering that leaves such a pair's texts equal does NOT retire this row, because the equality is the defect and a longer string preserving it has changed nothing. Note that the demonstration requires a PURPOSE-BUILT FIXTURE PAIR and not the two historical sites, because those sites arms have already been observed moving under changes aimed at neither of them -- once under the withdrawn candidate and once under an unrelated merge -- so anything derived from their current arm is measuring whatever last moved the tree" +} diff --git a/dag/gunbc/guarantee_stall/produced_operand_substitution_stall.dag b/dag/gunbc/guarantee_stall/produced_operand_substitution_stall.dag new file mode 100644 index 00000000000..4cf2930e890 --- /dev/null +++ b/dag/gunbc/guarantee_stall/produced_operand_substitution_stall.dag @@ -0,0 +1,13 @@ +module gunbc.guarantee_stall.produced_operand_substitution_stall + +import gunbc.guarantee_rung { OutsideTheLadder, StructurallyGuaranteed } +import gunbc.guarantee_stall { GuaranteeStall, AwaitsOneGrounding, UncountedNotEnumerable } + +data produced_operand_substitution_stall: GuaranteeStall = GuaranteeStall { + subject: "a call site whose PRODUCED type should have been substituted and was not is admitted silently at the optional-into-required seam, because the produced operand is read pre-substitution and a bare type variable carries no optionality either way", + current: OutsideTheLadder, + ceiling: StructurallyGuaranteed, + blocker: AwaitsOneGrounding { grounding: "a SUBSTITUTING read on the produced operand at both seams -- the produced side is resolved_type, which returns the node inferred Resolved payload and substitutes nothing, while the declared side already reads formal_subst" }, + population: UncountedNotEnumerable { reason: "the subject is a call site whose produced type should have been substituted and was not. The 219 sites where produced.inferred is a TypeVariable are NOT this population: most are a T inside a generic BODY where the value genuinely is a T. Separating the two requires the substituting read that does not exist, so the population is not enumerable until the grounding lands -- the same missing capability the blocker names, which is why no count is offered rather than a count being offered with a caveat" }, + next_rung_trigger: "a substituting read on the produced operand EXISTS and is CONSUMED BY BOTH SEAMS -- the direct-call argument seam and the record-field seam -- sufficient for a produced type that instantiates to an optional at a required destination to refuse, demonstrated by a red on a fixture whose callee returns a type parameter instantiated to an optional at a required destination and a green on the same path instantiated to a required type; a helper that lands unconsumed by either seam does NOT retire this row, because the wall stays dead while the artifact exists" +} diff --git a/dag/gunbc/guarantee_stall/roster.dag b/dag/gunbc/guarantee_stall/roster.dag index c1753a4e547..eb0b50bc2da 100644 --- a/dag/gunbc/guarantee_stall/roster.dag +++ b/dag/gunbc/guarantee_stall/roster.dag @@ -40,6 +40,12 @@ import gunbc.guarantee_stall.two_nat_authorities_stall { two_nat_authorities_sta import gunbc.guarantee_stall.external_model_scope_live_cover_stall { external_model_scope_live_cover_stall } import gunbc.guarantee_stall.observation_heartbeat_lockstep_stall { observation_heartbeat_lockstep_stall } import gunbc.guarantee_stall.operation_argv_binding_wall_stall { operation_argv_binding_wall_stall } +import gunbc.guarantee_stall.produced_operand_substitution_stall { produced_operand_substitution_stall } +import gunbc.guarantee_stall.split_non_emptiness_unmodelled_stall { split_non_emptiness_unmodelled_stall } +import gunbc.guarantee_stall.type_variable_test_keyed_by_spelling_stall { type_variable_test_keyed_by_spelling_stall } +import gunbc.guarantee_stall.undetermined_arm_severity_unsettled_stall { undetermined_arm_severity_unsettled_stall } +import gunbc.guarantee_stall.narrowing_arm_not_a_function_of_the_rendering_stall { narrowing_arm_not_a_function_of_the_rendering_stall } +import gunbc.guarantee_stall.emitted_field_access_ignores_value_shape_stall { emitted_field_access_ignores_value_shape_stall } import gunbc.guarantee_stall.roster_re_enumerates_its_own_rows_stall { roster_re_enumerates_its_own_rows_stall } import gunbc.guarantee_stall.self_host_wet_route_receipt_lifetime_stall { self_host_wet_route_receipt_lifetime_stall } @@ -141,6 +147,12 @@ data all_guarantee_stalls: List = [ external_model_scope_live_cover_stall, observation_heartbeat_lockstep_stall, operation_argv_binding_wall_stall, + produced_operand_substitution_stall, + split_non_emptiness_unmodelled_stall, + type_variable_test_keyed_by_spelling_stall, + undetermined_arm_severity_unsettled_stall, + narrowing_arm_not_a_function_of_the_rendering_stall, + emitted_field_access_ignores_value_shape_stall, roster_re_enumerates_its_own_rows_stall, self_host_wet_route_receipt_lifetime_stall, ] diff --git a/dag/gunbc/guarantee_stall/split_non_emptiness_unmodelled_stall.dag b/dag/gunbc/guarantee_stall/split_non_emptiness_unmodelled_stall.dag new file mode 100644 index 00000000000..80604699f34 --- /dev/null +++ b/dag/gunbc/guarantee_stall/split_non_emptiness_unmodelled_stall.dag @@ -0,0 +1,14 @@ +module gunbc.guarantee_stall.split_non_emptiness_unmodelled_stall + +import v2.std.algebra { Cons, Empty } +import gunbc.guarantee_rung { Mitigatable, StructurallyImpossible } +import gunbc.guarantee_stall { GuaranteeStall, AwaitsOneGrounding, BoundedPopulation } + +data split_non_emptiness_unmodelled_stall: GuaranteeStall = GuaranteeStall { + subject: "split returns List while its implementation guarantees a non-empty result, so every caller that reads split(...).first() carries an Absent arm the producer cannot emit, and must CHOOSE that arm's outcome rather than deriving it. One member cannot even refuse: md_parse_block returns MarkdownBlock, which declares no refusal variant, so its unreachable arm routes to the ParagraphBlock fallthrough rather than stopping the line -- the weakest member of the population and the reason the trigger is the TYPE and not a per-site convention. git_remote_ref_parts is weaker still and sets the floor for the row: it returns a plain GitRemoteRefParts record, and its three consumers -- merge_admission_walk.merge_target_refresh, merge_admission_current_context, and v2.workflow.floor_diff_observe -- each feed the result straight into a fetch remote or a default remote name, so there is no refusal channel at the producer OR at any consumer. Its Absent arm was deliberately left UNREPAIRED rather than bound to a sentinel remote name, because a fabricated remote is the plausible-output arm this ladder forbids and would be indistinguishable from a working one at every call site", + current: Mitigatable, + ceiling: StructurallyImpossible, + blocker: AwaitsOneGrounding { grounding: "a non-empty list type that split's return type inhabits, so first() on a split result is total and has no Absent case to decide" }, + population: BoundedPopulation { members: Cons { head: "extdeps.languages.html.parse_one_with", tail: Cons { head: "extdeps.languages.yaml.ingest.yaml_parse_mapping_entry", tail: Cons { head: "extdeps.languages.yaml.ingest.yaml_parse_mapping_entry_from_text", tail: Cons { head: "extdeps.languages.markdown.md_parse_block", tail: Cons { head: "extdeps.git.git_remote_ref_parts", tail: Empty {} } } } } } }, + next_rung_trigger: "split's RETURN TYPE carries non-emptiness AND these callers CONSUME it -- sufficient for the Absent arms in the rostered members to be unwritable rather than merely unreachable, demonstrated by those arms failing to compile once the type lands. A non-empty type that lands unconsumed by these callers does NOT retire this row, because the chosen arms survive and every future reader must re-derive the reachability argument that justified them" +} diff --git a/dag/gunbc/guarantee_stall/type_variable_test_keyed_by_spelling_stall.dag b/dag/gunbc/guarantee_stall/type_variable_test_keyed_by_spelling_stall.dag new file mode 100644 index 00000000000..2920afcc593 --- /dev/null +++ b/dag/gunbc/guarantee_stall/type_variable_test_keyed_by_spelling_stall.dag @@ -0,0 +1,14 @@ +module gunbc.guarantee_stall.type_variable_test_keyed_by_spelling_stall + +import v2.std.algebra { Cons, Empty } +import gunbc.guarantee_rung { Mitigatable, StructurallyGuaranteed } +import gunbc.guarantee_stall { GuaranteeStall, ClimbableButUnbuilt, BoundedPopulation } + +data type_variable_test_keyed_by_spelling_stall: GuaranteeStall = GuaranteeStall { + subject: "is_type_variable_name decides whether a name is a type variable by comparing it against a hand-authored spelling roster -- T, K, V, MappedElement, FoldAccumulator -- rather than against the declared generic parameters of the declaration in hand, so it is wrong for every formal nobody thought to add to the list", + current: Mitigatable, + ceiling: StructurallyGuaranteed, + blocker: ClimbableButUnbuilt, + population: BoundedPopulation { members: Cons { head: "v1.compiler.infer.is_type_variable_name", tail: Empty {} } }, + next_rung_trigger: "the type-variable test CONSULTS DECLARATION IDENTITY -- the generic parameter list of the declaration whose formal is being judged -- and its callers consume that answer, sufficient for a formal named outside the roster to be recognized, demonstrated by a red on a fixture whose declaration names a generic parameter absent from the spelling list and a green once the declaration-identity test is consulted. Deleting the roster while leaving a caller reading a name-shaped approximation does NOT retire this row" +} diff --git a/dag/gunbc/guarantee_stall/undetermined_arm_severity_unsettled_stall.dag b/dag/gunbc/guarantee_stall/undetermined_arm_severity_unsettled_stall.dag new file mode 100644 index 00000000000..92c599d7007 --- /dev/null +++ b/dag/gunbc/guarantee_stall/undetermined_arm_severity_unsettled_stall.dag @@ -0,0 +1,29 @@ +module gunbc.guarantee_stall.undetermined_arm_severity_unsettled_stall + +import gunbc.guarantee_rung { Mitigatable, StructurallyGuaranteed } +import gunbc.guarantee_stall { GuaranteeStall, AwaitsOneGrounding, UncountedNotEnumerable } + +// NOT SILENT IS NOT THE SAME AS BLOCKING, and conflating the two is what this row exists to stop. +// A counted, located, reported advisory is already not silent: it is visible, it has a population, +// and nobody can cite it as coverage. BLOCKING is the stronger claim that the program may not be +// built while this position is undecided. +// +// Blocking on "I cannot determine" has a consequence that was MEASURED, not argued. A candidate +// substitution-aware decline was built and run over the whole corpus. It declined 59 positions, +// 114 of its 120 diagnostic lines rendered 'Node(fn)', every one of the 59 had previously passed, +// and the first of them refused gunbc.generated_artifact_emit outright at std.key_relation:136, so +// regeneration could not complete. It repaired none of the 17 positions it was built for. +// +// That is the inverse of fail-closed. Fail-closed refuses when the PROGRAM is wrong; this refused +// because the CHECKER was unsure, which moves the checker's own limitation onto legitimately +// generic code. The candidate was therefore NOT landed, which is why this row's population is +// honestly unenumerable: the 59 is a measurement of an experiment that does not exist in the tree, +// and quoting it as a live population would be a number without a producer anyone can re-run. +data undetermined_arm_severity_unsettled_stall: GuaranteeStall = GuaranteeStall { + subject: "whether an undetermined optional-narrowing position should BLOCK the build or be counted and reported is unsettled, and the two have been treated as one decision because both are correctly described as not-silent -- so a future reach improvement can arrive as a build-stopping refusal over legitimately generic code without that severity choice ever having been made", + current: Mitigatable, + ceiling: StructurallyGuaranteed, + blocker: AwaitsOneGrounding { grounding: "a determination good enough that undetermined is RARE and each remaining instance is a real gap -- at which point blocking is the honest arm, and until which counting is" }, + population: UncountedNotEnumerable { reason: "the subject is the set of positions an undetermined arm would refuse, which depends on a determination that does not exist in the tree. The 59 measured by the unlanded candidate is evidence about THAT candidate and is not offered as this population, because the candidate was withdrawn and nobody can re-derive the number from the committed corpus" }, + next_rung_trigger: "the undetermined arm's severity is DERIVED from its measured rate on the real corpus rather than chosen -- blocking where undetermined is rare and counted where it is not -- sufficient for a reach improvement to be landable without silently converting passing generic code into refusals, demonstrated by a run reporting the undetermined count on a corpus that still builds. A reach improvement that lands with a blocking arm and no measured rate does NOT retire this row, it is the exact event the row exists to catch" +} diff --git a/dag/gunbc/host/host_converge.dag b/dag/gunbc/host/host_converge.dag index dec5dd26db8..ffa1b4d109a 100644 --- a/dag/gunbc/host/host_converge.dag +++ b/dag/gunbc/host/host_converge.dag @@ -639,7 +639,7 @@ fn runner_host_knobs(h: RunnerHostDeployment) -> List { fn session_host_knobs(slice_max: ByteSize, per_session: ByteSize) -> List { let kill_value = managed_oom_action_value(a: gunbc_oomd_sessions_policy.managed_oom_memory_pressure) - let pct = to_string(percent_count(p: gunbc_oomd_sessions_policy.managed_oom_memory_pressure_limit)) + concat( [ slice_numeric_knob( slice: SessionsSlice, @@ -668,17 +668,6 @@ fn session_host_knobs(slice_max: ByteSize, per_session: ByteSize) -> List List List { + match limit { + Absent => [] + Present { value: p } => { + let pct = to_string(percent_count(p: p)) + [ + legacy_converge_knob( + slice: SessionsSlice, + name: "oom_pressure_limit_pct", + desired: pct, + target: SliceProperty { + unit: gunbc_oomd_sessions_slice, + property: oomd_managed_oom_memory_pressure_limit_property, + apply_value: concat(pct, "%"), + expected_effective: to_string(managed_oom_pressure_limit_show_value(p: p)), + } + ), + ] + } + } } // ONE KNOB LIST WAS BEING WRITTEN TO EVERY HOST, AND THAT IS THE SHARP END OF THE AUTHORITY FORK. diff --git a/dag/gunbc/merge_admission_produce.dag b/dag/gunbc/merge_admission_produce.dag index 98c17a239e7..ab2ab274108 100644 --- a/dag/gunbc/merge_admission_produce.dag +++ b/dag/gunbc/merge_admission_produce.dag @@ -120,13 +120,22 @@ fn parse_receipt_wire_v2(text: String) -> MergeAdmissionReceiptV2? { } else if match lines.skip(n: 5).first() { Present { value: field } => field == "" Absent => true } { none } else { - match walk_attempt_id(raw: lines.skip(n: 1).first()) { + match lines.skip(n: 1).first() { + Absent => none + Present { value: attempt_raw } => + match walk_attempt_id(raw: attempt_raw) { Absent => none Present { value: attempt } => - match parse_check_conclusion(raw: lines.skip(n: 3).first()) { + match lines.skip(n: 3).first() { + Absent => none + Present { value: conclusion_raw } => + match parse_check_conclusion(raw: conclusion_raw) { Absent => none Present { value: conclusion } => - match parse_gate_roster_hash_wire(line: lines.skip(n: 2).first()) { + match lines.skip(n: 2).first() { + Absent => none + Present { value: gate_hash_raw } => + match parse_gate_roster_hash_wire(line: gate_hash_raw) { Absent => none Present { value: gate_roster_hash } => match lines.skip(n: 4).first() { @@ -163,7 +172,10 @@ fn parse_receipt_wire_v2(text: String) -> MergeAdmissionReceiptV2? { } } } + } } + } + } } } } @@ -219,10 +231,9 @@ fn render_receipt_wire(receipt: MergeAdmissionReceipt) -> String { } fn wire_pr_number_from_lines(lines: List) -> Int? { - if length(lines) >= 5 { - parse_int(s: lines.skip(n: 4).first()) - } else { - none + match lines.skip(n: 4).first() { + Absent => none + Present { value: pr_raw } => parse_int(s: pr_raw) } } @@ -231,27 +242,43 @@ fn parse_receipt_wire(text: String) -> MergeAdmissionReceipt? { if length(lines) < 4 { none } else { - match parse_check_conclusion(raw: lines.skip(n: 2).first()) { + match lines.skip(n: 2).first() { + Absent => none + Present { value: conclusion_raw } => + match parse_check_conclusion(raw: conclusion_raw) { Present { value: conclusion } => - match git_object_id_from_untagged_hex(hex: lines.first()) { + match lines.first() { + Absent => none + Present { value: base_hex } => + match git_object_id_from_untagged_hex(hex: base_hex) { Present { value: base_tree_hash } => - match parse_gate_roster_hash_wire(line: lines.skip(n: 1).first()) { + match lines.skip(n: 1).first() { + Absent => none + Present { value: gate_hash_raw } => + match parse_gate_roster_hash_wire(line: gate_hash_raw) { Absent => none Present { value: gate_roster_hash } => + match lines.skip(n: 3).first() { + Absent => none + Present { value: head_sha_line } => Present { value: MergeAdmissionReceipt { pr_number: wire_pr_number_from_lines(lines: lines), - head_sha: lines.skip(n: 3).first(), + head_sha: head_sha_line, base_tree_hash: base_tree_hash, gate_roster_hash: gate_roster_hash, conclusion: conclusion, } } + } + } } Absent => none } + } Absent => none } + } } } diff --git a/dag/gunbc/merge_admission_subject.dag b/dag/gunbc/merge_admission_subject.dag index 0901b4a3041..40a374dac75 100644 --- a/dag/gunbc/merge_admission_subject.dag +++ b/dag/gunbc/merge_admission_subject.dag @@ -134,9 +134,15 @@ fn parse_git_object_id_wire(raw: String) -> GitObjectId? { if !(length(split(s: raw, delimiter: ":")) == 2) { none } else if match split(s: raw, delimiter: ":").first() { Present { value: algorithm } => algorithm == "sha1" Absent => false } { - git_sha1_object_id(hex: split(s: raw, delimiter: ":").skip(n: 1).first()) + match split(s: raw, delimiter: ":").skip(n: 1).first() { + Absent => none + Present { value: hex } => git_sha1_object_id(hex: hex) + } } else if match split(s: raw, delimiter: ":").first() { Present { value: algorithm } => algorithm == "sha256" Absent => false } { - git_sha256_object_id(hex: split(s: raw, delimiter: ":").skip(n: 1).first()) + match split(s: raw, delimiter: ":").skip(n: 1).first() { + Absent => none + Present { value: hex } => git_sha256_object_id(hex: hex) + } } else { none } @@ -169,7 +175,10 @@ fn parse_tested_subject_wire(text: String) -> TestedSubject? { } else if match lines.skip(n: 4).first() { Present { value: field } => field == "" Absent => true } { none } else { - match walk_attempt_id(raw: lines.skip(n: 1).first()) { + match (match lines.skip(n: 1).first() { + Absent => none + Present { value: attempt_line } => walk_attempt_id(raw: attempt_line) + }) { Absent => none Present { value: attempt } => match lines.skip(n: 2).first() { diff --git a/dag/gunbc/product/printed_chassis/realization_contract.dag b/dag/gunbc/product/printed_chassis/realization_contract.dag index 193e42905d4..d9111ca5b24 100644 --- a/dag/gunbc/product/printed_chassis/realization_contract.dag +++ b/dag/gunbc/product/printed_chassis/realization_contract.dag @@ -277,9 +277,11 @@ fn decode_envelope(envelope: RawRealizationEnvelope) -> EnvelopeAdmission { } } ) - if scan.unknown.length() != 0 { - EnvelopeRefused { refusal: EnvelopeOperationUnknown { received: scan.unknown.first() } } - } else if envelope.ladder_holes.length() == 0 { + match scan.unknown.first() { + Present { value: received } => + EnvelopeRefused { refusal: EnvelopeOperationUnknown { received: received } } + Absent => + if envelope.ladder_holes.length() == 0 { EnvelopeRefused { refusal: EnvelopeCarriesNoOperations } } else { EnvelopeDecodedV0 { @@ -298,6 +300,7 @@ fn decode_envelope(envelope: RawRealizationEnvelope) -> EnvelopeAdmission { }, } } + } } } diff --git a/dag/gunbc/recurring_failure_mode/comparison_discards_the_dimension_it_judges.dag b/dag/gunbc/recurring_failure_mode/comparison_discards_the_dimension_it_judges.dag new file mode 100644 index 00000000000..5644ee6ebca --- /dev/null +++ b/dag/gunbc/recurring_failure_mode/comparison_discards_the_dimension_it_judges.dag @@ -0,0 +1,72 @@ +module gunbc.recurring_failure_mode.comparison_discards_the_dimension_it_judges + +import std.types { NonEmptyStr } +import gunbc.recurring_failure_mode { RecurringFailureMode } + +data comparison_discards_the_dimension_it_judges: RecurringFailureMode = RecurringFailureMode { + identity: "comparison_discards_the_dimension_it_judges" as NonEmptyStr, + + receipts: [ + "**a check that normalizes away the very dimension it exists to judge** (the range is complete, the operands are the right two, and the comparison is lossy -- so the check is correct everywhere a reader looks and answers the wrong question at every site. ", + + "Recognition rule, keyed on the shape rather than on any one check: for any comparison, name what it COMPARES and what it DISCARDED before comparing, then ask whether the property being judged survives the discard. ", + + "**Reading the logic of the check cannot find this**, which is why it survived: the comparison itself is right, and the defect is upstream of it in the operand preparation. ", + + "**NOT `total_at_the_level_examined_blind`, which is the nearest neighbour and has the opposite information state.** There the deciding distinction is PRESENT in the value being matched and the match declines to descend into the arm holding it, so the repair is to descend; here the dimension has been REMOVED from the operands before the comparison runs, so descending finds nothing and the repair is to stop discarding. ", + + "**NOT `check_subject_narrower_than_its_declared_claim`** either, whose recognition rule asks which sites, files and spellings the implementation VISITS: this class has a complete range -- both seams visit exactly the right positions -- so asking what population the check visited cannot find it. ", + + "**SPECIMEN** (gunbc#10187, `v1.compiler.infer`): `direct_call_arg_type_mismatch` at argument position and `field_type_diags` at record-literal field init each apply `with_required_cardinality` to the DECLARED side and then compare KERNELS, so cardinality -- the dimension deciding whether an optional may flow into a required position -- is normalized out of both operands before the comparison. ", + + "A field declared `String` accepted a value typed `Optional` with no diagnostic, which made a method's declared return type NON-LOAD-BEARING at every assignment and argument position. ", + + "**Executed, at two sites with two symptoms and one root**, which is also why one reproduction was not the population: changing `first()`'s declared return type broke `extdeps.git` at runtime in the evaluator with \"cannot concat on Variant\" two calls downstream, and `extdeps.bmc` with `NoSuchField` on `Optional`. ", + + "**Rung found at: below the ladder.** DESIGN section 4b names \"values inhabit declared types\" as part of the ordinary compiler floor, and a failure there is a below-baseline safety regression never compensated by higher-order capability. ", + + "**Ceiling: structural**, because the judgment is decidable -- compare the cardinality dimension instead of discarding it -- and the repair is one predicate wired at both seams, one-directional because required-into-optional is widening and loses nothing. ", + + "**Next-rung trigger, as a capability**: both position seams judging every dimension their operands carry, rather than a kernel projection of them. ", + + "**THE DIAGNOSTIC IS THE FREE EVIDENCE, AND IT IS THE EASIEST THING TO READ PAST**: a diagnostic renders WHAT THE CHECKER ACTUALLY COMPARED, not what the source says, so a rendering that disagrees with the declaration visible in the source is primary evidence about the INSTRUMENT'S INPUTS rather than about the subject. ", + + "Here the message rendered a formal declared `ProbeS?` as `Coproduct(ProbeS)` in every instance, which is the peeled operand confessing itself; it was read past twice because it is dressed as a statement about the program. When a declared type renders without the dimension being judged, the disagreement IS the finding. ", + + "**THE CLASS REACHED ITS OWN AUTHOR WITHIN HOURS OF BEING FILED**, which is evidence about how easy it is to reach rather than about any one lane: the repair for this very class was written with its argument seam judging `app.formal`, where `formal` is `peel_nominal_alias_identity(formal_subst)` -- so the check built to judge the cardinality dimension discarded that dimension from its own declared operand. ", + + "It was found by a four-cell fixture (each seam crossed with declared-optional and declared-required) rather than by any count, and exactly one cell was wrong while both true-positive cells fired -- the pairing that distinguishes a broken operand from a vacuous check. ", + + "**A DERIVED EXCLUSION MASKED IT**: bare-`none` values were excluded at both seams by deriving the predicate from its existing owner, which is correct by DESIGN section 3 and still treated a symptom -- with the declared side read correctly the excluded sites are not mismatches at all, so the exclusion had no work to do and its presence is why nobody asked why the check believed the wrong thing. ", + + "**THE CENSUS OF THIS CLASS IS ITSELF BLOCKED ON ONE MISSING CAPABILITY, AND IT IS THE SAME ROOT TWICE.** Measuring the population required naming, per site, which expression PRODUCED the possibly-absent value and whether a preceding branch already proved it present. Both were attempted over SOURCE TEXT and both failed in the same way. ", + + "Producer naming failed on 32 of 118 sites because the diagnostic span points at the ENCLOSING expression rather than the call, so the read begins mid-token or at a lambda head; the sites were counted into a declared unclassified bucket rather than dropped, which is the only reason the shortfall is visible at all. ", + + "Guard detection failed in the other direction and by an unbounded amount: a narrow predicate answered 50 guarded of 118 and a wider one 85, disagreeing on 35 sites, because each was keyed to remembered spellings of a proof -- `count() == 0` found, `length(parts) != 2` missed at `extdeps.container.oci.digest`, `count(segs) >= 2` missed at `gunbc.roadmap.roadmap_dispatch_actuator`. Enumerating spellings is not the repair; each new form is discovered only by reading a site the predicate got wrong. ", + + "**NEXT-RUNG TRIGGER FOR THE CENSUS, STATED AS ONE CAPABILITY**: an AST-grain reader over the RESOLVED program that answers, for a site, both its producing expression and the branch conditions dominating it. Not a better classifier, not another predicate, and not a per-question tool -- the two failures above are one root, and a trigger naming either alone would be satisfied while the census stayed unmeasurable. The compiler already holds this tree; the gap is that the measurement was taken beside it instead of from it. ", + + "**THE REPAIR IS TO MAKE THE PROOF UNNECESSARY, NOT TO MAKE IT VISIBLE** -- which is the whole content of the third repair kind and is easy to state backwards. Where a possibly-absent value reaches a required position behind a guard the checker cannot read, unwrapping discards a proof the author wrote, and exposing the guard to the type system is a larger project than the site deserves. Matching on the optional means NO PROOF IS NEEDED, because the absent case is decided rather than assumed. ", + + "Executed on five sites in three files (`extdeps.version.semver` `semver_compare_identifiers`, `extdeps.container.oci.digest` `oci_wire_digest_parts`, `std.occurrence_identity` `occurrence_id_list_is_prefix_of`): the regen closure went from 11 diagnostics to 0, which is what let the enforcing check accept the corpus it runs over and released a bootstrap deadlock in which the check refused before emit and so blocked regeneration of its own fix. ", + + "**AND A REPAIR THAT OBVIATES SOME CHECKS MUST PROVE SUBSUMPTION PER CHECK, BECAUSE ADJACENCY IS NOT SUBSUMPTION.** In `oci_wire_digest_parts` the matches prove NON-EMPTINESS while the neighbouring `length(parts) != 2` rejects three-or-more parts; removing it as newly-redundant would have been a silent widening wearing the costume of a simplification, arriving inside the safety repair itself. ", + + "**THE SECOND SPECIMEN IS THE SAME CLASS WITH A DIFFERENT WAY OF LOSING THE DIMENSION, AND IT IS THE MORE DANGEROUS ONE.** The first specimen PEELED the declared operand, discarding cardinality that was present. The second reads a declared operand on which cardinality was never established at all: a formal whose type is still an UNSUBSTITUTED type parameter. `node_carries_optional` answers `false` for it -- the identical `false` it gives a genuinely required position -- so the two are indistinguishable at the comparison, and the check concluded REQUIRED from an operand that carried no answer. ", + + "Peeled-formal and unsubstituted-formal are one class and not two, because in both the comparison ran on an operand that did not carry the dimension being judged; they differ only in whether the dimension was stripped or never arrived. Filing them separately would have produced two narrow repairs and no rule. ", + + "**AND THE SECOND SPECIMEN IS ALSO AN ABSORBING FALLBACK (DESIGN section 5), WHICH THE FIRST WAS NOT.** A two-valued result has nowhere to put a could-not-tell, so the unknowable case took the accusing arm -- the mechanism that cannot compute its answer substituted the widest one -- and because the widening emitted a LOCATED, TYPED diagnostic it read as the check working. That is the failure arm wearing the costume of the success arm. The repair is a third value: the judgment now answers `NarrowsToRequired | ConformsOrWidens | NarrowingUndetermined`, and the undetermined case declines to judge rather than concluding not-optional. ", + + "**THE SAME DEFECT PREDICTS FALSE NEGATIVES, WHICH IS WHY A CLEAN AFTER-MEASUREMENT WOULD BE THE ALARMING RESULT.** An operand that cannot carry optionality also cannot carry it where it genuinely IS optional, so the pre-repair check was silent at real defects as well as noisy at non-defects. A before/after identity join over the firing sites must therefore report NEWLY-APPEARING as its own cell: cleared-and-surviving alone cannot distinguish a repair from a silencer, and a newly-appearing count of zero after a substitution repair is evidence the fix did not reach the cell it was aimed at -- not evidence of a clean result. ", + + "**A TRIAGE CORRECTION BELONGS HERE FOR THE SAME REASON THE DIAGNOSTIC DOES.** Two sites were bucketed as generic-substitution artifacts because their declared type RENDERED EMPTY. Reading them (`extdeps.transports.rest`, the `RestFixtureScan` construction) shows a let-bound `first()` whose field is then accessed through the optional base: real defects of the guarded-let shape, with a degraded RENDERING. The rendering defect and the judgment defect are different faults, and collapsing them moved two true positives into an artifact bucket -- the artifact population is 8, not 10. ", + + "**THE PREDICATE IS WIRED AT BOTH SEAMS AND A NARROWER QUESTION IS STILL OPEN AT ONE OF THEM, WHICH IS A DIFFERENT SENTENCE AND MUST NOT BE COLLAPSED INTO THIS ONE.** Both the direct-call argument seam and the record-literal field seam now judge the cardinality dimension instead of discarding it, and both derive the same bare-`none` exclusion, so the class this row names is repaired at its full measured range. What is NOT settled at the field seam is the prior question of WHICH declared field the position expects when the record-literal instantiation cannot be classified at all -- an operand that was never established rather than one that was stripped. That is a separate subject with its own classification, cause carrier and fixtures, separately routed, and the fixtures here are deliberately confined to positions whose required type is already known so that a green cannot be read as covering it.\n", + + "**NOT ESTABLISHED HERE**: whether other checks in the tree prepare their operands the same way. This row names one class found at two seams; the general audit is the trigger's own subject and is not claimed by this row.", + ], + + evidence: [], +} diff --git a/dag/gunbc/recurring_failure_mode/declared_type_inhabitance_unchecked_by_position.dag b/dag/gunbc/recurring_failure_mode/declared_type_inhabitance_unchecked_by_position.dag new file mode 100644 index 00000000000..abe66c52d19 --- /dev/null +++ b/dag/gunbc/recurring_failure_mode/declared_type_inhabitance_unchecked_by_position.dag @@ -0,0 +1,32 @@ +module gunbc.recurring_failure_mode.declared_type_inhabitance_unchecked_by_position + +import std.types { NonEmptyStr } +import gunbc.recurring_failure_mode { RecurringFailureMode } + +data declared_type_inhabitance_unchecked_by_position: RecurringFailureMode = RecurringFailureMode { + identity: "declared_type_inhabitance_unchecked_by_position" as NonEmptyStr, + + receipts: [ + "**A BELOW-BASELINE FLOOR FAILURE, in DESIGN 4b's own words.** The ordinary compiler floor names `values inhabit declared types` alongside name resolution and exact-bijection binding, and says a failure there is a below-baseline safety regression never compensated by higher-order capability. This is that clause failing: a value of a wholly unrelated record type sits in a declared position and no diagnostic is produced. It ranks above every differentiating claim in the tree. ", + + "**The class is POSITIONAL, and genericity is a second axis that removes the check where it survives.** Measured with the discriminating matrix rather than a single site, because probing one position and filing at that width would send a reader to fix one arm of something general. Declared type CONCRETE then a GENERIC INSTANTIATION of the same shape, wrong-typed record literal in each of six positions: record field REFUSES then SILENT; direct call argument REFUSES then REFUSES; nested field REFUSES then SILENT; function RETURN silent then SILENT; let BINDING silent then SILENT; field declared through a type ALIAS silent then SILENT. ", + + "**So there are two classes here and they must not be merged.** (1) Generic-instantiation loss: field and nested positions hold for a concrete declared type and lose the wall when the same declared type is a generic instantiation. (2) Position-wide absence: return, let-binding and alias positions are unchecked for CONCRETE types too, so a function declared to return one record type may return an unrelated one with zero diagnostics. Only the direct-call argument seam enforces inhabitance in both columns. ", + + "**THE CHECK IS NOT MISSING AT THOSE POSITIONS; IT IS COMPARING THE WRONG THING.** Measured independently by a second session with primitive controls at the same positions: returning an `Int` where `A` is declared REFUSES, and returning a `String` where `Int` is declared REFUSES. So a return-position check EXISTS and catches primitives, and what passes through it is specifically a wrong RECORD LITERAL. That relocates the repair for whoever takes it -- not `add an inhabitance producer at return/binding/alias`, but `the existing comparison at those positions does not read a record literal's own type against the expected type`. It is the same shape as every other defect in this cluster: a comparison reading an axis that does not carry the question. ", + + "**AGREEMENT BETWEEN TWO AUTHORS ON ONE INSTRUMENT IS NOT CORROBORATION, and the row says so rather than banking the convergence.** Both measurements above used the same one-file harness and the same binary, which rules out author error and NOT instrument error -- a one-file corpus need not run every phase a full-corpus compile runs, and if a later pass is what would catch a return-position record mismatch, the probe would report a silence the production configuration does not have. The two harness validations (a bogus field refuses; two independent errors both report) establish that inference runs and that it is not fail-fast; NEITHER establishes phase parity with a whole-tree compile. The parity control is the probe placed INSIDE the full corpus and compiled with the argv CI uses, carrying a primitive control beside the mismatch so that a silence from a file nothing compiled cannot be read as a finding. ", + + "**Recognition rule**: for any refusal about a value against its DECLARED type, author the same mistake across positions -- field, argument, return, binding, nested, alias -- and across the concrete/generic axis. A wall present in one cell and absent in another is a wall whose declared subject is a superset of the population it ranges over. Reading the check cannot find it, because the check is correct wherever it runs; what is missing is a producer at the other positions. ", + + "**A corpus census cannot discover this class**: the silent cells emit nothing, so there is no diagnostic to count and no site list to join. It is reachable only by authoring the discriminating matrix, which is why the entry cost is a fixture harness rather than a lens. ", + + "**THE HARNESS EXISTS AND IS CHEAP, WHICH RETIRES THE STANDARD EXCUSE FOR LEAVING A CLASS AT UNAUTHORABLE-RED.** A one-file corpus under a workspace-relative source root, compiled with `gunbc compile --source-root --target dag --output-dir `, runs FULL INFERENCE at roughly a minute per probe. Verified two ways before any finding was drawn from it: a bogus field name refuses (so inference runs), and a file with two independent errors reports BOTH (so it is not fail-fast and a single diagnostic is not masking the rest). DESIGN 4b says to ask whether a check's RED is authorable in a fixture before calling a ceiling permanent; this is that fixture, and its cost is minutes. ", + + "**The control that separates cause from coincidence is mandatory for this class**, because it is typically discovered while editing the generic path. Here the class was found while a record-literal instantiation gate was under edit, so the gate was flipped from admitting to refusing and the probe re-run: zero diagnostics BOTH WAYS, establishing the silence is upstream and pre-existing rather than caused by the edit that found it. That gate is NOT part of this change -- it and its fixtures are separately routed -- and the control is reported anyway precisely because its result is that the gate is not the cause. A class found inside one's own diff is not thereby caused by it, and claiming it so the change looks thorough is the mirror error of hiding it. ", + + "**NOT `check_subject_narrower_than_its_declared_claim`**, whose repair is to widen the range a check visits: several of these positions have no inhabitance producer at all, so there is no range to widen. **NOT `absorbing_fallback`**: nothing widens to accept, the value simply reaches a producer of fields where another position reaches a producer of judgments. ", + ], + + evidence: [], +} diff --git a/dag/gunbc/recurring_failure_mode/instrument_renders_one_scope_while_adjudicating_another.dag b/dag/gunbc/recurring_failure_mode/instrument_renders_one_scope_while_adjudicating_another.dag new file mode 100644 index 00000000000..e49f6e053ad --- /dev/null +++ b/dag/gunbc/recurring_failure_mode/instrument_renders_one_scope_while_adjudicating_another.dag @@ -0,0 +1,26 @@ +module gunbc.recurring_failure_mode.instrument_renders_one_scope_while_adjudicating_another + +import std.types { NonEmptyStr } +import gunbc.recurring_failure_mode { RecurringFailureMode } + +data instrument_renders_one_scope_while_adjudicating_another: RecurringFailureMode = RecurringFailureMode { + identity: "instrument_renders_one_scope_while_adjudicating_another" as NonEmptyStr, + + receipts: [ + "**one run carries two different scopes and prints only one of them**, under a header bearing the run's own name -- so a reader who takes the printed roster as the scope of the number they are computing is reading a TRUE statement about a DIFFERENT phase. ", + + "**SPECIMEN** (gunbc, 2026-09-04): the required witnesses lane announces `phase parse (.dag: src/v1, dag, src/v2)`, rendering `v1.cli_run` `DAG_PARSE_SWEEP_ROOTS`, a hardcoded three-element constant that `run_dag_parse_sweep` consumes WITHOUT reading `--source-root` at all. Every other phase in the same run is scoped by the argv's two roots, `dag` and `src/v2`. Both rosters are correct; only one is printed. ", + + "**IT MISLED TWO READERS IN OPPOSITE DIRECTIONS ON ONE EVENING, WHICH IS WHAT MAKES IT A CLASS RATHER THAN A SLIP.** One read the printed roster and concluded the enforcing check's population included `src/v1` -- wrong, because that check is resolution-scoped to the argv roots. The other grepped the workflow for `--source-root`, found six flags naming two roots, and concluded the lane never touches `src/v1` -- also wrong, because a phase with a hardcoded roster is invisible to that grep. ", + + "**THE DIRECT READING WAS THE CORRECT ONE AND IT LOST TO THE CONFIDENT INFERENCE.** The first reader had the log line in front of them; the second had an inference from a different file and stated it with certainty, and the first retracted a true observation. So the residual harm was not the scope error at all -- it was a correct measurement withdrawn under someone else's confidence, which no amount of care by the retracting party would have prevented. ", + + "**RECOGNITION RULE**: whenever an instrument prints a scope, a root list, a roster or a population, ask whether the PHASE THAT PRODUCED YOUR NUMBER is the phase that printed it. A header names the run; it does not name the subject of every figure inside the run. And grepping the invocation for scope flags finds only argv-driven scopes -- a hardcoded roster is a scope the invocation cannot show you. ", + + "**RUNG FOUND AT: 1 (mitigatable)** -- careful readers can cross-check the per-phase roster against the source, and here two did and disagreed. **CEILING: structural**: the run already holds each phase's effective roster at the moment it announces the phase, so rendering it is construction rather than validation. ", + + "**NEXT-RUNG TRIGGER, AS A CAPABILITY**: every announced phase rendering its OWN effective roster, so that no printed scope can belong to a phase other than the one it labels. Not a corrected constant and not a documentation note -- the defect is that one roster is rendered for a run carrying several.", + ], + + evidence: [], +} diff --git a/dag/gunbc/recurring_failure_mode/result_that_confirms_the_hypothesis_exactly.dag b/dag/gunbc/recurring_failure_mode/result_that_confirms_the_hypothesis_exactly.dag new file mode 100644 index 00000000000..b2502636802 --- /dev/null +++ b/dag/gunbc/recurring_failure_mode/result_that_confirms_the_hypothesis_exactly.dag @@ -0,0 +1,30 @@ +module gunbc.recurring_failure_mode.result_that_confirms_the_hypothesis_exactly + +import std.types { NonEmptyStr } +import gunbc.recurring_failure_mode { RecurringFailureMode } + +data result_that_confirms_the_hypothesis_exactly: RecurringFailureMode = RecurringFailureMode { + identity: "result_that_confirms_the_hypothesis_exactly" as NonEmptyStr, + + receipts: [ + "**A CHANGE THAT CLEARS ITS ENTIRE POPULATION IS EVIDENCE THE INSTRUMENT STOPPED MEASURING, NOT THAT THE FIX WORKED.** The failure mode is not a wrong number; it is a number that is wrong in the shape the author was hoping for, which suppresses the one check that would catch it. A result matching the hypothesis exactly is the result to distrust FIRST. ", + + "**MEASURED** (gunbc, 2026-09-04, repairing the optional-into-required check): three consecutive runs reported CLEARED=103 of 103 with NEWLY-APPEARING=0 -- a perfect clearance, exactly what the hypothesis predicted -- and all three were instrument failures with three DIFFERENT causes. Run one invoked a subcommand spelled with a hyphen that does not exist. Run two invoked it with an underscore, which also does not exist, because it is a separate BINARY and not a subcommand at all. Run three reached the real binary and ran the real lane, and then grep silently switched to binary mode on a NUL byte in the log, emitting no lines while grep -c on the same file kept counting. The true answer was 1. ", + + "**THE THREE CAUSES SHARE NO MECHANISM, WHICH IS THE POINT**: two were argument errors and one was an encoding behaviour in a downstream text tool. What made them one failure mode is that each produced ZERO EXTRACTED SITES, and zero extracted sites renders as total success for a repair. Every instrument in the chain fails toward the answer the author wants. ", + + "**THE DISCRIMINATOR IS A POSITIVE CONTROL COUNTING THE SUBJECT AT ITS COARSEST GRAIN** -- here, diagnostics of ANY kind in the same log. At 0 it exposed runs one and two as never having compiled anything. At 206 beside an extracted 0 it exposed run three as an EXTRACTION fault rather than a compiler result, which is a distinction the numerator alone cannot carry. One line of instrument, three defects caught. ", + + "**A NON-ZERO EXIT WAS PRESENT AND READ PAST TWICE.** Runs one and two exited 2, and this same lane had recorded hours earlier that RC=2 from this binary family is a USAGE error rather than a verdict. A status code disagreeing with a plausible result loses to the result, because the result is the thing being looked for. The log's first five lines said unrecognized subcommand the entire time. ", + + "**THE MIRROR-IMAGE INSTANCE IS SUBTLER AND ARRIVED THE SAME HOUR**: a SMALL, NON-ZERO delta is more dangerous than a perfect one. The same lane edited `src/v1/04_infer.dag` without regenerating the stage0 seed that cargo actually compiles, measured a 103 -> 102 change, and attributed the single cleared site to a construct the binary did not contain (7 occurrences in the `.dag`, 0 in `v1_compiler_infer.rs`). A zero delta would have prompted a check; a small believable one did not. ", + + "**RECOGNITION RULE**: before reporting that a change cleared a population, ask what the instrument would print if it had not run at all -- and if that is indistinguishable from the reported result, the run establishes nothing. Then require, in the same output, a coarse-grained count that must be NON-ZERO for the fine-grained count to be readable. ", + + "**NEXT-RUNG TRIGGER**: a measurement harness that emits its subject-population count and its extraction count as one typed receipt, so an extraction yielding zero over a non-empty subject REFUSES rather than reporting a clean sweep. Until that exists this is mitigatable-by-discipline only, and the discipline is the positive control. ", + + "**NOT ESTABLISHED**: whether other lanes' before/after reports in this repo carry the same defect. This row names the class and its discriminator; auditing existing published deltas for uncompiled changes and empty extractions is a separate subject.", + ], + + evidence: [], +} diff --git a/dag/gunbc/recurring_failure_mode/roster.dag b/dag/gunbc/recurring_failure_mode/roster.dag index 520d3a5cbfe..f339282cf3c 100644 --- a/dag/gunbc/recurring_failure_mode/roster.dag +++ b/dag/gunbc/recurring_failure_mode/roster.dag @@ -25,6 +25,7 @@ import gunbc.recurring_failure_mode.coercion_proven_by_normalized_round_trip { c import gunbc.recurring_failure_mode.parallel_representation_debt { parallel_representation_debt } import gunbc.recurring_failure_mode.internal_review_finds_missing_tests_external { internal_review_finds_missing_tests_external } import gunbc.recurring_failure_mode.unmarked_workaround { unmarked_workaround } +import gunbc.recurring_failure_mode.declared_type_inhabitance_unchecked_by_position { declared_type_inhabitance_unchecked_by_position } import gunbc.recurring_failure_mode.self_authorized_dissolution { self_authorized_dissolution } import gunbc.recurring_failure_mode.positional_citation { positional_citation } import gunbc.recurring_failure_mode.bound_shaped_closure { bound_shaped_closure } @@ -106,6 +107,10 @@ import gunbc.recurring_failure_mode.content_digest_makes_annotations_semanticall import gunbc.recurring_failure_mode.subject_and_its_digest_as_independent_parameters { subject_and_its_digest_as_independent_parameters } import gunbc.recurring_failure_mode.a_written_row_is_not_a_firing_mechanism { a_written_row_is_not_a_firing_mechanism } import gunbc.recurring_failure_mode.required_evidence_absent_reads_as_evidence_of_pass { required_evidence_absent_reads_as_evidence_of_pass } +import gunbc.recurring_failure_mode.comparison_discards_the_dimension_it_judges { comparison_discards_the_dimension_it_judges } +import gunbc.recurring_failure_mode.source_text_census_counts_its_own_documentation { source_text_census_counts_its_own_documentation } +import gunbc.recurring_failure_mode.instrument_renders_one_scope_while_adjudicating_another { instrument_renders_one_scope_while_adjudicating_another } +import gunbc.recurring_failure_mode.result_that_confirms_the_hypothesis_exactly { result_that_confirms_the_hypothesis_exactly } import gunbc.recurring_failure_mode.right_censored_cost_read_as_exact { right_censored_cost_read_as_exact } import gunbc.recurring_failure_mode.guard_precondition_discharged_by_the_route_that_uses_it { guard_precondition_discharged_by_the_route_that_uses_it } import gunbc.recurring_failure_mode.reachability_answered_is_consumed_as_protection_established { reachability_answered_is_consumed_as_protection_established } @@ -134,6 +139,7 @@ data recurring_failure_mode_roster: List = [ parallel_representation_debt, internal_review_finds_missing_tests_external, unmarked_workaround, + declared_type_inhabitance_unchecked_by_position, self_authorized_dissolution, positional_citation, bound_shaped_closure, @@ -215,6 +221,10 @@ data recurring_failure_mode_roster: List = [ subject_and_its_digest_as_independent_parameters, a_written_row_is_not_a_firing_mechanism, required_evidence_absent_reads_as_evidence_of_pass, + comparison_discards_the_dimension_it_judges, + source_text_census_counts_its_own_documentation, + instrument_renders_one_scope_while_adjudicating_another, + result_that_confirms_the_hypothesis_exactly, right_censored_cost_read_as_exact, guard_precondition_discharged_by_the_route_that_uses_it, reachability_answered_is_consumed_as_protection_established, diff --git a/dag/gunbc/recurring_failure_mode/source_text_census_counts_its_own_documentation.dag b/dag/gunbc/recurring_failure_mode/source_text_census_counts_its_own_documentation.dag new file mode 100644 index 00000000000..24040013d26 --- /dev/null +++ b/dag/gunbc/recurring_failure_mode/source_text_census_counts_its_own_documentation.dag @@ -0,0 +1,30 @@ +module gunbc.recurring_failure_mode.source_text_census_counts_its_own_documentation + +import std.types { NonEmptyStr } +import gunbc.recurring_failure_mode { RecurringFailureMode } + +data source_text_census_counts_its_own_documentation: RecurringFailureMode = RecurringFailureMode { + identity: "source_text_census_counts_its_own_documentation" as NonEmptyStr, + + receipts: [ + "**a source-text census over this corpus counts the prose that DOCUMENTS a construct as instances OF that construct** -- and the effect is structural here rather than incidental, because DESIGN section 4c requires prose to live in TYPED CARRIERS, and those carriers are `.dag` data rows in the same syntax as code. ", + + "So a receipt quoting a defect verbatim is, to any matcher that reads bytes, indistinguishable from the defect. The corpus documents itself in its own language, which is exactly the property that makes the documentation reviewable and the census wrong. ", + + "**THE LEDGER IS THE DENSEST CONTAMINATOR, WHICH INVERTS THE USUAL EXPECTATION**: `gunbc.recurring_failure_mode` exists to quote defects precisely, so the file most committed to accurate citation is the one that most corrupts a count of the thing cited. The floor is not fixed -- it GROWS as the ledger grows, so a census re-run later is more contaminated, not less. ", + + "**MEASURED** (gunbc, 2026-09-03, censusing `first()`/`last()` over the roots DESIGN's Building-and-checks section declares -- `--source-root dag --source-root src/v2`): 660 raw matches, of which **19 sat inside string literals** and 641 were code positions, a 2.9% overstatement. Densest carriers: `state_space_conflation` 6, `gunbc.roadmap.roadmap_publish` 4, `extdeps.languages.rust.emit` 2, `std.languages` 2. ", + + "**THE SELF-REFERENCE IS THE SHARP EDGE**: two of the contaminating receipts were filed BY THE SAME LANE ON THE SAME NIGHT as the census they inflated. Writing up a defect measurably increases the measured population of that defect, so a lane diligently recording what it found makes its own next measurement worse, and nothing in either activity signals the interaction. ", + + "It surfaced only as a 3-occurrence disagreement between two independently built instruments, and it was attributed to merge drift first -- the commits were checked and carried none of the shape, which is what forced the real cause out. A single instrument would have reported the inflated number with no disagreement to investigate. ", + + "**RUNG FOUND AT: 1 (mitigatable)** -- a reviewer can split string-literal spans from code positions by hand, and this row is the only thing that would prompt them to. **CEILING: structural**, since the distinction is fully decided by the resolved program: a string literal and a call are different nodes, and the compiler already holds that tree. ", + + "**NEXT-RUNG TRIGGER, AS A CAPABILITY**: an AST-grain reader over the resolved program that answers population questions from nodes rather than bytes. Not a smarter regex and not a per-census exclusion list -- the same capability that the enclosing-span and guard-detection failures of `comparison_discards_the_dimension_it_judges` name, which is the third independent arrival at one missing tool. ", + + "**RECOGNITION RULE**: before publishing any population derived from matching source text in this repository, ask what fraction of the hits are inside string literals, and report the split. If the subject of the census is a defect class, expect the failure-mode ledger to be among the top contaminators, and expect the fraction to be worst for the classes most carefully documented.", + ], + + evidence: [], +} diff --git a/dag/gunbc/recurring_failure_mode/state_space_conflation.dag b/dag/gunbc/recurring_failure_mode/state_space_conflation.dag index 5df176f7ad7..b32072008cd 100644 --- a/dag/gunbc/recurring_failure_mode/state_space_conflation.dag +++ b/dag/gunbc/recurring_failure_mode/state_space_conflation.dag @@ -155,7 +155,25 @@ data state_space_conflation: RecurringFailureMode = RecurringFailureMode { "The guard's state space has no cell for content divergence, so its count is the same either way. ", - "What such a check must additionally do is adjudicate any surviving duplicate against main's BYTES and REFUSE when neither copy matches, rather than resolve by position or first-wins, which is silent.", + "What such a check must additionally do is adjudicate any surviving duplicate against main's BYTES and REFUSE when neither copy matches, rather than resolve by position or first-wins, which is silent. ", + + "**A FORM WITH THE OPPOSITE RUNG FROM THE FOURTH, WHICH IS WHY IT IS FILED SEPARATELY** (gunbc, 2026-09-02/03): `v1.compiler.infer` `field_summary_for_type` has an arm matching `field == \"value\"` on a normalized optional that claims `OptionalUnwrap` plus `PlainValue` BY SPELLING, with no inspection of whether the inner type declares its own `value` field -- and `Outcome` and `EvalResult` both do. ", + + "The fourth form is the same carrier and the same optional spellings but REFUSES with `NoSuchField`, which that row calls the whole of the good news; **this arm ANSWERS**. ", + + "The unwrap yields `Value::Null`, and `LiteralValue::LitNull` evaluating to `Value::Null` makes `null` an AUTHORABLE literal, so the fabricated result is not a similar spelling but THE SAME VALUE -- it hashes alike, prints as \"null\", and serializes to `PortableValue::Null`. ", + + "No downstream consumer, however careful, can separate \"the unwrap had nothing\" from \"the author wrote null\": absence of signal is recoverable by asking again, a valid-looking wrong value is not, which is DESIGN section 5 silent wrongness rather than a low rung. ", + + "**The repair is not inside the arm**, because the arm cannot distinguish the two nulls -- the information was destroyed upstream where `PlainValue` was claimed for an unverified spelling, and a fix inside the arm would have to GUESS which null it holds, which is the absorbing-fallback shape wearing a different hat. ", + + "Rung found at 1, and only because a corpus annotation documents it; **ceiling structural**, since membership is decidable by inspecting the inner type before claiming the payload, and the distance between decidable and mitigatable is the whole argument for this receipt. ", + + "**Next-rung trigger as a capability**: `field_summary_for_type` resolving `.value` on an optional by consulting the inner type's declared fields and refusing or preferring the inner field where both could answer -- not merely adding a check. ", + + "Reached independently three times, which is evidence about the DEFECT rather than about diligence -- easy to reach and hard to see is the pair that ranks a class for climbing: twice by two lanes reading the arm for unrelated questions, and once as `extdeps.bmc` `pid_control_decode`, a pre-existing minimal reproduction already in the corpus and measured both ways. ", + + "**Deliberately NOT repaired by the `first()`/`last()` change that found it**, which preserves the pre-existing null result rather than widening its own subject.", ], evidence: [], diff --git a/dag/gunbc/roadmap/roadmap_dispatch_actuator.dag b/dag/gunbc/roadmap/roadmap_dispatch_actuator.dag index ee5b2ac4782..c7dd09743ad 100644 --- a/dag/gunbc/roadmap/roadmap_dispatch_actuator.dag +++ b/dag/gunbc/roadmap/roadmap_dispatch_actuator.dag @@ -1877,14 +1877,13 @@ fn tmux_session_observation_for_scope( ) -> TmuxSessionObservation { let scoped_name = scope.session_name as String let matched = entries |> filter(e => e.session_name == scoped_name) - if count(matched) == 0 { - SessionAbsent - } else { - let e = matched.first() - SessionNameObserved { - session_name: scope.session_name, - windows: e.windows, - } + match matched.first() { + Absent => SessionAbsent + Present { value: e } => + SessionNameObserved { + session_name: scope.session_name, + windows: e.windows, + } } } @@ -2310,14 +2309,17 @@ type TmuxPaneEntry { fn parse_tmux_pane_line(line: String) -> TmuxPaneEntry? { let segs = split(s: line, delimiter: " ") - if count(segs) >= 2 && segs.first() != "" { - let name = segs.first() - Present { value: TmuxPaneEntry { - session_name: name, - command: substring(s: line, start: string_length(s: name) + 1, end: string_length(s: line)), - } } - } else { - none + match segs.first() { + Absent => none + Present { value: name } => + if count(segs) >= 2 && name != "" { + Present { value: TmuxPaneEntry { + session_name: name, + command: substring(s: line, start: string_length(s: name) + 1, end: string_length(s: line)), + } } + } else { + none + } } } diff --git a/dag/gunbc/roadmap/roadmap_launch_deployment_cli.dag b/dag/gunbc/roadmap/roadmap_launch_deployment_cli.dag index 9b4071573c4..e4b040d0941 100644 --- a/dag/gunbc/roadmap/roadmap_launch_deployment_cli.dag +++ b/dag/gunbc/roadmap/roadmap_launch_deployment_cli.dag @@ -174,7 +174,10 @@ fn read_remote_main_hex() -> RemoteRefRead { if line == "" { RemoteRefUnreadable { detail: join(["origin advertises no ", main_ref_name], "") } } else { - match git_object_id_from_untagged_hex(hex: split(s: line, delimiter: "\t").first()) { + match (match split(s: line, delimiter: "\t").first() { + Absent => none + Present { value: hex } => git_object_id_from_untagged_hex(hex: hex) + }) { Present { value: oid } => RemoteRefHex { hex: git_object_id_wire_hex(oid: oid) as String } Absent => RemoteRefUnreadable { detail: join(["origin advertises an undecodable ", main_ref_name, ": ", line], "") } } @@ -207,10 +210,27 @@ fn transition_text(s: ActuationStanding) -> String { } } -fn deployed_tree_hexes(o: DeployedTreeObservation) -> List { +// The two hexes are a NAMED PAIR, not a two-element list. As a list the caller reached them with +// .first() and .last(), so the LIST ORDER decided which hex was the revision and which the tree -- +// a positional naming scheme for two things the observation already names, and one that reports a +// tree hex as a revision if the pair is ever built in the other order. +type DeployedTreeHexes { + revision_hex: String + tree_hex: String +} + +fn deployed_tree_hexes(o: DeployedTreeObservation) -> DeployedTreeHexes { match o { - DeployedTreeObserved { revision: r, tree: t, content: _ } => [git_object_id_wire_hex(oid: r) as String, git_object_id_wire_hex(oid: t) as String] - DeployedTreeUnobservable { cause: c } => [join(["unobserved: ", deployed_tree_unobservable_text(cause: c)], ""), "unobserved"] + DeployedTreeObserved { revision: r, tree: t, content: _ } => + DeployedTreeHexes { + revision_hex: git_object_id_wire_hex(oid: r) as String, + tree_hex: git_object_id_wire_hex(oid: t) as String, + } + DeployedTreeUnobservable { cause: c } => + DeployedTreeHexes { + revision_hex: join(["unobserved: ", deployed_tree_unobservable_text(cause: c)], ""), + tree_hex: "unobserved", + } } } @@ -252,8 +272,8 @@ func window_snapshot(context: FleetSshExecutionContext, instance: HostDashboardI WindowSnapshot { main_hex: remote_ref_text(r: read_remote_main_hex()), desired_hex: remote_ref_text(r: read_desired_hex()), - deployed_revision_hex: hexes.first(), - deployed_tree_hex: hexes.last(), + deployed_revision_hex: hexes.revision_hex, + deployed_tree_hex: hexes.tree_hex, running_release_hex: running_release_hex_routed(base: routed_base), transition: transition_text(s: transition_actuation_standing(instance_root: instance.instance_root as String)), active_instance: active_instance_text_routed(base: routed_base), diff --git a/dag/gunbc/roadmap/roadmap_model.dag b/dag/gunbc/roadmap/roadmap_model.dag index 4a099cc4a19..e5a8aa7e3ec 100644 --- a/dag/gunbc/roadmap/roadmap_model.dag +++ b/dag/gunbc/roadmap/roadmap_model.dag @@ -87,10 +87,9 @@ fn roadmap_parent_ids(edges: List, node: RoadmapNodeId) -> List, node: RoadmapNodeId) -> RoadmapParent { let parents = roadmap_parent_ids(edges: edges, node: node) - if count(parents) == 0 { - top_level() - } else { - under_parent(p: first(parents)) + match first(parents) { + Absent => top_level() + Present { value: parent } => under_parent(p: parent) } } @@ -484,18 +483,22 @@ fn acceptance_history_prior_prefix_mismatch_index_at( current: List, index: Int, ) -> Int { - if count(prior) == 0 { - index - } else if count(current) == 0 { - index - } else if !acceptance_event_eq(a: first(prior), b: first(current)) { - index - } else { - acceptance_history_prior_prefix_mismatch_index_at( - prior: drop_first_acceptance_event(events: prior), - current: drop_first_acceptance_event(events: current), - index: index + 1, - ) + match first(prior) { + Absent => index + Present { value: prior_head } => + match first(current) { + Absent => index + Present { value: current_head } => + if !acceptance_event_eq(a: prior_head, b: current_head) { + index + } else { + acceptance_history_prior_prefix_mismatch_index_at( + prior: drop_first_acceptance_event(events: prior), + current: drop_first_acceptance_event(events: current), + index: index + 1, + ) + } + } } } @@ -510,16 +513,22 @@ fn acceptance_history_extends_prior( prior: List, current: List, ) -> Bool { - if count(prior) == 0 { - true - } else if count(current) < count(prior) { - false - } else { - acceptance_event_eq(a: first(prior), b: first(current)) - && acceptance_history_extends_prior( - prior: drop_first_acceptance_event(events: prior), - current: drop_first_acceptance_event(events: current), - ) + match first(prior) { + Absent => true + Present { value: prior_head } => + if count(current) < count(prior) { + false + } else { + match first(current) { + Absent => false + Present { value: current_head } => + acceptance_event_eq(a: prior_head, b: current_head) + && acceptance_history_extends_prior( + prior: drop_first_acceptance_event(events: prior), + current: drop_first_acceptance_event(events: current), + ) + } + } } } @@ -605,27 +614,18 @@ fn acceptance_history_integrity_verdict( match replay_acceptance_history(events: history) { Absent => AcceptanceHistoryIntegrityRefusedReplay Present { value: state } => - if !all( - state.ever_recorded, - r => ever_recorded_receipt_accounted_for( - receipt: r, - live: state.live, - revoked: state.revoked, + match first( + state.ever_recorded |> filter(r => + !ever_recorded_receipt_accounted_for( + receipt: r, + live: state.live, + revoked: state.revoked, + ) ), ) { - AcceptanceHistoryIntegrityRefusedVanishedWithoutRevocation { - receipt: first( - state.ever_recorded |> filter(r => - !ever_recorded_receipt_accounted_for( - receipt: r, - live: state.live, - revoked: state.revoked, - ) - ), - ), - } - } else { - AcceptanceHistoryIntegrityHolds + Absent => AcceptanceHistoryIntegrityHolds + Present { value: unaccounted } => + AcceptanceHistoryIntegrityRefusedVanishedWithoutRevocation { receipt: unaccounted } } } } diff --git a/dag/gunbc/runner/runner_deploy_emit.dag b/dag/gunbc/runner/runner_deploy_emit.dag index 42b6408f379..e815ac4f1fd 100644 --- a/dag/gunbc/runner/runner_deploy_emit.dag +++ b/dag/gunbc/runner/runner_deploy_emit.dag @@ -209,7 +209,7 @@ fn session_slice_line(host: HostIdentity, ceiling: ByteSize) -> Doc { ), " oom_pressure_kill=true" ), - concat(" oom_pressure_limit_pct=", to_string(percent_count(p: gunbc_oomd_sessions_policy.managed_oom_memory_pressure_limit))) + session_slice_pressure_limit_segment(limit: gunbc_oomd_sessions_policy.managed_oom_memory_pressure_limit) ), concat(" cpu_weight=", to_string(workload_class_cpu_weight(wc: InteractiveLatencySensitive))) ) @@ -217,6 +217,17 @@ fn session_slice_line(host: HostIdentity, ceiling: ByteSize) -> Doc { } } +// The rendered line MIRRORS the knob list: oomd declares this limit optional, so a policy that +// states no limit renders no segment rather than a segment carrying an invented percentage. The +// renderer and gunbc.host_converge session_host_pressure_limit_knobs must agree on that, because a +// line describing a knob that is not emitted is a receipt for work that never happens. +fn session_slice_pressure_limit_segment(limit: Percent?) -> String { + match limit { + Absent => "" + Present { value: p } => concat(" oom_pressure_limit_pct=", to_string(percent_count(p: p))) + } +} + fn session_slice_doc() -> Doc { match session_admission_oomd_ceiling(p: gunbc_session_admission_policy) { Absent => diff --git a/dag/gunbc/srv3/srv3_os_install_diagnostic.dag b/dag/gunbc/srv3/srv3_os_install_diagnostic.dag index 5c9c92bdfa9..7649f124620 100644 --- a/dag/gunbc/srv3/srv3_os_install_diagnostic.dag +++ b/dag/gunbc/srv3/srv3_os_install_diagnostic.dag @@ -1186,16 +1186,22 @@ fn parse_serve_port_observation(stdout: String, intent: OsInstallAttemptIntent) fn parse_observe_content_hash_observed(stdout: String) -> ContentHash? { let parts = split(s: stdout, delimiter: "content_hash_observed=") - if parts.length() <= 1 { - none - } else { - let tail = parts.skip(n: 1).first() - let line = split(s: tail, delimiter: "\n").first() - match fnv1a64_structural_hex_digest(hex: split(s: line, delimiter: " ").first()) { - Present { value: structural } => - Present { value: as_content_hash_structural(structural: structural) } - Absent => none - } + match parts.skip(n: 1).first() { + Absent => none + Present { value: tail } => + match split(s: tail, delimiter: "\n").first() { + Absent => none + Present { value: line } => + match split(s: line, delimiter: " ").first() { + Absent => none + Present { value: hex } => + match fnv1a64_structural_hex_digest(hex: hex) { + Present { value: structural } => + Present { value: as_content_hash_structural(structural: structural) } + Absent => none + } + } + } } } diff --git a/dag/std/effect_grant.dag b/dag/std/effect_grant.dag index 04d0f6fbc0c..9773d953aa4 100644 --- a/dag/std/effect_grant.dag +++ b/dag/std/effect_grant.dag @@ -185,15 +185,14 @@ fn grant_coverage_fold( // fail-closed. fn grant_coverage_go(grants: List, verb: Verb, target: NamespacePosition) -> GrantCoverage { - if grants.count() == 0 { - GrantNotCovered { verb: verb, target: target } - } else { - let g = grants.first() - if grant_covers(grant: g, verb: verb, target: target) { - GrantCoveredBy { grant: g } - } else { - grant_coverage_go(grants: grants.skip(n: 1), verb: verb, target: target) - } + match grants.first() { + Absent => GrantNotCovered { verb: verb, target: target } + Present { value: g } => + if grant_covers(grant: g, verb: verb, target: target) { + GrantCoveredBy { grant: g } + } else { + grant_coverage_go(grants: grants.skip(n: 1), verb: verb, target: target) + } } } @@ -282,22 +281,20 @@ fn admit_effect(env: Envelope, verb: Verb, target: NamespacePosition) -> AccessD } fn parent_covers_grant(parent_grants: List, child_grant: Grant) -> Bool { - if parent_grants.count() == 0 { - false - } else { - let pg = parent_grants.first() - (verb_eq(a: grant_verb(g: pg), b: grant_verb(g: child_grant)) && position_under(target: grant_root(g: child_grant), root: grant_root(g: pg))) - || parent_covers_grant(parent_grants: parent_grants.skip(n: 1), child_grant: child_grant) + match parent_grants.first() { + Absent => false + Present { value: pg } => + (verb_eq(a: grant_verb(g: pg), b: grant_verb(g: child_grant)) && position_under(target: grant_root(g: child_grant), root: grant_root(g: pg))) + || parent_covers_grant(parent_grants: parent_grants.skip(n: 1), child_grant: child_grant) } } fn all_child_grants_bounded(child_grants: List, parent_grants: List) -> Bool { - if child_grants.count() == 0 { - true - } else { - let cg = child_grants.first() - parent_covers_grant(parent_grants: parent_grants, child_grant: cg) - && all_child_grants_bounded(child_grants: child_grants.skip(n: 1), parent_grants: parent_grants) + match child_grants.first() { + Absent => true + Present { value: cg } => + parent_covers_grant(parent_grants: parent_grants, child_grant: cg) + && all_child_grants_bounded(child_grants: child_grants.skip(n: 1), parent_grants: parent_grants) } } diff --git a/dag/std/occurrence_identity.dag b/dag/std/occurrence_identity.dag index da11dcac247..46e13251944 100644 --- a/dag/std/occurrence_identity.dag +++ b/dag/std/occurrence_identity.dag @@ -446,23 +446,28 @@ fn occurrence_id_list_is_prefix_of( f: (acc, expected) => if !acc.ok { acc - } else if (acc.path_remaining |> count) == 0 { - OccurrenceIdListPrefixAcc { - path_remaining: [], - ok: false, - } - } else if occurrence_id_eq( - left: acc.path_remaining.first(), - right: expected, - ) { - OccurrenceIdListPrefixAcc { - path_remaining: acc.path_remaining.skip(n: 1), - ok: true, - } } else { - OccurrenceIdListPrefixAcc { - path_remaining: acc.path_remaining, - ok: false, + match acc.path_remaining.first() { + Absent => + OccurrenceIdListPrefixAcc { + path_remaining: [], + ok: false, + } + Present { value: head } => + if occurrence_id_eq( + left: head, + right: expected, + ) { + OccurrenceIdListPrefixAcc { + path_remaining: acc.path_remaining.skip(n: 1), + ok: true, + } + } else { + OccurrenceIdListPrefixAcc { + path_remaining: acc.path_remaining, + ok: false, + } + } } }, ).ok diff --git a/dag/std/realization_schedule.dag b/dag/std/realization_schedule.dag index eb74cba9982..10707468697 100644 --- a/dag/std/realization_schedule.dag +++ b/dag/std/realization_schedule.dag @@ -584,28 +584,37 @@ fn schedule_witness_entry_roster_contains( fold(xs, init: false, f: fn(found, x) { found || schedule_witness_entry_eq(a: x, b: w) }) } -fn string_list_eq(left: List, right: List) -> Bool { - if left.count() != right.count() { - false - } else if left.count() == 0 { - true - } else if left.first() != right.first() { - false - } else { - string_list_eq(left: left.skip(n: 1), right: right.skip(n: 1)) +// ONE FOLD FOR FOUR LIST EQUALITIES, AND THE REASON IT MATCHES RATHER THAN ASSERTS. +// Four functions here were the same recursion modulo the element comparison, each opening with +// a count()-pair guard and then calling first() on both sides. That shape is why the optional +// arrives at a required position: first() is total and returns an Optional, the emptiness proof +// lives in a branch the type checker cannot read, and every copy reproduced the same unread proof. +// Unwrapping would have discarded the author's proof four times over; matching CONSUMES the +// optional, so the absent case is decided rather than assumed and no proof is needed. +// It is also cheaper: the count() pair was recomputed at every level, so the old shape paid a +// linear scan per element. +fn list_eq_by(left: List, right: List, eq: fn(T, T) -> Bool) -> Bool { + match left.first() { + Absent => + match right.first() { + Absent => true + Present { value: _ } => false + } + Present { value: l } => + match right.first() { + Absent => false + Present { value: r } => + eq(l, r) && list_eq_by(left: left.skip(n: 1), right: right.skip(n: 1), eq: eq) + } } } +fn string_list_eq(left: List, right: List) -> Bool { + list_eq_by(left: left, right: right, eq: (a, b) => a == b) +} + fn schedule_witness_entry_list_eq(left: List, right: List) -> Bool { - if left.count() != right.count() { - false - } else if left.count() == 0 { - true - } else if !schedule_witness_entry_eq(a: left.first(), b: right.first()) { - false - } else { - schedule_witness_entry_list_eq(left: left.skip(n: 1), right: right.skip(n: 1)) - } + list_eq_by(left: left, right: right, eq: (a, b) => schedule_witness_entry_eq(a: a, b: b)) } fn runnable_eq(left: Runnable, right: Runnable) -> Bool { @@ -636,27 +645,11 @@ fn runnable_eq(left: Runnable, right: Runnable) -> Bool { } fn runnable_batch_eq(left: List, right: List) -> Bool { - if left.count() != right.count() { - false - } else if left.count() == 0 { - true - } else if !runnable_eq(left: left.first(), right: right.first()) { - false - } else { - runnable_batch_eq(left: left.skip(n: 1), right: right.skip(n: 1)) - } + list_eq_by(left: left, right: right, eq: (a, b) => runnable_eq(left: a, right: b)) } fn schedule_eq(left: Schedule, right: Schedule) -> Bool { - if left.count() != right.count() { - false - } else if left.count() == 0 { - true - } else if !runnable_batch_eq(left: left.first(), right: right.first()) { - false - } else { - schedule_eq(left: left.skip(n: 1), right: right.skip(n: 1)) - } + list_eq_by(left: left, right: right, eq: (a, b) => runnable_batch_eq(left: a, right: b)) } fn schedule_generates_identical_schedule(plan: RealizationPlan, schedule: Schedule) -> Bool { diff --git a/dag/std/serialize.dag b/dag/std/serialize.dag index c43569c652a..415ab253931 100644 --- a/dag/std/serialize.dag +++ b/dag/std/serialize.dag @@ -15,8 +15,8 @@ fn serialize_value_doc(knobs: SerializationKnobs, v: SerialValue) -> Doc { match v { ScalarValue { text: t } => match knobs.value_quote { - null => doc_text(text: t) - q => doc_text(text: concat(concat(q, t), q)) + Absent => doc_text(text: t) + Present { value: q } => doc_text(text: concat(concat(q, t), q)) } RecordValue { fields: fields } => serialize_record_doc(knobs: knobs, fields: fields) diff --git a/src/v1/00_core.dag b/src/v1/00_core.dag index 1955d464465..30041f69967 100644 --- a/src/v1/00_core.dag +++ b/src/v1/00_core.dag @@ -279,6 +279,8 @@ type CompilerDiagnostic | UnresolvedType { name: String, span: SourceSpan } | UnitVariantPhantomIdentityEvidenceUnavailable { name: String, span: SourceSpan } | TypeMismatch { expected: String, got: String, span: SourceSpan } + | OptionalValueInRequiredPosition { declared: String, span: SourceSpan } + | OptionalNarrowingUndetermined { declared: String, cause: String, span: SourceSpan } | ArityMismatch { name: String, expected: Int, got: Int, span: SourceSpan } | VariantNotFound { variant: String, type_name: String, span: SourceSpan } | FieldNotFound { field: String, type_name: String, span: SourceSpan } @@ -463,6 +465,8 @@ fn diagnostic_to_span(d: CompilerDiagnostic) -> SourceSpan { UnresolvedType { name: _, span: s } => s UnitVariantPhantomIdentityEvidenceUnavailable { name: _, span: s } => s TypeMismatch { expected: _, got: _, span: s } => s + OptionalValueInRequiredPosition { declared: _, span: s } => s + OptionalNarrowingUndetermined { declared: _, cause: _, span: s } => s ArityMismatch { name: _, expected: _, got: _, span: s } => s VariantNotFound { variant: _, type_name: _, span: s } => s FieldNotFound { field: _, type_name: _, span: s } => s @@ -534,6 +538,8 @@ fn diagnostic_to_message(d: CompilerDiagnostic) -> String { UnresolvedType { name: n, span: _ } => concat("unresolved type '", n, "'") UnitVariantPhantomIdentityEvidenceUnavailable { name: n, span: _ } => concat("unit-variant marker identity evidence unavailable for '", n, "'") TypeMismatch { expected: e, got: g, span: _ } => concat("type mismatch: expected '", e, "', got '", g, "'") + OptionalValueInRequiredPosition { declared: d, span: _ } => concat(concat("optional value in a required position: this position is declared '", d), "' and the value may be ABSENT. The declared type is not a rendering of the value's shape here -- an optional and its payload print identically at a primitive kernel -- so the cause is named rather than shown. Match on the value and decide the absent case, or supply a default.") + OptionalNarrowingUndetermined { declared: d, cause: c, span: _ } => concat(concat(concat("cannot judge this position: optionality is not established either way, and the position is rendered '", d), "'. The check DECLINES rather than concluding required -- concluding required from an operand that carries no answer is the accusing arm of an absorbing fallback. This counts the CHECK'S OWN deficit, NOT a defect in the code at this position. Cause: "), c) ArityMismatch { name: n, expected: e, got: g, span: _ } => concat("type ", n, " expects ", to_string(value: e), " type arguments, got ", to_string(value: g)) VariantNotFound { variant: v, type_name: t, span: _ } => concat("variant '", v, "' not found in type '", t, "'") FieldNotFound { field: f, type_name: t, span: _ } => concat("field '", f, "' not found in type '", t, "'") @@ -2483,6 +2489,52 @@ fn module_path_segments(path: String) -> List { if path == "" { [] } else { path |> split(delimiter: ".") } } +// ONE SEMANTIC FACT, TWO AUTHORED CARRIERS. "This position is optional" is spelled two ways that +// both survive normalization: `T?` carries it in return_cardinality, and an explicitly written +// `Optional` carries it in the type NAME at cardinality Required. A predicate testing ONE carrier +// reads the other as its NEGATION, and is not detectably incomplete by reading it -- it is clean, +// total, and silently half-scoped. +// +// THIS IS NOT THE FIX FOR THAT CLASS AND MUST NOT BE CITED AS ONE. The construction move is +// canonicalization at normalization, which would make every cardinality-only test correct without +// being touched; a shared predicate that callers must REMEMBER is validation standing where +// construction was available, and it leaves the eighteenth half-scoped test as writable as the +// first. It exists to collapse three divergent expressions of one concept into one authority +// (DESIGN section 2), not to close the class. +// +// The name comparison goes through qualified_last_segment: a bare `name == "Optional"` misses the +// qualified authoring, which is its own separately filed defect. +// DECLARED SUBJECT OF THE optional-into-required CHECK, written down because it twice existed only +// in its author's head and both times the predicate asked a question nobody had stated it was +// asking -- which is exactly the thing review cannot catch. +// +// SUBJECT: a COMPUTED optional -- a first()/last() result, an optional field read, any expression +// whose type carries optionality -- reaching a position DECLARED required. +// +// Everything else is an EXPLICIT EXCLUSION with a reason, and a future red outside this sentence is +// a scope violation to be read rather than output to be explained: +// +// EXCLUDED -- a bare `none` literal. Its type is decided BY the position it lands in, so it is not +// a value flowing into one. Whether a position admits a bare none is a different question with a +// different owner (field_type_admits_bare_none); this check routes to it rather than re-deciding. +// Measured: `takes_opt(x: none)` against `fn takes_opt(x: Thing?)` was refused, and 146 corpus +// sites reached through one helper's `else_stmt: TsStmt?` calls were the same false positive. +// +// EXCLUDED -- required-into-optional. Widening loses nothing. +// +// COVERED, AND THIS ENTRY USED TO SAY IT WAS NOT -- an explicitly-spelled Optional VALUE +// reaching a required position. Both operands are now read through node_carries_optional, so the +// nominal Optional coproduct and the cardinality marker are recognized on the produced side as +// well as the declared one. The prior text called this a stated gap; the gap is closed, and the +// correction is noted rather than deleted because the sentence outlived its subject by staying +// byte-stable while the implementation moved beneath it. +fn node_carries_optional(n: Node) -> Bool { + match n.return_cardinality { + CardOptional => true + Required => qualified_last_segment(name: n.name) == "Optional" && (n.children |> count) == 1 + } +} + fn qualified_last_segment(name: String) -> String { match module_path_segments(path: name) |> last { Present { value: s } => s diff --git a/src/v1/04_infer.dag b/src/v1/04_infer.dag index 474e14ca857..39d87cf1ebf 100644 --- a/src/v1/04_infer.dag +++ b/src/v1/04_infer.dag @@ -1141,6 +1141,179 @@ fn declared_type_kernel_inhabitance_mismatch_here_or_at_element( declared: declared, produced: produced, scope: scope) } +// DESIGN section 4b names "values inhabit declared types" as part of the ORDINARY COMPILER FLOOR, +// and this is the position where that floor was open. Both seams below normalize the DECLARED side +// with with_required_cardinality and then compare KERNELS, so the cardinality dimension was never +// judged at all: a field declared String accepted a value typed Optional with no +// diagnostic. That is not a narrow gap. It made a method's declared return type NON-LOAD-BEARING at +// every assignment and argument position -- so changing first()'s declared return type broke sites +// at RUNTIME, in the evaluator, instead of at the check (gunbc#10187, extdeps/git/git.dag:629, +// where `remote: String` received `parts.first()` and the failure surfaced as +// "cannot concat on Variant" two calls later). +// +// The judgment is deliberately ONE-DIRECTIONAL. Required-into-optional is widening and is fine: +// an Optional position accepting a T loses nothing. Optional-into-required is the narrowing that +// drops the absent case on the floor, and it is the only case decided here. +// BOTH SIDES NOW READ THE SAME AUTHORITY, and this paragraph used to say otherwise. It described a +// deliberate asymmetry -- declared side recognizes both spellings, produced side tests cardinality +// only -- and listed the explicitly-spelled Optional VALUE reaching a required position as an +// inspectable gap. That gap is CLOSED: both operands are read through node_carries_optional, which +// recognizes the cardinality marker and the nominal Optional coproduct alike, so the asymmetry the +// sentence defended no longer exists. +// +// The correction is recorded rather than silently deleted because of how it survived: the +// implementation moved and this prose stayed byte-stable, so a reader consulting the comment would +// have been told a real repair was absent. Nothing refused, because no Accepted program reads a +// comment. The same sentence had been duplicated into std.core beside node_carries_optional and had +// to be corrected there too -- one claim in two places, which is why it outlived its subject. +// THREE ANSWERS, NOT TWO. node_carries_optional answers `false` for a declared position whose type +// is still an UNSUBSTITUTED type parameter -- the same `false` it gives a genuinely required +// position -- so a Bool result conflated "proved required" with "could not tell", and the +// conflation fired in the ACCUSING direction. That is the absorbing fallback of DESIGN §5 exactly: +// the arm that cannot compute its answer substituted the widest one instead of refusing, and +// because the widening produced a located diagnostic it read as the check working. Declining to +// judge is not a weaker check -- it is the only honest verdict available before substitution, and +// it keeps the deficit visible as an unjudged position rather than burying it in a false positive. +type OptionalNarrowingCause = DeclaredFormalUnsubstituted | ProducedTypeUnsubstituted + +fn optional_narrowing_cause_text(c: OptionalNarrowingCause) -> String { + match c { + DeclaredFormalUnsubstituted => + "the DECLARED type at this position is an unsubstituted type parameter. Dissolves when builtin generic formals are substituted at the argument seam." + ProducedTypeUnsubstituted => + "the PRODUCED value's type is an unsubstituted type parameter, so its cardinality is not yet established. Dissolves when call-site instantiation reaches this position." + } +} + +type OptionalNarrowing = NarrowsToRequired | ConformsOrWidens | NarrowingUndetermined { cause: OptionalNarrowingCause } + +// Either operand may fail to carry the dimension, so the predicate is named for the QUESTION it +// answers rather than for one side of it. Reusing it on both sides is the whole content of the +// produced-side repair below. +// TWO CARRIERS OF "THIS IS A TYPE PARAMETER", AND READING ONLY THE FIRST ACCUSED CORRECT CODE. +// A type parameter occurrence is stamped `inferred: TypeVariable` where the stamping pass reaches +// it, and arrives as a BARE NAMED LEAF where it does not -- a declared field whose type is the +// parameter itself, supplied from a raw declaration rather than an instantiated template. The leaf +// renders `Primitive(T)`, carries no optionality, and therefore read as REQUIRED, so an optional +// value flowing into it took the accusing arm. Measured: 7 sites in v2.compiler.resolve and +// v2.compiler.translate, all `Outcome { value: T }` positions where T substitutes to `Symbol?` +// and the honest verdict is ConformsOrWidens. +// +// THE SECOND CARRIER IS TESTED POSITIVELY, AGAINST THE ENCLOSING DECLARATION'S OWN FORMALS. +// The tempting test is absence -- "this leaf resolves to no declared type, so it must be a +// parameter" -- and it is a fail-open wearing a repair's clothes: a leaf also resolves to nothing +// when it is a typo, an undeclared type, or a missing import, so the rule would silently stop +// declining genuinely undeclared names. The justification for it is circular besides ("within an +// Accepted program names resolve" is a property of the accepted corpus, asserted inside the +// mechanism that decides membership). +// +// A hardcoded spelling list is the other wrong answer and already exists here as +// is_type_variable_name (`name == "T" || "K" || "V" || ...`). It is wrong for `Elem` or `Acc` and +// spreads the spelling-keyed fork that several defects on this branch share a root with. +// +// So the discriminator is declaration structure: a name is an unsubstituted parameter IFF IT IS A +// DECLARED FORMAL of the declaration supplying this position. Three arms, and the third is what +// keeps the repair from being a fail-open: resolves to a declared type -> ordinary judgment; is a +// formal -> undetermined, defer; NEITHER -> an unresolved name, which keeps refusing. +fn node_names_enclosing_formal(n: Node, formals: List, source_indices: Map) -> Bool { + let nm = authored_name_at(source_indices: source_indices, node: n) + if nm == "" { false } else { (formals |> filter(f => f == nm) |> count) > 0 } +} + +fn optionality_undetermined_with_formals(n: Node, formals: List, source_indices: Map) -> Bool { + match n.inferred { + Present { value: i } => is_type_variable(inferred: i) + Absent => node_names_enclosing_formal(n: n, formals: formals, source_indices: source_indices) + } +} + +fn optionality_undetermined(n: Node) -> Bool { + match n.inferred { + Present { value: i } => is_type_variable(inferred: i) + Absent => false + } +} + +// THE PRODUCED SIDE IS TESTED FIRST, AND THAT ORDER IS THE REPAIR. Matching on +// produced.return_cardinality first let `Required` short-circuit to ConformsOrWidens, so an +// unsubstituted PRODUCED type parameter -- whose cardinality is Required only because nothing has +// instantiated it yet -- was admitted without any unknown ever being considered. That is the +// false-negative twin of the declared-side defect: same conflation of "proved required" with +// "carries no answer", surviving on the other operand because the arms were ordered so it could +// never be reached. When that T instantiates to an optional at a required destination, the check +// was silent. +// THE PRODUCED-SIDE REPAIR IS A SPELLING WIDENING, NOT A TYPE-VARIABLE FLAG, AND THE FIRST ATTEMPT +// GOT THAT WRONG BY A FACTOR OF FOURTEEN. Flagging every produced TYPE VARIABLE as undetermined +// conflated two unrelated facts: a type variable says nothing about OPTIONALITY, and a value of type +// T at Required cardinality is fully determinate -- `witness_from_optional` binds the already +// narrowed payload and produces a `T`, which is correct generic code, not an unjudgeable position. +// Measured over dag + src/v2 that arm fired at 219 sites; the review finding it was meant to close +// concerns produced T INSTANTIATED to an optional at a required destination, which is a concrete +// post-substitution state, not the uninstantiated one. +// +// The real gap is the one this seam already documented: the produced side tested +// return_cardinality ALONE, so an optional spelled NOMINALLY -- the Optional coproduct rather than +// the cardinality marker -- reached a required position unjudged. node_carries_optional is the +// existing single authority that recognizes BOTH spellings, and reading the produced side through +// it closes the false negative without inventing an unknown. +fn optional_into_required_mismatch_with_formals(declared: Node, produced: Node, formals: List, source_indices: Map) -> OptionalNarrowing { + if node_carries_optional(n: produced) { + if optionality_undetermined_with_formals(n: declared, formals: formals, source_indices: source_indices) { + NarrowingUndetermined { cause: DeclaredFormalUnsubstituted } + } + else if node_carries_optional(n: declared) { ConformsOrWidens } + else { NarrowsToRequired } + } else { + ConformsOrWidens + } +} + +fn optional_into_required_mismatch(declared: Node, produced: Node) -> OptionalNarrowing { + if node_carries_optional(n: produced) { + if optionality_undetermined(n: declared) { + NarrowingUndetermined { cause: DeclaredFormalUnsubstituted } + } + else if node_carries_optional(n: declared) { ConformsOrWidens } + else { NarrowsToRequired } + } else { + ConformsOrWidens + } +} + +// The third value must REACH A CONSUMER or it is decoration. Collapsing it to a Bool here was the +// absorbing fallback a second time and in the more dangerous direction: `NarrowingUndetermined => +// false` admitted the position with no diagnostic, no count and no trace, trading a LOUD false +// positive for a SILENT one. The false positive accused correct code, but it announced itself and +// was found in one read; a silent admission has no artifact to notice, so the deficit stops ranking +// for repair. Below the ladder, not low on it. +// +// So the decline is EMITTED. Its diagnostic is deliberately a different variant from the accusation: +// it attributes the deficit to THE SEAM (an unsubstituted formal the checker cannot judge) rather +// than to the code at the position, and it is countable in the same log the population census +// already parses. +fn optional_narrowing_diags(v: OptionalNarrowing, declared: Node, span: SourceSpan, module_name: String, source_indices: Map) -> List { + match v { + ConformsOrWidens => [] + NarrowsToRequired => + [make_error_node( + diagnostic: OptionalValueInRequiredPosition { + declared: node_type_shape(n: declared, source_indices: source_indices), + span: span + }, + module_name: module_name + )] + NarrowingUndetermined { cause: c } => + [make_error_node( + diagnostic: OptionalNarrowingUndetermined { + declared: node_type_shape(n: declared, source_indices: source_indices), + cause: optional_narrowing_cause_text(c: c), + span: span + }, + module_name: module_name + )] + } +} + fn declared_type_conformance_diags(declared: Node, produced: Node, span: SourceSpan, scope: InferScope) -> List { let si = scope.type_env.source_indices let both_ground = conformance_ground_type(n: declared, source_indices: si) @@ -1225,10 +1398,13 @@ fn field_type_admits_bare_none(ft: Node, scope: InferScope) -> Bool { ft.return_cardinality == CardOptional || declares_none_variant } -fn expr_is_bare_none_reference(texpr: Node, scope: InferScope) -> Bool { +// Takes source_indices rather than an InferScope because that is all it reads, and narrowing it is +// what lets the direct-call argument seam -- which has no InferScope -- call THIS function instead +// of keeping a second copy that must be hand-kept in agreement with it (DESIGN section 3). +fn expr_is_bare_none_reference(texpr: Node, source_indices: Map) -> Bool { match texpr.expr_data { ExprVar { binding_kind: _ } => - expr_var_name_at(texpr: texpr, source_indices: scope.type_env.source_indices) == "None" + expr_var_name_at(texpr: texpr, source_indices: source_indices) == "None" _ => false } } @@ -1244,7 +1420,7 @@ fn bare_none_field_construction_diags( Absent => [] Present { value: ft } => let value_expr = field_init_node_value(n: fi) - if expr_is_bare_none_reference(texpr: value_expr, scope: scope) + if expr_is_bare_none_reference(texpr: value_expr, source_indices: scope.type_env.source_indices) && field_declared_type_is_identified(ft: ft, scope: scope) && field_type_admits_bare_none(ft: ft, scope: scope) == false { [make_error_node( @@ -1268,6 +1444,26 @@ fn field_type_is_optional_coproduct(ft: Node, env: TypeEnv) -> Bool { ft.return_cardinality == CardOptional && inner.connective == Disj } +// THE FORMALS COME FROM THE DECLARATION THAT SUPPLIED THE FIELDS, which is the type itself when the +// literal names a type and the VARIANT OWNER when it names a variant -- `Accepted { value: .. }` +// is a variant of `Outcome`, and T is declared on the owner, not on the arm. +fn record_lit_enclosing_formals(type_name: String?, scope: InferScope) -> List { + match type_name { + Present { value: tn } => + match lookup_type_by_name(env: scope.type_env, name: tn) { + Present { value: decl } => + decl.params |> map(pn => authored_name_at(source_indices: scope.type_env.source_indices, node: pn)) + Absent => + match variant_owner_node(scope: scope, name: tn) { + Present { value: parent } => + parent.params |> map(pn => authored_name_at(source_indices: scope.type_env.source_indices, node: pn)) + Absent => [] + } + } + Absent => [] + } +} + fn record_lit_expected_fields(type_name: String?, scope: InferScope) -> List { match type_name { Present { value: tn } => @@ -2507,7 +2703,7 @@ fn equality_operand_admission(n: Node, scope: InferScope, visited: Map count) == 1) { + if node_carries_optional(n: peeled) { equality_operand_admission(n: extract_optional_inner_node(n: peeled), scope: scope, visited: visited, depth: depth) } else { let name = authored_name_at(source_indices: source_indices, node: peeled) @@ -4461,7 +4657,14 @@ fn direct_call_arg_mismatch_diags( } else { let actual_raw = resolved_type(n: actual_expr) let actual = peel_nominal_alias_identity(n: actual_raw, env: type_env, module_name: module_name) - if direct_call_arg_type_mismatch( + let narrowing_diags = optional_narrowing_diags( + v: optional_into_required_mismatch(declared: app.formal_subst, produced: actual_raw), + declared: app.formal_subst, span: actual_expr.span, + module_name: module_name, source_indices: source_indices) + if expr_is_bare_none_reference(texpr: actual_expr, source_indices: source_indices) == false + && (narrowing_diags |> count) > 0 { + narrowing_diags + } else if direct_call_arg_type_mismatch( formal: formal, actual: actual, type_env: type_env, module_name: module_name, source_indices: source_indices) { [type_mismatch_error( expected: node_type_shape(n: formal, source_indices: source_indices), @@ -7778,7 +7981,16 @@ fn infer_record_lit_structural(occurrence_identity: NodeOccurrenceIdentity, type } let formal_peeled = peel_nominal_alias_identity(n: expected_required, env: scope.type_env, module_name: scope.module_name) let actual_peeled = peel_nominal_alias_identity(n: got_node, env: scope.type_env, module_name: scope.module_name) - if kernel_value_declared_type_mismatch(formal: formal_peeled, actual: actual_peeled, type_env: scope.type_env, source_indices: scope.type_env.source_indices) { + let narrowing_diags = optional_narrowing_diags( + v: optional_into_required_mismatch_with_formals(declared: expected_node, produced: got_node, + formals: record_lit_enclosing_formals(type_name: type_name, scope: scope), + source_indices: scope.type_env.source_indices), + declared: expected_node, span: ar_typed.span, + module_name: scope.module_name, source_indices: scope.type_env.source_indices) + if expr_is_bare_none_reference(texpr: ar_typed, source_indices: scope.type_env.source_indices) == false + && (narrowing_diags |> count) > 0 { + narrowing_diags + } else if kernel_value_declared_type_mismatch(formal: formal_peeled, actual: actual_peeled, type_env: scope.type_env, source_indices: scope.type_env.source_indices) { [type_mismatch_error( expected: node_type_shape(n: formal_peeled, source_indices: scope.type_env.source_indices), got: node_type_shape(n: actual_peeled, source_indices: scope.type_env.source_indices), diff --git a/src/v1/04_types.dag b/src/v1/04_types.dag index 6b419130c66..4e2a65fb335 100644 --- a/src/v1/04_types.dag +++ b/src/v1/04_types.dag @@ -1184,17 +1184,22 @@ fn method_receiver_element_node(receiver_type: Node, source_indices: Map is unwrapped to its child. fn extract_optional_inner_node(n: Node) -> Node { - let is_optional = n.return_cardinality == CardOptional - if is_optional { - with_required_cardinality(n: n) - } else if n.name == "Optional" && n.children |> count == 1 { - - match n.children |> first { - Present { value: inner } => inner - Absent => n + if node_carries_optional(n: n) == false { + n + } else { + match n.return_cardinality { + CardOptional => with_required_cardinality(n: n) + Required => + match n.children |> first { + Present { value: inner } => inner + Absent => n + } } - } else { n } + } } fn algebra_field_kind_name(kind: AlgebraFieldKind) -> String { diff --git a/src/v1/compiler_tests_rust.dag b/src/v1/compiler_tests_rust.dag index e1d3983844f..ecaca1c754c 100644 --- a/src/v1/compiler_tests_rust.dag +++ b/src/v1/compiler_tests_rust.dag @@ -1126,6 +1126,8 @@ fn ct_coercion_tests() -> String { ct_render_rust_applied_type_qualified_base_test(), ct_renderer_hop_identity_keying_test(), ct_generic_param_declines_fail_closed_unwrap_test(), + ct_optional_narrowing_undetermined_test(), + ct_production_seam_narrowing_tests(), ct_witness_carrier_declines_non_witness_expected_type_test(), ct_kernel_identity_single_authority_test(), ct_resource_item_is_not_a_type_item_test()) @@ -1139,6 +1141,179 @@ fn ct_coercion_tests() -> String { // the instantiated parameter is `Optional` and the unwrap strips exactly the Option the // return type demands. Arm 2 holds the other direction: a CONCRETE non-optional parameter still // takes the unwrap, so a repair that simply stopped injecting would go red here. +// THE FIFTH FIXTURE CELL, AND IT LIVES HERE BECAUSE compiler_tests.rs IS A GENERATED MIRROR. +// It was first hand-written into the mirror, where required-regen would have deleted it on the next +// run -- evidence that disappears exactly when someone regenerates is the "holds until the next +// edit" failure it exists to prevent. +// +// The seam has THREE outcomes and the original four cells asserted two, so the undetermined arm +// shipped with no discriminating RED. The assertion is three-way ON PURPOSE: a cell checking only +// that "some diagnostic is emitted" would have passed the silent code this replaced, because the +// sibling arm still accused at every other site. It must go red when the arm emits the ACCUSATION +// (the false positive returning) and red when it emits NOTHING (the silent admission returning). +// Both directions were verified by mutation before this was enrolled. +// +// It is the only artifact that will tell a future reader the decline must stay OBSERVABLE: +// optional_narrowing_refuses and optional_into_required_error were both deleted by the climb, so no +// production code carries that history any more. +// PRODUCTION-SEAM EVIDENCE, NOT HELPER EVIDENCE, and the distinction is the whole point of this +// cell. The earlier narrowing cells construct Node values directly and call the judging helper, so +// deleting the production CONSUMER of that helper would leave them green: they establish that the +// helper can answer, not that the seam supplies it the right input or keeps consuming the answer. +// +// These compile AUTHORED SOURCE through compile_sources, so the judgment is reached the way a +// program reaches it -- through direct-call application inference and through record-literal +// structural inference respectively. Each carries its own GREEN control on the same path, because a +// refusing fixture with no accepting twin cannot distinguish "the wall fired" from "this path +// refuses everything". +// +// SCOPE, AND THE DISTINCTION IS NARROWER THAN THE FUNCTION THEY RUN IN. Both cells judge an +// optional value flowing into a position whose required type is ALREADY KNOWN -- a declared field +// of a declared record, concrete or generically instantiated. Neither says anything about the case +// where the expected field template could not be selected at all: that is record-literal +// INSTANTIATION UNAVAILABILITY, a different question with its own classification, gate, cause +// carrier and fixtures, none of which are in this change. A reader must not take the green here as +// evidence that the unavailable arm is judged, because it is not judged here at all. +fn ct_production_seam_narrowing_tests() -> String { + concat( + " fn narrowing_refusals_for(src: &str) -> usize {\n", + " let source = std::rc::Rc::new(crate::v1_compiler_compile::SourceFile {\n", + " path: \"probe.dag\".to_string(),\n", + " content: src.to_string(),\n", + " });\n", + " let result = crate::v1_compiler_compile::compile_sources(\n", + " std::rc::Rc::new(im::vector![source]),\n", + " crate::v1_compiler_artifact::RenderTarget::Rust,\n", + " );\n", + " result\n", + " .diagnostics\n", + " .iter()\n", + " .filter(|d| {\n", + " matches!(\n", + " &*d.diagnostic,\n", + " crate::v1_std_core::CompilerDiagnostic::OptionalValueInRequiredPosition { .. }\n", + " )\n", + " })\n", + " .count()\n", + " }\n", + "\n", + " #[test]\n", + " fn optional_into_required_refuses_through_direct_call_application() {\n", + " let result = std::thread::Builder::new()\n", + " .stack_size(16 * 1024 * 1024)\n", + " .spawn(|| {\n", + " assert_eq!(\n", + " narrowing_refusals_for(\"module probe\\ntype Thing { n: Int }\\nfn needs_required(t: Thing) -> Int { t.n }\\nfn opt_source() -> Thing? { none }\\nfn call_with_optional() -> Int { needs_required(t: opt_source()) }\\n\"),\n", + " 1,\n", + " \"SEAM STOPPED CONSUMING THE JUDGMENT: authored source passing an optional-returning call into a REQUIRED formal produced no optional-into-required refusal. The helper answering correctly in isolation does not establish that direct-call application inference still asks it or still keeps the answer\"\n", + " );\n", + " assert_eq!(\n", + " narrowing_refusals_for(\"module probe\\ntype Thing { n: Int }\\nfn needs_required(t: Thing) -> Int { t.n }\\nfn req_source() -> Thing { Thing { n: 1 } }\\nfn call_with_required() -> Int { needs_required(t: req_source()) }\\n\"),\n", + " 0,\n", + " \"GREEN CONTROL FAILED: the same call shape with a REQUIRED-returning callee was refused, so the fixture above cannot distinguish a working wall from a path that refuses everything\"\n", + " );\n", + " })\n", + " .expect(\"failed to spawn thread\")\n", + " .join();\n", + " result.expect(\"optional_into_required_refuses_through_direct_call_application panicked\");\n", + " }\n", + "\n", + " #[test]\n", + " fn optional_into_required_refuses_through_record_literal_inference() {\n", + " let result = std::thread::Builder::new()\n", + " .stack_size(16 * 1024 * 1024)\n", + " .spawn(|| {\n", + " assert_eq!(\n", + " narrowing_refusals_for(\"module probe\\ntype Thing { n: Int }\\ntype Holder { t: Thing }\\nfn opt_source() -> Thing? { none }\\nfn build() -> Holder { Holder { t: opt_source() } }\\n\"),\n", + " 1,\n", + " \"SEAM STOPPED CONSUMING THE JUDGMENT: an optional value in a REQUIRED record-literal field produced no refusal through record-literal structural inference\"\n", + " );\n", + " assert_eq!(\n", + " narrowing_refusals_for(\"module probe\\ntype Thing { n: Int }\\ntype Box { held: A }\\nfn opt_source() -> Thing? { none }\\nfn build_generic() -> Box { Box { held: opt_source() } }\\n\"),\n", + " 1,\n", + " \"GENERIC INSTANTIATION ROUTE LOST ITS JUDGMENT: the same defect inside a GENERIC record literal went unrefused, which is the instantiated path failing to hand the substituted field type to the narrowing check\"\n", + " );\n", + " assert_eq!(\n", + " narrowing_refusals_for(\"module probe\\ntype Thing { n: Int }\\ntype Holder { t: Thing }\\nfn req_source() -> Thing { Thing { n: 1 } }\\nfn build_ok() -> Holder { Holder { t: req_source() } }\\n\"),\n", + " 0,\n", + " \"GREEN CONTROL FAILED: a required value in the same required field was refused, so the two fixtures above cannot distinguish a working wall from a path that refuses everything\"\n", + " );\n", + " assert_eq!(\n", + " narrowing_refusals_for(\"module probe\\ntype Colour = | Red | Green { shade: Int }\\nfn variant_lit() -> Colour { Green { shade: 3 } }\\n\"),\n", + " 0,\n", + " \"VARIANT ROUTE FALSE POSITIVE: a coproduct variant literal is NOT a generic instantiation, and accusing it is the regression that withdrawing the fallback from the ordinary variant route caused before\"\n", + " );\n", + " })\n", + " .expect(\"failed to spawn thread\")\n", + " .join();\n", + " result.expect(\"optional_into_required_refuses_through_record_literal_inference panicked\");\n", + " }\n", + "\n") +} + +fn ct_optional_narrowing_undetermined_test() -> String { + concat( + " fn type_variable_declared_node() -> std::rc::Rc {\n", + " let base = named_type_node(\"T\");\n", + " std::rc::Rc::new(crate::v1_std_core::Node {\n", + " inferred: Some(std::rc::Rc::new(\n", + " crate::v1_std_core::InferredNode::TypeVariable { id: \"T\".to_string() },\n", + " )),\n", + " ..(*base).clone()\n", + " })\n", + " }\n\n", + " fn optional_produced_node() -> std::rc::Rc {\n", + " let base = named_type_node(\"String\");\n", + " std::rc::Rc::new(crate::v1_std_core::Node {\n", + " return_cardinality: crate::v1_std_core::Cardinality::CardOptional,\n", + " ..(*base).clone()\n", + " })\n", + " }\n\n", + " #[test]\n", + " fn an_unsubstituted_formal_declines_visibly_and_emits_neither_accusation_nor_silence() {\n", + " use crate::v1_std_core::CompilerDiagnostic;\n", + " let source_indices = std::rc::Rc::new(HashMap::new());\n", + " let declared = type_variable_declared_node();\n", + " let produced = optional_produced_node();\n", + " let verdict = crate::v1_compiler_infer::optional_into_required_mismatch(\n", + " declared.clone(),\n", + " produced.clone(),\n", + " );\n", + " assert!(\n", + " matches!(&*verdict, crate::v1_compiler_infer::OptionalNarrowing::NarrowingUndetermined { .. }),\n", + " \"an unsubstituted type parameter establishes optionality NEITHER way, so the judgment must decline rather than conclude required\"\n", + " );\n", + " let diags = crate::v1_compiler_infer::optional_narrowing_diags(\n", + " verdict,\n", + " declared.clone(),\n", + " crate::v1_std_core::no_span(),\n", + " \"probe.module\".to_string(),\n", + " source_indices.clone(),\n", + " );\n", + " assert_eq!(\n", + " diags.len(),\n", + " 1,\n", + " \"SILENT ADMISSION RETURNED: the undetermined arm emitted nothing, which is the absorbing fallback -- no artifact to notice, so the deficit stops ranking for repair\"\n", + " );\n", + " match &*diags[0].diagnostic {\n", + " CompilerDiagnostic::OptionalNarrowingUndetermined { .. } => {}\n", + " CompilerDiagnostic::OptionalValueInRequiredPosition { .. } => panic!(\n", + " \"FALSE POSITIVE RETURNED: the arm accused a position whose declared type is a type variable\"\n", + " ),\n", + " other => panic!(\"undetermined arm emitted an unexpected diagnostic: {:?}\", other),\n", + " }\n", + " let concrete_required = named_type_node(\"String\");\n", + " assert!(\n", + " matches!(&*crate::v1_compiler_infer::optional_into_required_mismatch(concrete_required, produced.clone()), crate::v1_compiler_infer::OptionalNarrowing::NarrowsToRequired),\n", + " \"a CONCRETE required declared type still narrows and must still be accused\"\n", + " );\n", + " assert!(\n", + " matches!(&*crate::v1_compiler_infer::optional_into_required_mismatch(optional_produced_node(), produced.clone()), crate::v1_compiler_infer::OptionalNarrowing::ConformsOrWidens),\n", + " \"optional into optional conforms and must stay silent\"\n", + " );\n", + " }\n\n") +} + fn ct_generic_param_declines_fail_closed_unwrap_test() -> String { concat( " fn optional_typed_arg_node() -> std::rc::Rc {\n", diff --git a/src/v1/stage0/src/cli_run/compile_clean.rs b/src/v1/stage0/src/cli_run/compile_clean.rs index a2e3b0c0b51..8a529780457 100644 --- a/src/v1/stage0/src/cli_run/compile_clean.rs +++ b/src/v1/stage0/src/cli_run/compile_clean.rs @@ -766,6 +766,15 @@ pub fn compile_clean_diagnostic_histogram_key(d: &Rc) -> (String, Str "UnitVariantPhantomIdentityEvidenceUnavailable" } CompilerDiagnostic::TypeMismatch { .. } => "TypeMismatch", + CompilerDiagnostic::OptionalValueInRequiredPosition { .. } => { + "OptionalValueInRequiredPosition" + } + // A DISTINCT histogram class on purpose. This diagnostic counts the CHECK'S OWN deficit -- + // a formal the checker cannot judge because it is still an unsubstituted type parameter -- + // and not a defect in the code at that position. Folding it into the accusation above would + // make the repair population look like it grew when what actually happened is that a + // previously silent arm started reporting. + CompilerDiagnostic::OptionalNarrowingUndetermined { .. } => "OptionalNarrowingUndetermined", CompilerDiagnostic::ArityMismatch { .. } => "ArityMismatch", CompilerDiagnostic::VariantNotFound { .. } => "VariantNotFound", CompilerDiagnostic::FieldNotFound { .. } => "FieldNotFound", @@ -847,6 +856,8 @@ pub fn compile_clean_diagnostic_histogram_key(d: &Rc) -> (String, Str name.clone() } CompilerDiagnostic::TypeMismatch { got, .. } => got.clone(), + CompilerDiagnostic::OptionalValueInRequiredPosition { declared, .. } => declared.clone(), + CompilerDiagnostic::OptionalNarrowingUndetermined { declared, .. } => declared.clone(), CompilerDiagnostic::ArityMismatch { name, .. } => name.clone(), CompilerDiagnostic::VariantNotFound { variant, .. } => variant.clone(), CompilerDiagnostic::FieldNotFound { field, .. } => field.clone(), diff --git a/src/v1/stage0/src/compiler_tests.rs b/src/v1/stage0/src/compiler_tests.rs index 06c9b736b90..ee321577086 100644 --- a/src/v1/stage0/src/compiler_tests.rs +++ b/src/v1/stage0/src/compiler_tests.rs @@ -3580,6 +3580,155 @@ mod compiler_tests { ); } + fn type_variable_declared_node() -> std::rc::Rc { + let base = named_type_node("T"); + std::rc::Rc::new(crate::v1_std_core::Node { + inferred: Some(std::rc::Rc::new( + crate::v1_std_core::InferredNode::TypeVariable { + id: "T".to_string(), + }, + )), + ..(*base).clone() + }) + } + + fn optional_produced_node() -> std::rc::Rc { + let base = named_type_node("String"); + std::rc::Rc::new(crate::v1_std_core::Node { + return_cardinality: crate::v1_std_core::Cardinality::CardOptional, + ..(*base).clone() + }) + } + + #[test] + fn an_unsubstituted_formal_declines_visibly_and_emits_neither_accusation_nor_silence() { + use crate::v1_std_core::CompilerDiagnostic; + let source_indices = std::rc::Rc::new(HashMap::new()); + let declared = type_variable_declared_node(); + let produced = optional_produced_node(); + let verdict = crate::v1_compiler_infer::optional_into_required_mismatch( + declared.clone(), + produced.clone(), + ); + assert!( + matches!(&*verdict, crate::v1_compiler_infer::OptionalNarrowing::NarrowingUndetermined { .. }), + "an unsubstituted type parameter establishes optionality NEITHER way, so the judgment must decline rather than conclude required" + ); + let diags = crate::v1_compiler_infer::optional_narrowing_diags( + verdict, + declared.clone(), + crate::v1_std_core::no_span(), + "probe.module".to_string(), + source_indices.clone(), + ); + assert_eq!( + diags.len(), + 1, + "SILENT ADMISSION RETURNED: the undetermined arm emitted nothing, which is the absorbing fallback -- no artifact to notice, so the deficit stops ranking for repair" + ); + match &*diags[0].diagnostic { + CompilerDiagnostic::OptionalNarrowingUndetermined { .. } => {} + CompilerDiagnostic::OptionalValueInRequiredPosition { .. } => panic!( + "FALSE POSITIVE RETURNED: the arm accused a position whose declared type is a type variable" + ), + other => panic!("undetermined arm emitted an unexpected diagnostic: {:?}", other), + } + let concrete_required = named_type_node("String"); + assert!( + matches!( + &*crate::v1_compiler_infer::optional_into_required_mismatch( + concrete_required, + produced.clone() + ), + crate::v1_compiler_infer::OptionalNarrowing::NarrowsToRequired + ), + "a CONCRETE required declared type still narrows and must still be accused" + ); + assert!( + matches!( + &*crate::v1_compiler_infer::optional_into_required_mismatch( + optional_produced_node(), + produced.clone() + ), + crate::v1_compiler_infer::OptionalNarrowing::ConformsOrWidens + ), + "optional into optional conforms and must stay silent" + ); + } + + fn narrowing_refusals_for(src: &str) -> usize { + let source = std::rc::Rc::new(crate::v1_compiler_compile::SourceFile { + path: "probe.dag".to_string(), + content: src.to_string(), + }); + let result = crate::v1_compiler_compile::compile_sources( + std::rc::Rc::new(im::vector![source]), + crate::v1_compiler_artifact::RenderTarget::Rust, + ); + result + .diagnostics + .iter() + .filter(|d| { + matches!( + &*d.diagnostic, + crate::v1_std_core::CompilerDiagnostic::OptionalValueInRequiredPosition { .. } + ) + }) + .count() + } + + #[test] + fn optional_into_required_refuses_through_direct_call_application() { + let result = std::thread::Builder::new() + .stack_size(16 * 1024 * 1024) + .spawn(|| { + assert_eq!( + narrowing_refusals_for("module probe\ntype Thing { n: Int }\nfn needs_required(t: Thing) -> Int { t.n }\nfn opt_source() -> Thing? { none }\nfn call_with_optional() -> Int { needs_required(t: opt_source()) }\n"), + 1, + "SEAM STOPPED CONSUMING THE JUDGMENT: authored source passing an optional-returning call into a REQUIRED formal produced no optional-into-required refusal. The helper answering correctly in isolation does not establish that direct-call application inference still asks it or still keeps the answer" + ); + assert_eq!( + narrowing_refusals_for("module probe\ntype Thing { n: Int }\nfn needs_required(t: Thing) -> Int { t.n }\nfn req_source() -> Thing { Thing { n: 1 } }\nfn call_with_required() -> Int { needs_required(t: req_source()) }\n"), + 0, + "GREEN CONTROL FAILED: the same call shape with a REQUIRED-returning callee was refused, so the fixture above cannot distinguish a working wall from a path that refuses everything" + ); + }) + .expect("failed to spawn thread") + .join(); + result.expect("optional_into_required_refuses_through_direct_call_application panicked"); + } + + #[test] + fn optional_into_required_refuses_through_record_literal_inference() { + let result = std::thread::Builder::new() + .stack_size(16 * 1024 * 1024) + .spawn(|| { + assert_eq!( + narrowing_refusals_for("module probe\ntype Thing { n: Int }\ntype Holder { t: Thing }\nfn opt_source() -> Thing? { none }\nfn build() -> Holder { Holder { t: opt_source() } }\n"), + 1, + "SEAM STOPPED CONSUMING THE JUDGMENT: an optional value in a REQUIRED record-literal field produced no refusal through record-literal structural inference" + ); + assert_eq!( + narrowing_refusals_for("module probe\ntype Thing { n: Int }\ntype Box { held: A }\nfn opt_source() -> Thing? { none }\nfn build_generic() -> Box { Box { held: opt_source() } }\n"), + 1, + "GENERIC INSTANTIATION ROUTE LOST ITS JUDGMENT: the same defect inside a GENERIC record literal went unrefused, which is the instantiated path failing to hand the substituted field type to the narrowing check" + ); + assert_eq!( + narrowing_refusals_for("module probe\ntype Thing { n: Int }\ntype Holder { t: Thing }\nfn req_source() -> Thing { Thing { n: 1 } }\nfn build_ok() -> Holder { Holder { t: req_source() } }\n"), + 0, + "GREEN CONTROL FAILED: a required value in the same required field was refused, so the two fixtures above cannot distinguish a working wall from a path that refuses everything" + ); + assert_eq!( + narrowing_refusals_for("module probe\ntype Colour = | Red | Green { shade: Int }\nfn variant_lit() -> Colour { Green { shade: 3 } }\n"), + 0, + "VARIANT ROUTE FALSE POSITIVE: a coproduct variant literal is NOT a generic instantiation, and accusing it is the regression that withdrawing the fallback from the ordinary variant route caused before" + ); + }) + .expect("failed to spawn thread") + .join(); + result.expect("optional_into_required_refuses_through_record_literal_inference panicked"); + } + #[test] fn witness_carrier_declines_a_non_witness_expected_type() { let source_indices = std::rc::Rc::new(HashMap::new()); diff --git a/src/v1/stage0/src/extdeps_container_oci_digest.rs b/src/v1/stage0/src/extdeps_container_oci_digest.rs index a8ac4a28e78..ce7e895a4f5 100644 --- a/src/v1/stage0/src/extdeps_container_oci_digest.rs +++ b/src/v1/stage0/src/extdeps_container_oci_digest.rs @@ -233,7 +233,16 @@ pub fn oci_wire_digest_parts(raw: String) -> Option> { if ((parts.clone().len() as i64) != 2) { std::option::Option::None } else { - Some(oci_wire_digest_parts_from_split(parts.clone().first().cloned().expect("fail-closed: an optional value flowed into non-optional parameter 0 of oci_wire_digest_parts_from_split (empty Optional at runtime)"), parts.clone().iter().cloned().skip(1 as usize).next().expect("fail-closed: an optional value flowed into non-optional parameter 1 of oci_wire_digest_parts_from_split (empty Optional at runtime)"))) + match parts.clone().first().cloned() { + std::option::Option::None => std::option::Option::None, + Some(algorithm) => match parts.clone().iter().cloned().skip(1 as usize).next() { + std::option::Option::None => std::option::Option::None, + Some(encoded) => Some(oci_wire_digest_parts_from_split( + algorithm.clone(), + encoded.clone(), + )), + }, + } } } } diff --git a/src/v1/stage0/src/extdeps_version_semver.rs b/src/v1/stage0/src/extdeps_version_semver.rs index f20c72fe7bf..12768d9c6b7 100644 --- a/src/v1/stage0/src/extdeps_version_semver.rs +++ b/src/v1/stage0/src/extdeps_version_semver.rs @@ -88,27 +88,34 @@ pub fn semver_compare_identifiers( mut b: Rc>>, ) -> Ordering { loop { - if (((a.clone().len() as i64) == 0) && ((b.clone().len() as i64) == 0)) { - break Ordering::Equal; - } else { - if ((a.clone().len() as i64) == 0) { - break Ordering::Less; - } else { - if ((b.clone().len() as i64) == 0) { + match a.clone().first().cloned() { + std::option::Option::None => match b.clone().first().cloned() { + std::option::Option::None => { + break Ordering::Equal; + } + Some(_) => { + break Ordering::Less; + } + }, + Some(ah) => match b.clone().first().cloned() { + std::option::Option::None => { break Ordering::Greater; - } else { - match semver_compare_identifier(a.clone().first().cloned().expect("fail-closed: an optional value flowed into non-optional parameter 0 of semver_compare_identifier (empty Optional at runtime)"), b.clone().first().cloned().expect("fail-closed: an optional value flowed into non-optional parameter 1 of semver_compare_identifier (empty Optional at runtime)")) { - Ordering::Equal => { { - let __tco_0 = Rc::new(a.iter().cloned().skip(1 as usize).collect::>()); -let __tco_1 = Rc::new(b.iter().cloned().skip(1 as usize).collect::>()); -a = __tco_0; -b = __tco_1; -continue; -} }, - other => { break other.clone(); }, -} } - } + Some(bh) => match semver_compare_identifier(ah.clone(), bh.clone()) { + Ordering::Equal => { + let __tco_0 = + Rc::new(a.iter().cloned().skip(1 as usize).collect::>()); + let __tco_1 = + Rc::new(b.iter().cloned().skip(1 as usize).collect::>()); + a = __tco_0; + b = __tco_1; + continue; + } + other => { + break other.clone(); + } + }, + }, } } } diff --git a/src/v1/stage0/src/std_occurrence_identity.rs b/src/v1/stage0/src/std_occurrence_identity.rs index b8fa01bbd6f..a24e33c5e00 100644 --- a/src/v1/stage0/src/std_occurrence_identity.rs +++ b/src/v1/stage0/src/std_occurrence_identity.rs @@ -474,31 +474,49 @@ pub fn occurrence_id_list_is_prefix_of( prefix: Rc>, path: Rc>, ) -> bool { - prefix.iter().cloned().fold(Rc::new(OccurrenceIdListPrefixAcc { - path_remaining: path.clone(), - ok: true, -}), |acc: _, expected: OccurrenceId| if !acc.ok.clone() { - acc.clone() - } else { - if ((acc.path_remaining.clone().len() as i64) == 0) { + prefix + .iter() + .cloned() + .fold( Rc::new(OccurrenceIdListPrefixAcc { - path_remaining: Rc::new(vec![]), - ok: false, -}) - } else { - if occurrence_id_eq(acc.path_remaining.clone().first().cloned().expect("fail-closed: an optional value flowed into non-optional parameter 0 of occurrence_id_eq (empty Optional at runtime)"), expected.clone()) { - Rc::new(OccurrenceIdListPrefixAcc { - path_remaining: Rc::new(acc.path_remaining.clone().iter().cloned().skip(1 as usize).collect::>()), - ok: true, -}) - } else { - Rc::new(OccurrenceIdListPrefixAcc { - path_remaining: acc.path_remaining.clone(), - ok: false, -}) - } - } - }).ok.clone() + path_remaining: path.clone(), + ok: true, + }), + |acc: _, expected: OccurrenceId| { + if !acc.ok.clone() { + acc.clone() + } else { + match acc.path_remaining.clone().first().cloned() { + std::option::Option::None => Rc::new(OccurrenceIdListPrefixAcc { + path_remaining: Rc::new(vec![]), + ok: false, + }), + Some(head) => { + if occurrence_id_eq(head.clone(), expected.clone()) { + Rc::new(OccurrenceIdListPrefixAcc { + path_remaining: Rc::new( + acc.path_remaining + .clone() + .iter() + .cloned() + .skip(1 as usize) + .collect::>(), + ), + ok: true, + }) + } else { + Rc::new(OccurrenceIdListPrefixAcc { + path_remaining: acc.path_remaining.clone(), + ok: false, + }) + } + } + } + } + }, + ) + .ok + .clone() } pub fn occurrence_containment_ancestors_are_prefix_of( diff --git a/src/v1/stage0/src/std_realization_schedule.rs b/src/v1/stage0/src/std_realization_schedule.rs index 4af9c94ada9..8a0b1377248 100644 --- a/src/v1/stage0/src/std_realization_schedule.rs +++ b/src/v1/stage0/src/std_realization_schedule.rs @@ -745,59 +745,56 @@ pub fn schedule_witness_entry_roster_contains( }) } -pub fn string_list_eq(mut left: Rc>, mut right: Rc>) -> bool { - loop { - if ((left.clone().len() as i64) != (right.clone().len() as i64)) { - break false; - } else { - if ((left.clone().len() as i64) == 0) { - break true; - } else { - if (left.clone().first().cloned().as_deref() - != right.clone().first().cloned().as_deref()) - { - break false; - } else { - { - let __tco_0 = - Rc::new(left.iter().cloned().skip(1 as usize).collect::>()); - let __tco_1 = - Rc::new(right.iter().cloned().skip(1 as usize).collect::>()); - left = __tco_0; - right = __tco_1; - continue; - } +pub fn list_eq_by( + left: Rc>, + right: Rc>, + eq: impl Fn(T, T) -> bool + Clone, +) -> bool { + stacker::maybe_grow(512 * 1024, 2 * 1024 * 1024, || { + match left.clone().first().cloned() { + std::option::Option::None => match right.clone().first().cloned() { + std::option::Option::None => true, + Some(_) => false, + }, + Some(l) => match right.clone().first().cloned() { + std::option::Option::None => false, + Some(r) => { + (eq(l.clone(), r.clone()) + && list_eq_by( + Rc::new( + left.clone() + .iter() + .cloned() + .skip(1 as usize) + .collect::>(), + ), + Rc::new( + right + .clone() + .iter() + .cloned() + .skip(1 as usize) + .collect::>(), + ), + eq.clone(), + )) } - } + }, } - } + }) +} + +pub fn string_list_eq(left: Rc>, right: Rc>) -> bool { + list_eq_by(left.clone(), right.clone(), |a, b| (a.clone() == b.clone())) } pub fn schedule_witness_entry_list_eq( - mut left: Rc>>, - mut right: Rc>>, + left: Rc>>, + right: Rc>>, ) -> bool { - loop { - if ((left.clone().len() as i64) != (right.clone().len() as i64)) { - break false; - } else { - if ((left.clone().len() as i64) == 0) { - break true; - } else { - if !schedule_witness_entry_eq(left.clone().first().cloned().expect("fail-closed: an optional value flowed into non-optional parameter 0 of schedule_witness_entry_eq (empty Optional at runtime)"), right.clone().first().cloned().expect("fail-closed: an optional value flowed into non-optional parameter 1 of schedule_witness_entry_eq (empty Optional at runtime)")) { - break false; -} else { - { - let __tco_0 = Rc::new(left.iter().cloned().skip(1 as usize).collect::>()); -let __tco_1 = Rc::new(right.iter().cloned().skip(1 as usize).collect::>()); -left = __tco_0; -right = __tco_1; -continue; -} -} - } - } - } + list_eq_by(left.clone(), right.clone(), |a, b| { + schedule_witness_entry_eq(a.clone(), b.clone()) + }) } pub fn runnable_eq(left: Rc, right: Rc) -> bool { @@ -866,55 +863,16 @@ pub fn runnable_eq(left: Rc, right: Rc) -> bool { } } -pub fn runnable_batch_eq( - mut left: Rc>>, - mut right: Rc>>, -) -> bool { - loop { - if ((left.clone().len() as i64) != (right.clone().len() as i64)) { - break false; - } else { - if ((left.clone().len() as i64) == 0) { - break true; - } else { - if !runnable_eq(left.clone().first().cloned().expect("fail-closed: an optional value flowed into non-optional parameter 0 of runnable_eq (empty Optional at runtime)"), right.clone().first().cloned().expect("fail-closed: an optional value flowed into non-optional parameter 1 of runnable_eq (empty Optional at runtime)")) { - break false; -} else { - { - let __tco_0 = Rc::new(left.iter().cloned().skip(1 as usize).collect::>()); -let __tco_1 = Rc::new(right.iter().cloned().skip(1 as usize).collect::>()); -left = __tco_0; -right = __tco_1; -continue; -} -} - } - } - } +pub fn runnable_batch_eq(left: Rc>>, right: Rc>>) -> bool { + list_eq_by(left.clone(), right.clone(), |a, b| { + runnable_eq(a.clone(), b.clone()) + }) } -pub fn schedule_eq(mut left: Schedule, mut right: Schedule) -> bool { - loop { - if ((left.clone().len() as i64) != (right.clone().len() as i64)) { - break false; - } else { - if ((left.clone().len() as i64) == 0) { - break true; - } else { - if !runnable_batch_eq(left.clone().first().cloned().expect("fail-closed: an optional value flowed into non-optional parameter 0 of runnable_batch_eq (empty Optional at runtime)"), right.clone().first().cloned().expect("fail-closed: an optional value flowed into non-optional parameter 1 of runnable_batch_eq (empty Optional at runtime)")) { - break false; -} else { - { - let __tco_0 = Rc::new(left.iter().cloned().skip(1 as usize).collect::>()); -let __tco_1 = Rc::new(right.iter().cloned().skip(1 as usize).collect::>()); -left = __tco_0; -right = __tco_1; -continue; -} -} - } - } - } +pub fn schedule_eq(left: Schedule, right: Schedule) -> bool { + list_eq_by(left.clone(), right.clone(), |a, b| { + runnable_batch_eq(a.clone(), b.clone()) + }) } pub fn schedule_generates_identical_schedule( diff --git a/src/v1/stage0/src/v1_compiler_compiler_tests_rust.rs b/src/v1/stage0/src/v1_compiler_compiler_tests_rust.rs index 20d23f042b3..a21316e31b2 100644 --- a/src/v1/stage0/src/v1_compiler_compiler_tests_rust.rs +++ b/src/v1/stage0/src/v1_compiler_compiler_tests_rust.rs @@ -114,10 +114,18 @@ pub fn ct_coercion_tests() -> String { } __result }); - v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(" // =========================================================================\n".to_string(), " // Coercion registry tests (auto-generated from data declarations)\n".to_string()), " // =========================================================================\n\n".to_string()), test_fns.clone().join(&"\n".to_string())), ct_rust_btree_set_ord_eligibility_test()), ct_diagnostics_carrier_grounding_test()), ct_render_rust_applied_type_qualified_base_test()), ct_renderer_hop_identity_keying_test()), ct_generic_param_declines_fail_closed_unwrap_test()), ct_witness_carrier_declines_non_witness_expected_type_test()), ct_kernel_identity_single_authority_test()), ct_resource_item_is_not_a_type_item_test()) + v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(" // =========================================================================\n".to_string(), " // Coercion registry tests (auto-generated from data declarations)\n".to_string()), " // =========================================================================\n\n".to_string()), test_fns.clone().join(&"\n".to_string())), ct_rust_btree_set_ord_eligibility_test()), ct_diagnostics_carrier_grounding_test()), ct_render_rust_applied_type_qualified_base_test()), ct_renderer_hop_identity_keying_test()), ct_generic_param_declines_fail_closed_unwrap_test()), ct_optional_narrowing_undetermined_test()), ct_production_seam_narrowing_tests()), ct_witness_carrier_declines_non_witness_expected_type_test()), ct_kernel_identity_single_authority_test()), ct_resource_item_is_not_a_type_item_test()) } } +pub fn ct_production_seam_narrowing_tests() -> String { + v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(" fn narrowing_refusals_for(src: &str) -> usize {\n".to_string(), " let source = std::rc::Rc::new(crate::v1_compiler_compile::SourceFile {\n".to_string()), " path: \"probe.dag\".to_string(),\n".to_string()), " content: src.to_string(),\n".to_string()), " });\n".to_string()), " let result = crate::v1_compiler_compile::compile_sources(\n".to_string()), " std::rc::Rc::new(im::vector![source]),\n".to_string()), " crate::v1_compiler_artifact::RenderTarget::Rust,\n".to_string()), " );\n".to_string()), " result\n".to_string()), " .diagnostics\n".to_string()), " .iter()\n".to_string()), " .filter(|d| {\n".to_string()), " matches!(\n".to_string()), " &*d.diagnostic,\n".to_string()), " crate::v1_std_core::CompilerDiagnostic::OptionalValueInRequiredPosition { .. }\n".to_string()), " )\n".to_string()), " })\n".to_string()), " .count()\n".to_string()), " }\n".to_string()), "\n".to_string()), " #[test]\n".to_string()), " fn optional_into_required_refuses_through_direct_call_application() {\n".to_string()), " let result = std::thread::Builder::new()\n".to_string()), " .stack_size(16 * 1024 * 1024)\n".to_string()), " .spawn(|| {\n".to_string()), " assert_eq!(\n".to_string()), " narrowing_refusals_for(\"module probe\\ntype Thing { n: Int }\\nfn needs_required(t: Thing) -> Int { t.n }\\nfn opt_source() -> Thing? { none }\\nfn call_with_optional() -> Int { needs_required(t: opt_source()) }\\n\"),\n".to_string()), " 1,\n".to_string()), " \"SEAM STOPPED CONSUMING THE JUDGMENT: authored source passing an optional-returning call into a REQUIRED formal produced no optional-into-required refusal. The helper answering correctly in isolation does not establish that direct-call application inference still asks it or still keeps the answer\"\n".to_string()), " );\n".to_string()), " assert_eq!(\n".to_string()), " narrowing_refusals_for(\"module probe\\ntype Thing { n: Int }\\nfn needs_required(t: Thing) -> Int { t.n }\\nfn req_source() -> Thing { Thing { n: 1 } }\\nfn call_with_required() -> Int { needs_required(t: req_source()) }\\n\"),\n".to_string()), " 0,\n".to_string()), " \"GREEN CONTROL FAILED: the same call shape with a REQUIRED-returning callee was refused, so the fixture above cannot distinguish a working wall from a path that refuses everything\"\n".to_string()), " );\n".to_string()), " })\n".to_string()), " .expect(\"failed to spawn thread\")\n".to_string()), " .join();\n".to_string()), " result.expect(\"optional_into_required_refuses_through_direct_call_application panicked\");\n".to_string()), " }\n".to_string()), "\n".to_string()), " #[test]\n".to_string()), " fn optional_into_required_refuses_through_record_literal_inference() {\n".to_string()), " let result = std::thread::Builder::new()\n".to_string()), " .stack_size(16 * 1024 * 1024)\n".to_string()), " .spawn(|| {\n".to_string()), " assert_eq!(\n".to_string()), " narrowing_refusals_for(\"module probe\\ntype Thing { n: Int }\\ntype Holder { t: Thing }\\nfn opt_source() -> Thing? { none }\\nfn build() -> Holder { Holder { t: opt_source() } }\\n\"),\n".to_string()), " 1,\n".to_string()), " \"SEAM STOPPED CONSUMING THE JUDGMENT: an optional value in a REQUIRED record-literal field produced no refusal through record-literal structural inference\"\n".to_string()), " );\n".to_string()), " assert_eq!(\n".to_string()), " narrowing_refusals_for(\"module probe\\ntype Thing { n: Int }\\ntype Box { held: A }\\nfn opt_source() -> Thing? { none }\\nfn build_generic() -> Box { Box { held: opt_source() } }\\n\"),\n".to_string()), " 1,\n".to_string()), " \"GENERIC INSTANTIATION ROUTE LOST ITS JUDGMENT: the same defect inside a GENERIC record literal went unrefused, which is the instantiated path failing to hand the substituted field type to the narrowing check\"\n".to_string()), " );\n".to_string()), " assert_eq!(\n".to_string()), " narrowing_refusals_for(\"module probe\\ntype Thing { n: Int }\\ntype Holder { t: Thing }\\nfn req_source() -> Thing { Thing { n: 1 } }\\nfn build_ok() -> Holder { Holder { t: req_source() } }\\n\"),\n".to_string()), " 0,\n".to_string()), " \"GREEN CONTROL FAILED: a required value in the same required field was refused, so the two fixtures above cannot distinguish a working wall from a path that refuses everything\"\n".to_string()), " );\n".to_string()), " assert_eq!(\n".to_string()), " narrowing_refusals_for(\"module probe\\ntype Colour = | Red | Green { shade: Int }\\nfn variant_lit() -> Colour { Green { shade: 3 } }\\n\"),\n".to_string()), " 0,\n".to_string()), " \"VARIANT ROUTE FALSE POSITIVE: a coproduct variant literal is NOT a generic instantiation, and accusing it is the regression that withdrawing the fallback from the ordinary variant route caused before\"\n".to_string()), " );\n".to_string()), " })\n".to_string()), " .expect(\"failed to spawn thread\")\n".to_string()), " .join();\n".to_string()), " result.expect(\"optional_into_required_refuses_through_record_literal_inference panicked\");\n".to_string()), " }\n".to_string()), "\n".to_string()) +} + +pub fn ct_optional_narrowing_undetermined_test() -> String { + v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(" fn type_variable_declared_node() -> std::rc::Rc {\n".to_string(), " let base = named_type_node(\"T\");\n".to_string()), " std::rc::Rc::new(crate::v1_std_core::Node {\n".to_string()), " inferred: Some(std::rc::Rc::new(\n".to_string()), " crate::v1_std_core::InferredNode::TypeVariable { id: \"T\".to_string() },\n".to_string()), " )),\n".to_string()), " ..(*base).clone()\n".to_string()), " })\n".to_string()), " }\n\n".to_string()), " fn optional_produced_node() -> std::rc::Rc {\n".to_string()), " let base = named_type_node(\"String\");\n".to_string()), " std::rc::Rc::new(crate::v1_std_core::Node {\n".to_string()), " return_cardinality: crate::v1_std_core::Cardinality::CardOptional,\n".to_string()), " ..(*base).clone()\n".to_string()), " })\n".to_string()), " }\n\n".to_string()), " #[test]\n".to_string()), " fn an_unsubstituted_formal_declines_visibly_and_emits_neither_accusation_nor_silence() {\n".to_string()), " use crate::v1_std_core::CompilerDiagnostic;\n".to_string()), " let source_indices = std::rc::Rc::new(HashMap::new());\n".to_string()), " let declared = type_variable_declared_node();\n".to_string()), " let produced = optional_produced_node();\n".to_string()), " let verdict = crate::v1_compiler_infer::optional_into_required_mismatch(\n".to_string()), " declared.clone(),\n".to_string()), " produced.clone(),\n".to_string()), " );\n".to_string()), " assert!(\n".to_string()), " matches!(&*verdict, crate::v1_compiler_infer::OptionalNarrowing::NarrowingUndetermined { .. }),\n".to_string()), " \"an unsubstituted type parameter establishes optionality NEITHER way, so the judgment must decline rather than conclude required\"\n".to_string()), " );\n".to_string()), " let diags = crate::v1_compiler_infer::optional_narrowing_diags(\n".to_string()), " verdict,\n".to_string()), " declared.clone(),\n".to_string()), " crate::v1_std_core::no_span(),\n".to_string()), " \"probe.module\".to_string(),\n".to_string()), " source_indices.clone(),\n".to_string()), " );\n".to_string()), " assert_eq!(\n".to_string()), " diags.len(),\n".to_string()), " 1,\n".to_string()), " \"SILENT ADMISSION RETURNED: the undetermined arm emitted nothing, which is the absorbing fallback -- no artifact to notice, so the deficit stops ranking for repair\"\n".to_string()), " );\n".to_string()), " match &*diags[0].diagnostic {\n".to_string()), " CompilerDiagnostic::OptionalNarrowingUndetermined { .. } => {}\n".to_string()), " CompilerDiagnostic::OptionalValueInRequiredPosition { .. } => panic!(\n".to_string()), " \"FALSE POSITIVE RETURNED: the arm accused a position whose declared type is a type variable\"\n".to_string()), " ),\n".to_string()), " other => panic!(\"undetermined arm emitted an unexpected diagnostic: {:?}\", other),\n".to_string()), " }\n".to_string()), " let concrete_required = named_type_node(\"String\");\n".to_string()), " assert!(\n".to_string()), " matches!(&*crate::v1_compiler_infer::optional_into_required_mismatch(concrete_required, produced.clone()), crate::v1_compiler_infer::OptionalNarrowing::NarrowsToRequired),\n".to_string()), " \"a CONCRETE required declared type still narrows and must still be accused\"\n".to_string()), " );\n".to_string()), " assert!(\n".to_string()), " matches!(&*crate::v1_compiler_infer::optional_into_required_mismatch(optional_produced_node(), produced.clone()), crate::v1_compiler_infer::OptionalNarrowing::ConformsOrWidens),\n".to_string()), " \"optional into optional conforms and must stay silent\"\n".to_string()), " );\n".to_string()), " }\n\n".to_string()) +} + pub fn ct_generic_param_declines_fail_closed_unwrap_test() -> String { v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(" fn optional_typed_arg_node() -> std::rc::Rc {\n".to_string(), " let optional_type = shaped_type_node(\"Node\", Vec::new());\n".to_string()), " let optional_type = std::rc::Rc::new(crate::v1_std_core::Node {\n".to_string()), " return_cardinality: crate::v1_std_core::Cardinality::CardOptional,\n".to_string()), " ..(*optional_type).clone()\n".to_string()), " });\n".to_string()), " let arg = named_type_node(\"child\");\n".to_string()), " std::rc::Rc::new(crate::v1_std_core::Node {\n".to_string()), " inferred: Some(std::rc::Rc::new(crate::v1_std_core::InferredNode::Resolved {\n".to_string()), " node: optional_type,\n".to_string()), " })),\n".to_string()), " ..(*arg).clone()\n".to_string()), " })\n".to_string()), " }\n\n".to_string()), " fn callee_with_one_param(param_type_name: &str) -> Option> {\n".to_string()), " let param = shaped_type_node(\"value\", vec![named_type_node(param_type_name)]);\n".to_string()), " Some(std::rc::Rc::new(crate::v1_compiler_infer_items::ItemInfo {\n".to_string()), " name: \"outcome_accepted\".to_string(),\n".to_string()), " module_name: \"v2.std.diagnostic\".to_string(),\n".to_string()), " kind: crate::v1_compiler_infer_items::ItemKind::FnItem,\n".to_string()), " service_names: std::rc::Rc::new(im::Vector::new()),\n".to_string()), " resource_names: std::rc::Rc::new(im::Vector::new()),\n".to_string()), " params: std::rc::Rc::new(vec![param].into()),\n".to_string()), " is_self_recursive: false,\n".to_string()), " has_non_tail_self_call: false,\n".to_string()), " }))\n".to_string()), " }\n\n".to_string()), " #[test]\n".to_string()), " fn generic_parameter_declines_the_fail_closed_unwrap() {\n".to_string()), " let source_indices = std::rc::Rc::new(HashMap::new());\n".to_string()), " let arg = optional_typed_arg_node();\n".to_string()), " let generic = crate::v1_compiler_emit_rust::rust_call_arg_fail_closed_unwrap(\n".to_string()), " \"child.clone()\".to_string(),\n".to_string()), " arg.clone(),\n".to_string()), " callee_with_one_param(\"T\"),\n".to_string()), " 0,\n".to_string()), " \"outcome_accepted\".to_string(),\n".to_string()), " source_indices.clone(),\n".to_string()), " );\n".to_string()), " assert_eq!(\n".to_string()), " generic, \"child.clone()\",\n".to_string()), " \"a type-variable parameter cannot say the instantiation is non-optional, so no unwrap may be injected\"\n".to_string()), " );\n".to_string()), " let concrete = crate::v1_compiler_emit_rust::rust_call_arg_fail_closed_unwrap(\n".to_string()), " \"child.clone()\".to_string(),\n".to_string()), " arg,\n".to_string()), " callee_with_one_param(\"Node\"),\n".to_string()), " 0,\n".to_string()), " \"node_locus\".to_string(),\n".to_string()), " source_indices,\n".to_string()), " );\n".to_string()), " assert!(\n".to_string()), " concrete.contains(\".expect(\"),\n".to_string()), " \"a concrete non-optional parameter must still take the unwrap: {}\",\n".to_string()), " concrete\n".to_string()), " );\n".to_string()), " }\n\n".to_string()) } diff --git a/src/v1/stage0/src/v1_compiler_infer.rs b/src/v1/stage0/src/v1_compiler_infer.rs index ea39ae4172e..58b6252ad69 100644 --- a/src/v1/stage0/src/v1_compiler_infer.rs +++ b/src/v1/stage0/src/v1_compiler_infer.rs @@ -8,6 +8,8 @@ use self::InhabitanceRefusalReason::*; use self::InhabitanceUndecidableReason::*; use self::InhabitanceVerdict::*; use self::LiteralBoundary::*; +use self::OptionalNarrowing::*; +use self::OptionalNarrowingCause::*; use self::ServiceConfigFieldJudgment::*; pub use crate::extdeps_container_oci_digest::{ oci_other_digest_algorithm, oci_other_digest_encoded, @@ -281,6 +283,7 @@ pub use crate::v1_std_core::{ }; pub use crate::v1_std_core::{ divergent_type, expr_is_any_literal, expr_literal_symbol_optional, module_path_segments, + node_carries_optional, }; pub use crate::v1_std_core::{ AdmitCallersEntry, CallSemantics, CallTargetIdentity, Cardinality, CompilerDiagnostic, @@ -1503,6 +1506,167 @@ pub fn declared_type_kernel_inhabitance_mismatch_here_or_at_element( )) } +#[derive( + Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize, +)] +#[serde(tag = "_variant")] +pub enum OptionalNarrowingCause { + DeclaredFormalUnsubstituted, + ProducedTypeUnsubstituted, +} + +pub fn optional_narrowing_cause_text(c: OptionalNarrowingCause) -> String { + match c.clone() { + OptionalNarrowingCause::DeclaredFormalUnsubstituted => "the DECLARED type at this position is an unsubstituted type parameter. Dissolves when builtin generic formals are substituted at the argument seam.".to_string(), + OptionalNarrowingCause::ProducedTypeUnsubstituted => "the PRODUCED value's type is an unsubstituted type parameter, so its cardinality is not yet established. Dissolves when call-site instantiation reaches this position.".to_string(), +} +} + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(tag = "_variant")] +pub enum OptionalNarrowing { + NarrowsToRequired, + ConformsOrWidens, + NarrowingUndetermined { cause: OptionalNarrowingCause }, +} +impl OptionalNarrowing { + pub fn cause(&self) -> OptionalNarrowingCause { + match self { + OptionalNarrowing::NarrowsToRequired => panic!("no cause on unit variant"), + OptionalNarrowing::ConformsOrWidens => panic!("no cause on unit variant"), + OptionalNarrowing::NarrowingUndetermined { cause: __val, .. } => __val.clone(), + } + } +} + +pub fn node_names_enclosing_formal( + n: Rc, + formals: Rc>, + source_indices: Rc>>, +) -> bool { + { + let nm = crate::v1_std_core::authored_name_at(source_indices.clone(), n.clone()); + if (nm.clone() == "".to_string()) { + false + } else { + ((Rc::new({ + let mut __result = Vec::new(); + for f in formals.iter().cloned() { + if (f.clone() == nm.clone()) { + __result.push(f); + } + } + __result + }) + .len() as i64) + > 0) + } + } +} + +pub fn optionality_undetermined_with_formals( + n: Rc, + formals: Rc>, + source_indices: Rc>>, +) -> bool { + match n.inferred.clone() { + Some(i) => is_type_variable(i.clone()), + std::option::Option::None => { + node_names_enclosing_formal(n.clone(), formals.clone(), source_indices.clone()) + } + } +} + +pub fn optionality_undetermined(n: Rc) -> bool { + match n.inferred.clone() { + Some(i) => is_type_variable(i.clone()), + std::option::Option::None => false, + } +} + +pub fn optional_into_required_mismatch_with_formals( + declared: Rc, + produced: Rc, + formals: Rc>, + source_indices: Rc>>, +) -> Rc { + if node_carries_optional(produced.clone()) { + if optionality_undetermined_with_formals( + declared.clone(), + formals.clone(), + source_indices.clone(), + ) { + Rc::new(OptionalNarrowing::NarrowingUndetermined { + cause: OptionalNarrowingCause::DeclaredFormalUnsubstituted, + }) + } else { + if node_carries_optional(declared.clone()) { + Rc::new(OptionalNarrowing::ConformsOrWidens) + } else { + Rc::new(OptionalNarrowing::NarrowsToRequired) + } + } + } else { + Rc::new(OptionalNarrowing::ConformsOrWidens) + } +} + +pub fn optional_into_required_mismatch( + declared: Rc, + produced: Rc, +) -> Rc { + if node_carries_optional(produced.clone()) { + if optionality_undetermined(declared.clone()) { + Rc::new(OptionalNarrowing::NarrowingUndetermined { + cause: OptionalNarrowingCause::DeclaredFormalUnsubstituted, + }) + } else { + if node_carries_optional(declared.clone()) { + Rc::new(OptionalNarrowing::ConformsOrWidens) + } else { + Rc::new(OptionalNarrowing::NarrowsToRequired) + } + } + } else { + Rc::new(OptionalNarrowing::ConformsOrWidens) + } +} + +pub fn optional_narrowing_diags( + v: Rc, + declared: Rc, + span: Rc, + module_name: String, + source_indices: Rc>>, +) -> Rc>> { + match (*v.clone()).clone() { + OptionalNarrowing::ConformsOrWidens => Rc::new(vec![]), + OptionalNarrowing::NarrowsToRequired => Rc::new(vec![crate::v1_std_core::make_error_node( + Rc::new(CompilerDiagnostic::OptionalValueInRequiredPosition { + declared: crate::v1_compiler_infer_types::node_type_shape( + declared.clone(), + source_indices.clone(), + ), + span: span.clone(), + }), + module_name.clone(), + )]), + OptionalNarrowing::NarrowingUndetermined { cause: c, .. } => { + Rc::new(vec![crate::v1_std_core::make_error_node( + Rc::new(CompilerDiagnostic::OptionalNarrowingUndetermined { + declared: crate::v1_compiler_infer_types::node_type_shape( + declared.clone(), + source_indices.clone(), + ), + cause: optional_narrowing_cause_text(c.clone()), + span: span.clone(), + }), + module_name.clone(), + )]) + } + } +} + pub fn declared_type_conformance_diags( declared: Rc, produced: Rc, @@ -1645,15 +1809,16 @@ pub fn field_type_admits_bare_none(ft: Rc, scope: Rc) -> bool } } -pub fn expr_is_bare_none_reference(texpr: Rc, scope: Rc) -> bool { +pub fn expr_is_bare_none_reference( + texpr: Rc, + source_indices: Rc>>, +) -> bool { match (*texpr.expr_data.clone()).clone() { ExprData::ExprVar { binding_kind: _, .. } => { - (crate::v1_std_core::expr_var_name_at( - texpr.clone(), - scope.type_env.clone().source_indices.clone(), - ) == "None".to_string()) + (crate::v1_std_core::expr_var_name_at(texpr.clone(), source_indices.clone()) + == "None".to_string()) } _ => false, } @@ -1670,8 +1835,10 @@ pub fn bare_none_field_construction_diags( std::option::Option::None => Rc::new(vec![]), Some(ft) => { let value_expr = crate::v1_std_core::field_init_node_value(fi.clone()); - if ((expr_is_bare_none_reference(value_expr.clone(), scope.clone()) - && field_declared_type_is_identified(ft.clone(), scope.clone())) + if ((expr_is_bare_none_reference( + value_expr.clone(), + scope.type_env.clone().source_indices.clone(), + ) && field_declared_type_is_identified(ft.clone(), scope.clone())) && (field_type_admits_bare_none(ft.clone(), scope.clone()) == false)) { Rc::new(vec![crate::v1_std_core::make_error_node( @@ -1707,6 +1874,43 @@ pub fn field_type_is_optional_coproduct(ft: Rc, env: Rc) -> bool } } +pub fn record_lit_enclosing_formals( + type_name: Option, + scope: Rc, +) -> Rc> { + match type_name.clone() { + Some(tn) => match crate::v1_compiler_infer_env::lookup_type_by_name( + scope.type_env.clone(), + tn.clone(), + ) { + Some(decl) => Rc::new({ + let mut __result = Vec::new(); + for pn in decl.params.clone().iter().cloned() { + __result.push(crate::v1_std_core::authored_name_at( + scope.type_env.clone().source_indices.clone(), + pn.clone(), + )); + } + __result + }), + std::option::Option::None => match variant_owner_node(scope.clone(), tn.clone()) { + Some(parent) => Rc::new({ + let mut __result = Vec::new(); + for pn in parent.params.clone().iter().cloned() { + __result.push(crate::v1_std_core::authored_name_at( + scope.type_env.clone().source_indices.clone(), + pn.clone(), + )); + } + __result + }), + std::option::Option::None => Rc::new(vec![]), + }, + }, + std::option::Option::None => Rc::new(vec![]), + } +} + pub fn record_lit_expected_fields( type_name: Option, scope: Rc, @@ -3493,10 +3697,7 @@ pub fn equality_operand_admission( } else { { let peeled = crate::v1_compiler_infer_types::normalize_access_type_node(n.clone()); - if ((peeled.return_cardinality.clone() == Cardinality::CardOptional) - || ((peeled.name.clone() == "Optional".to_string()) - && ((peeled.children.clone().len() as i64) == 1))) - { + if node_carries_optional(peeled.clone()) { equality_operand_admission( crate::v1_compiler_infer_types::extract_optional_inner_node(peeled.clone()), scope.clone(), @@ -6579,10 +6780,15 @@ if match (*actual_expr.expr_data.clone()).clone() { { let actual_raw = crate::v1_compiler_infer_types::resolved_type(actual_expr.clone()); let actual = crate::v1_compiler_infer_resolve::peel_nominal_alias_identity(actual_raw.clone(), type_env.clone(), module_name.clone()); -if direct_call_arg_type_mismatch(formal.clone(), actual.clone(), type_env.clone(), module_name.clone(), source_indices.clone()) { - Rc::new(vec![type_mismatch_error(crate::v1_compiler_infer_types::node_type_shape(formal.clone(), source_indices.clone()), crate::v1_compiler_infer_types::node_type_shape(actual.clone(), source_indices.clone()), actual_expr.span.clone(), module_name.clone())]) +let narrowing_diags = optional_narrowing_diags(optional_into_required_mismatch(app.formal_subst.clone(), actual_raw.clone()), app.formal_subst.clone(), actual_expr.span.clone(), module_name.clone(), source_indices.clone()); +if ((expr_is_bare_none_reference(actual_expr.clone(), source_indices.clone()) == false) && ((narrowing_diags.clone().len() as i64) > 0)) { + narrowing_diags.clone() } else { - Rc::new(vec![]) + if direct_call_arg_type_mismatch(formal.clone(), actual.clone(), type_env.clone(), module_name.clone(), source_indices.clone()) { + Rc::new(vec![type_mismatch_error(crate::v1_compiler_infer_types::node_type_shape(formal.clone(), source_indices.clone()), crate::v1_compiler_infer_types::node_type_shape(actual.clone(), source_indices.clone()), actual_expr.span.clone(), module_name.clone())]) + } else { + Rc::new(vec![]) + } } } } @@ -12920,16 +13126,21 @@ Rc::new(vec![type_mismatch_error(crate::v1_compiler_infer_types::node_type_shape }; let formal_peeled = crate::v1_compiler_infer_resolve::peel_nominal_alias_identity(expected_required.clone(), scope.type_env.clone(), scope.module_name.clone()); let actual_peeled = crate::v1_compiler_infer_resolve::peel_nominal_alias_identity(got_node.clone(), scope.type_env.clone(), scope.module_name.clone()); -if kernel_value_declared_type_mismatch(formal_peeled.clone(), actual_peeled.clone(), scope.type_env.clone(), scope.type_env.clone().source_indices.clone()) { - Rc::new(vec![type_mismatch_error(crate::v1_compiler_infer_types::node_type_shape(formal_peeled.clone(), scope.type_env.clone().source_indices.clone()), crate::v1_compiler_infer_types::node_type_shape(actual_peeled.clone(), scope.type_env.clone().source_indices.clone()), ar_typed.span.clone(), scope.module_name.clone())]) +let narrowing_diags = optional_narrowing_diags(optional_into_required_mismatch_with_formals(expected_node.clone(), got_node.clone(), record_lit_enclosing_formals(type_name.clone(), scope.clone()), scope.type_env.clone().source_indices.clone()), expected_node.clone(), ar_typed.span.clone(), scope.module_name.clone(), scope.type_env.clone().source_indices.clone()); +if ((expr_is_bare_none_reference(ar_typed.clone(), scope.type_env.clone().source_indices.clone()) == false) && ((narrowing_diags.clone().len() as i64) > 0)) { + narrowing_diags.clone() } else { - if structured_application_site_type_mismatch(expected_node.clone(), crate::v1_std_core::field_init_node_value(fi.clone()), scope.clone()) { + if kernel_value_declared_type_mismatch(formal_peeled.clone(), actual_peeled.clone(), scope.type_env.clone(), scope.type_env.clone().source_indices.clone()) { Rc::new(vec![type_mismatch_error(crate::v1_compiler_infer_types::node_type_shape(formal_peeled.clone(), scope.type_env.clone().source_indices.clone()), crate::v1_compiler_infer_types::node_type_shape(actual_peeled.clone(), scope.type_env.clone().source_indices.clone()), ar_typed.span.clone(), scope.module_name.clone())]) } else { - if ((expected_node.return_cardinality.clone() != Cardinality::CardOptional) && coproduct_payload_where_parent_required(formal_peeled.clone(), actual_peeled.clone(), scope.clone())) { + if structured_application_site_type_mismatch(expected_node.clone(), crate::v1_std_core::field_init_node_value(fi.clone()), scope.clone()) { Rc::new(vec![type_mismatch_error(crate::v1_compiler_infer_types::node_type_shape(formal_peeled.clone(), scope.type_env.clone().source_indices.clone()), crate::v1_compiler_infer_types::node_type_shape(actual_peeled.clone(), scope.type_env.clone().source_indices.clone()), ar_typed.span.clone(), scope.module_name.clone())]) } else { - Rc::new(vec![]) + if ((expected_node.return_cardinality.clone() != Cardinality::CardOptional) && coproduct_payload_where_parent_required(formal_peeled.clone(), actual_peeled.clone(), scope.clone())) { + Rc::new(vec![type_mismatch_error(crate::v1_compiler_infer_types::node_type_shape(formal_peeled.clone(), scope.type_env.clone().source_indices.clone()), crate::v1_compiler_infer_types::node_type_shape(actual_peeled.clone(), scope.type_env.clone().source_indices.clone()), ar_typed.span.clone(), scope.module_name.clone())]) + } else { + Rc::new(vec![]) + } } } } @@ -25654,6 +25865,10 @@ pub fn reconcile_with_census_extra( } } +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct DeclaredFormalUnsubstituted; +#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct ProducedTypeUnsubstituted; #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct PositionRecordLiteralField; #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] diff --git a/src/v1/stage0/src/v1_compiler_infer_types.rs b/src/v1/stage0/src/v1_compiler_infer_types.rs index dbef15a2a74..0d2352734fc 100644 --- a/src/v1/stage0/src/v1_compiler_infer_types.rs +++ b/src/v1/stage0/src/v1_compiler_infer_types.rs @@ -35,6 +35,7 @@ pub use crate::std_types::{ pub use crate::v1_compiler_infer_env::TypeBinding; use crate::v1_rt; use crate::v1_rt::{VecCompat, VecJoin}; +pub use crate::v1_std_core::node_carries_optional; use crate::v1_std_core::Cardinality::{CardOptional, Required}; use crate::v1_std_core::CompilerDiagnostic::InternalError; use crate::v1_std_core::Connective::{Conj, Disj, NoConnective}; @@ -2987,21 +2988,15 @@ pub fn method_receiver_element_node( } pub fn extract_optional_inner_node(n: Rc) -> Rc { - { - let is_optional = (n.return_cardinality.clone() == Cardinality::CardOptional); - if is_optional.clone() { - crate::v1_std_core::with_required_cardinality(n) - } else { - if ((n.name.clone() == "Optional".to_string()) - && ((n.children.clone().len() as i64) == 1)) - { - match n.children.clone().first().cloned() { - Some(inner) => inner.clone(), - std::option::Option::None => n, - } - } else { - n - } + if (node_carries_optional(n.clone()) == false) { + n.clone() + } else { + match n.return_cardinality.clone() { + Cardinality::CardOptional => crate::v1_std_core::with_required_cardinality(n.clone()), + Cardinality::Required => match n.children.clone().first().cloned() { + Some(inner) => inner.clone(), + std::option::Option::None => n.clone(), + }, } } } diff --git a/src/v1/stage0/src/v1_interpreter.rs b/src/v1/stage0/src/v1_interpreter.rs index 06fd8df8d00..edd6d7e129f 100644 --- a/src/v1/stage0/src/v1_interpreter.rs +++ b/src/v1/stage0/src/v1_interpreter.rs @@ -9020,21 +9020,83 @@ fn eval_field_access( let access_style = summary.map(|s| &s.access_style); + // `field_summary_for_type` decides field access in TWO parts, and this evaluator used to + // consume only the first. `value_shape: OptionalValue` is the checker's FUNCTOR LIFT: field + // access through an `Optional` yields an `Optional`, PRESERVING the empty case rather than + // erasing it. Reading the field directly off the `Optional` value instead -- which is what + // dropping `value_shape` amounts to -- refuses with `NoSuchField { "Optional", .. }` on every + // site the checker typed as a lift, so the two arms disagreed by construction. One authority, + // both directions: the checker's decision is consumed here rather than re-derived. + if matches!( + summary.map(|s| &s.value_shape), + Some(FieldValueShape::OptionalValue) + ) { + if let Value::Variant { + type_name, + variant_name, + fields, + } = &base_val + { + if *type_name == ctx.sym("Optional") { + if *variant_name == ctx.sym("Absent") { + return Ok(optional_absent(ctx)); + } + let inner = fields_get(fields, ctx.sym("value")) + .cloned() + .unwrap_or(Value::Null); + let lifted = field_access_by_style(access_style, inner, &field_name, env, ctx)?; + return Ok(optional_present(lifted, ctx)); + } + } + } + + field_access_by_style(access_style, base_val, &field_name, env, ctx) +} + +/// The `access_style` half of a `FieldSummary`, applied to one already-selected value. Split out +/// so the `OptionalValue` lift above can run it on the payload rather than on the wrapper. +fn field_access_by_style( + access_style: Option<&FieldAccessStyle>, + base_val: Value, + field_name: &str, + env: &Rc, + ctx: &InterpContext, +) -> InterpResult { match access_style { Some(FieldAccessStyle::TupleFirst) => match expect_list(&base_val, "tuple.first") { Ok(items) => Ok(items.front().cloned().unwrap_or(Value::Null)), - Err(_) => extract_field(&base_val, &field_name, env, ctx), + Err(_) => extract_field(&base_val, field_name, env, ctx), }, Some(FieldAccessStyle::TupleSecond) => match expect_list(&base_val, "tuple.second") { Ok(items) => Ok(items.get(1).cloned().unwrap_or(Value::Null)), - Err(_) => extract_field(&base_val, &field_name, env, ctx), + Err(_) => extract_field(&base_val, field_name, env, ctx), }, + // This arm was written against the NULL-SENTINEL encoding, where an absent optional was + // `Value::Null` and a present one was the bare element -- so returning `base_val` WAS the + // unwrap. Constructing a real `Optional` variant for `first`/`last` retires that encoding + // here, and returning `base_val` would now hand back the wrapper instead of its payload. + // The `Absent` case keeps the pre-existing `Value::Null` result rather than being + // repaired: the unwrap style has no plain value to yield there, and that gap is the + // separately-filed `.value`-spelling ambiguity, not this change's subject. Some(FieldAccessStyle::OptionalUnwrap) => match &base_val { Value::Null => Ok(Value::Null), + Value::Variant { + type_name, + variant_name, + fields, + } if *type_name == ctx.sym("Optional") => { + if *variant_name == ctx.sym("Absent") { + Ok(Value::Null) + } else { + Ok(fields_get(fields, ctx.sym("value")) + .cloned() + .unwrap_or(Value::Null)) + } + } _ => Ok(base_val), }, - Some(FieldAccessStyle::EnumAccessor) => extract_field(&base_val, &field_name, env, ctx), - _ => extract_field(&base_val, &field_name, env, ctx), + Some(FieldAccessStyle::EnumAccessor) => extract_field(&base_val, field_name, env, ctx), + _ => extract_field(&base_val, field_name, env, ctx), } } @@ -9936,13 +9998,27 @@ macro_rules! v1_algebra_method_arms { }, arm "method_call.first" { "first" } => { + // std.algebra free_monoid_collection_templates declares + // first [ReceiverSelf] -> OptionalOf { inner: ReceiverElement } + // so the result is an Optional OF THE ELEMENT: at element type U? the two + // absences are distinct levels. Constructing them here -- rather than + // returning a bare element or a Value::Null sentinel -- is the same + // call-site construction `map_lookup_as_optional` already performs for maps. let items = expect_list(&$receiver, "first")?; - Ok(items.front().cloned().unwrap_or(Value::Null)) + Ok(match items.front().cloned() { + Some(v) => optional_present(v, $ctx), + None => optional_absent($ctx), + }) }, arm "method_call.last" { "last" } => { + // Same declaration, same construction: last [ReceiverSelf] -> + // OptionalOf { inner: ReceiverElement }. let items = expect_list(&$receiver, "last")?; - Ok(items.last().cloned().unwrap_or(Value::Null)) + Ok(match items.last().cloned() { + Some(v) => optional_present(v, $ctx), + None => optional_absent($ctx), + }) }, arm "method_call.reverse" { "reverse" } => { diff --git a/src/v1/stage0/src/v1_std_core.rs b/src/v1/stage0/src/v1_std_core.rs index 28483018d9e..8c6200797ff 100644 --- a/src/v1/stage0/src/v1_std_core.rs +++ b/src/v1/stage0/src/v1_std_core.rs @@ -487,6 +487,15 @@ pub enum CompilerDiagnostic { got: String, span: Rc, }, + OptionalValueInRequiredPosition { + declared: String, + span: Rc, + }, + OptionalNarrowingUndetermined { + declared: String, + cause: String, + span: Rc, + }, ArityMismatch { name: String, expected: i64, @@ -805,6 +814,8 @@ pub fn diagnostic_to_span(d: Rc) -> Rc { s.clone() } CompilerDiagnostic::TypeMismatch { span: s, .. } => s.clone(), + CompilerDiagnostic::OptionalValueInRequiredPosition { span: s, .. } => s.clone(), + CompilerDiagnostic::OptionalNarrowingUndetermined { span: s, .. } => s.clone(), CompilerDiagnostic::ArityMismatch { span: s, .. } => s.clone(), CompilerDiagnostic::VariantNotFound { span: s, .. } => s.clone(), CompilerDiagnostic::FieldNotFound { span: s, .. } => s.clone(), @@ -872,6 +883,8 @@ pub fn diagnostic_to_message(d: Rc) -> String { CompilerDiagnostic::UnresolvedType { name: n, .. } => v1_rt::concat(v1_rt::concat("unresolved type '".to_string(), n.clone()), "'".to_string()), CompilerDiagnostic::UnitVariantPhantomIdentityEvidenceUnavailable { name: n, .. } => v1_rt::concat(v1_rt::concat("unit-variant marker identity evidence unavailable for '".to_string(), n.clone()), "'".to_string()), CompilerDiagnostic::TypeMismatch { expected: e, got: g, .. } => v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat("type mismatch: expected '".to_string(), e.clone()), "', got '".to_string()), g.clone()), "'".to_string()), + CompilerDiagnostic::OptionalValueInRequiredPosition { declared: d, .. } => v1_rt::concat(v1_rt::concat("optional value in a required position: this position is declared '".to_string(), d.clone()), "' and the value may be ABSENT. The declared type is not a rendering of the value's shape here -- an optional and its payload print identically at a primitive kernel -- so the cause is named rather than shown. Match on the value and decide the absent case, or supply a default.".to_string()), + CompilerDiagnostic::OptionalNarrowingUndetermined { declared: d, cause: c, .. } => v1_rt::concat(v1_rt::concat(v1_rt::concat("cannot judge this position: optionality is not established either way, and the position is rendered '".to_string(), d.clone()), "'. The check DECLINES rather than concluding required -- concluding required from an operand that carries no answer is the accusing arm of an absorbing fallback. This counts the CHECK'S OWN deficit, NOT a defect in the code at this position. Cause: ".to_string()), c.clone()), CompilerDiagnostic::ArityMismatch { name: n, expected: e, got: g, .. } => v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat("type ".to_string(), n.clone()), " expects ".to_string()), (e.clone()).to_string()), " type arguments, got ".to_string()), (g.clone()).to_string()), CompilerDiagnostic::VariantNotFound { variant: v, type_name: t, .. } => v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat("variant '".to_string(), v.clone()), "' not found in type '".to_string()), t.clone()), "'".to_string()), CompilerDiagnostic::FieldNotFound { field: f, type_name: t, .. } => v1_rt::concat(v1_rt::concat(v1_rt::concat(v1_rt::concat("field '".to_string(), f.clone()), "' not found in type '".to_string()), t.clone()), "'".to_string()), @@ -4656,6 +4669,16 @@ pub fn module_path_segments(path: String) -> Rc> { } } +pub fn node_carries_optional(n: Rc) -> bool { + match n.return_cardinality.clone() { + Cardinality::CardOptional => true, + Cardinality::Required => { + ((qualified_last_segment(n.name.clone()) == "Optional".to_string()) + && ((n.children.clone().len() as i64) == 1)) + } + } +} + pub fn qualified_last_segment(name: String) -> String { match module_path_segments(name.clone()).last().cloned() { Some(s) => s.clone(),