diff --git a/changelog.d/409.md b/changelog.d/409.md new file mode 100644 index 000000000..45bb4264a --- /dev/null +++ b/changelog.d/409.md @@ -0,0 +1,5 @@ +--- +section: authoring +--- + +- **Extractions can report whether their subject is present** (#409). `extraction/v0` has a new optional `presence` field, `present` or `absent`, that says whether what a projection describes exists at the revision, such as a workflow the revision predates. Omitted means not reported, which hosts treat as unknown, never present. The engine rejects an `absent` extraction that has entities or relationships, or that names nothing in `missingInputs`, and it keeps `presence` as written, so extractions that omit it keep their digests. Custom extractors check the files that make up their subject with `request.subjectExists()` and `request.subjectMatches()` in Node, `request.subject_exists()` and `request.subject_matches()` in Python, or `Context::subject_exists` and `Context::subject_matches` in the Rust extractor SDK. `result()` then writes `presence`: `absent` when none of them exists, and `present` otherwise. `engine.presence(before, after)` (and `presenceChange` in `@githubnext/projections-schemas`) reports whether a change added, removed or kept a subject. In the Rust SDK, `Context::finish` now returns a `Result`. Built-in extractors will write `presence` in a later release, which changes their digests once, and `extraction/v1` will require it. See [presence](docs/contracts/extractions.md#presence). diff --git a/docs/agents/create-projection.md b/docs/agents/create-projection.md index 4dd85b275..e9b88107f 100644 --- a/docs/agents/create-projection.md +++ b/docs/agents/create-projection.md @@ -471,7 +471,8 @@ in the examined revision, `request.checkout` where its dependencies are, files in the revision, project-relative), and `result(entities=..., relationships=...)` writes the extraction, items as lists with an `id` or as dicts keyed by ID, sorted, `graph/v0` unless -`schema="..."`, with optional `metadata`, `volatile` and `missing_inputs`: +`schema="..."`, with optional `metadata`, `volatile`, `presence` and +`missing_inputs`: ```python from projections import request, result @@ -495,7 +496,17 @@ import {request, result} from '@githubnext/projections-sdk/extractor' result({entities: {'service:payments': {kind: 'service', label: 'Payments'}}}) ``` -In other languages, write the JSON above. +When what the projection describes may not exist at a revision (a workflow, +a manifest the revision predates), check it before reading it: +`request.subject_exists("flags.yaml")` in Python, +`request.subjectExists('flags.json')` in JavaScript, or `subject_matches` / +`subjectMatches` for a glob. If none of the anchors you checked exists, return +no items. `result()` then writes `presence: "absent"` with the path in +`missingInputs`, and hosts show the subject as added or removed rather than +empty. Don't fail, and don't return a bare empty extraction. + +In other languages, write the JSON above, with `"presence": "absent"` and the +missing path in `missingInputs` when the subject doesn't exist. - `graph/v0`: entities and directed relationships between them; the general choice. Built-in extractors present it with `architecture`, `dependencies`, `file-packing`, `gallery`, `graph`, `text-diff`. - Fields and strictness: no typed `data`, so every `data` field is open JSON (https://github.com/githubnext/projections/blob/main/docs/reference/schemas/graph.md). diff --git a/docs/contracts.md b/docs/contracts.md index 77af944e3..24dcf9db9 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -254,9 +254,9 @@ explaining why. Hosted views never load artifact-supplied renderers. ## One implementation, native and browser Both the native and browser Engines implement the same request/response contract -(engine ABI version 0), exposing eight operations: `parse-json`, `decode`, -`normalize`, `canonicalize`, `validate-comparison`, `vary`, `pair`, and -`review`. +(engine ABI version 0), exposing nine operations: `parse-json`, `decode`, +`normalize`, `canonicalize`, `validate-comparison`, `vary`, `pair`, `review`, +and `presence`. - `review` (`{comparison}`, reading only each change's `status`, `correspondence`, and `varied` fields on an engine-validated comparison) @@ -289,6 +289,20 @@ Both the native and browser Engines implement the same request/response contract Wasm. Code outside the engine never compares digests or definitions on its own; the `no-restricted-syntax` rules in `tools/scripts/engine-contracts.mjs` flag any attempt to do so. +- `presence` (`{before, after}`, reading only `presence`, `missingInputs`, and + whether `entities` or `relationships` has an item) says whether what two + extractions describe exists on each side and what the change did to it: + `{before, after, change, inferred}`. Each side is `present`, `absent`, or + `unknown`. `change` is `added`, `removed`, `absent` (on both sides), + `present`, or `unknown`. A side that omits `presence` is inferred `present` + when it has items and `absent` when it has none and names missing inputs, and + is otherwise unknown; `inferred` is true when either side was inferred (see + [presence](contracts/extractions.md#presence)). The CLI calls + `projections_engine::presence_change`, JavaScript hosts call + `engine.presence(before, after)`, and `presenceChange` in + `@githubnext/projections-schemas` mirrors it for callers that can't wait on + the engine; the shared conformance corpus holds all of them to the same + answers. - `vary` (`{before, after}`) compares two extractions of the same revision—such as a rerun—item by item by ID without matching. It returns diff --git a/docs/contracts/extractions.md b/docs/contracts/extractions.md index 4964d638f..07a5c3b4f 100644 --- a/docs/contracts/extractions.md +++ b/docs/contracts/extractions.md @@ -2,10 +2,11 @@ An extraction is the snapshot an extractor produces for a single revision. Every extraction includes `protocolVersion: 0`, a domain `schema`, `entities`, and -`relationships`, along with optional `volatile`, `missingInputs`, and `metadata` -fields. The seven domain schemas are `graph/v0`, `dag/v0`, `treemap/v0`, -`metrics/v0`, `api/v0`, `database/v0`, and `architecture/v0`. Extractor IDs are -just names—they are not an engine-owned catalog or extension boundary. +`relationships`, along with optional `volatile`, `missingInputs`, `presence`, +and `metadata` fields. The seven domain schemas are `graph/v0`, `dag/v0`, +`treemap/v0`, `metrics/v0`, `api/v0`, `database/v0`, and `architecture/v0`. +Extractor IDs are just names—they are not an engine-owned catalog or extension +boundary. `missingInputs` records any declared inputs (repository-relative files, folders, or globs) that do not exist at the examined revision—for instance, an older @@ -16,6 +17,9 @@ most 1024 characters with no NULs, up to 256 entries (`duplicate-missing-input`, field if the list is empty. Runners surface missing inputs as comparison notices, and they are included in the extraction's canonical bytes. +`presence` says whether what the projection describes, its subject, exists at +the revision; see [Presence](#presence). + An extraction can also declare `vocabularies`—typed conventions layered on top of its domain schema, such as `dependency-injection/v0`, `infrastructure/v0`, and `runtime-policy/v0` over `architecture/v0`, or `scenarios/v0` over @@ -104,6 +108,73 @@ without normalizing Unicode text. Extractions are bounded to 10,000 entities, and unknown fields are rejected outright rather than silently dropped—any custom extension belongs in explicit `data` or `metadata` objects. +## Presence + +An extraction's subject is what its projection describes: a workflow file, a +package manifest, a set of schema files. `presence` reports whether it exists at +the examined revision: + +- `present`: it exists, though it may be empty. Zero items means "present and + empty". +- `absent`: it doesn't. For example, the revision predates the workflow. An + absent extraction has no entities or relationships, and its `missingInputs` + names what is missing, so a host can say what isn't there. +- Omitted: not reported. That means unknown, never present. + +```json +{ + "protocolVersion": 0, + "schema": "dag/v0", + "presence": "absent", + "entities": [], + "relationships": [], + "missingInputs": [".github/workflows/release.yml"], + "metadata": {"workflow": ".github/workflows/release.yml"} +} +``` + +The engine rejects any other value (`invalid-presence`), an absent extraction +with items (`absent-with-items`), and one whose `missingInputs` is empty or +omitted (`absent-without-missing-input`). It keeps `presence` as written, either +value, and includes it in the canonical bytes. An extraction that omits it keeps +the bytes and digest it had before the field existed. When reruns report +different presence, the extractor isn't deterministic: `vary` reports +`/presence` as a difference beyond tolerance. + +Presence is separate from the other states an extraction can be in. A missing +auxiliary input, one whose absence leaves the subject in place, is recorded in +`missingInputs` with the subject still `present`. A subject that exists but +can't be read fails the extraction, as before, rather than reporting it absent. +An extractor that describes the whole repository or project always has its +subject: include globs that match nothing select nothing, so the extraction is +present and empty. + +Extractors set `presence` through the SDK helpers: `subject_exists` and +`subject_matches` in Rust, `request.subjectExists()` and +`request.subjectMatches()` in Node, `request.subject_exists()` and +`request.subject_matches()` in Python. Each records an anchor of the subject. +The extraction is `absent` when none of the anchors checked exists, and +`present` otherwise. Each missing anchor is also added to `missingInputs` (see +[extractors](extractors.md#an-absent-subject)). + +A pair of extractions has one presence state, which the engine derives +(`engine.presence(before, after)`, the `presence` operation) and +`presenceChange` in `@githubnext/projections-schemas` mirrors without the +engine. The shared conformance corpus holds both to the same answers. Each side +is `present` or `absent` as reported. A side that omits `presence` is `unknown` +unless it can be inferred: `present` when it has items, which an absent +extraction can't have, or `absent` when it has none and names missing inputs. +That second rule is the legacy heuristic, and it misreads a present, empty +subject that lacks only an auxiliary input. The pair's `change` is `added` +(absent, then present), `removed` (present, then absent), `absent` (absent on +both sides), `present` (present on both sides), or `unknown` when either side +is. `inferred` is true when either side's presence was inferred. Comparisons +stay item-level: a subject that's added still shows every item as added. + +Built-in extractors will write `presence` on every extraction, so their digests +change once when they start. In `extraction/v1`, `presence` will be required, +and the inference will go away. + ## Volatile data Extractions behave much like test results: determinism is the goal, but some @@ -235,9 +306,9 @@ Canonical bytes are produced by sorting `entities` and `relationships` by UTF-16 code-unit ID order and serializing with RFC 8785 JSON canonicalization. Omitted item `data` becomes `{}`. Evidence, previous IDs, and extraction metadata are excluded, while kind, label, data, confidence, relationship endpoints, IDs, -normalized `volatile` declarations, and `missingInputs` are included. Because -volatile values are still ordinary data, two runs that differ within tolerance -produce different digests. Negative zero canonicalizes to zero, and object keys -and numeric formatting follow RFC 8785 rather than locale sorting or host -insertion order. The extraction digest is the lowercase SHA-256 of these UTF-8 -bytes. +normalized `volatile` declarations, `missingInputs`, and `presence` (when +written) are included. Because volatile values are still ordinary data, two runs +that differ within tolerance produce different digests. Negative zero +canonicalizes to zero, and object keys and numeric formatting follow RFC 8785 +rather than locale sorting or host insertion order. The extraction digest is the +lowercase SHA-256 of these UTF-8 bytes. diff --git a/docs/contracts/extractors.md b/docs/contracts/extractors.md index 483d42d2e..ab86e59c1 100644 --- a/docs/contracts/extractors.md +++ b/docs/contracts/extractors.md @@ -203,6 +203,27 @@ cancellation, missing tools, invalid output, or partial extraction, fail explicitly with a nonzero exit status and a clear message on stderr—never recover by emitting a valid-looking empty extraction. +## An absent subject + +If what the projection describes doesn't exist at the revision, emit an absent +extraction instead of failing or returning a bare empty one. Examples: a +workflow the revision predates, or a manifest it removed. An absent extraction +has `presence: "absent"`, no items, and the missing path in `missingInputs` (see +[presence](extractions.md#presence)). A pull request that adds the subject then +compares an absent base with a present head and shows it as added. + +The helpers do this for you. Check each anchor of the subject, meaning a path or +glob that names it, with `subject_exists`/`subject_matches` in the Rust SDK, +`request.subjectExists()`/`request.subjectMatches()` in Node, or +`request.subject_exists()`/`request.subject_matches()` in Python. Each one +records a missing anchor in `missingInputs`. At the end, the extraction is +`absent` when no anchor checked exists and `present` otherwise. An extractor +that finds none of its subject but still returns items fails with a message +naming the anchors. Check auxiliary inputs, whose absence leaves the subject in +place, with Rust's `input_exists` instead; they never affect `presence`. An +extractor that checks no anchor reports no `presence` unless it sets it itself, +and hosts read an unreported presence as unknown. + ## Built-in extractors Built-in extractors use the exact same interface as custom ones. Each runs as diff --git a/docs/design/proposals/subject-presence.md b/docs/design/proposals/subject-presence.md new file mode 100644 index 000000000..131e83f38 --- /dev/null +++ b/docs/design/proposals/subject-presence.md @@ -0,0 +1,219 @@ +# Proposal: subject presence + +Status: **in progress**. Phase 1 (the contract: schema, Engine and SDK helpers) +is implemented; the other phases are proposals. Trigger: +[#373](https://github.com/githubnext/projections/issues/373). + +A projection describes something: a workflow, a package manifest, a set of +schema files. Call that its subject. Sometimes a revision doesn't have the +subject at all. For example, the base of a pull request that adds a workflow +predates it. This proposal makes "the subject doesn't exist here" a fact that an +extraction states, so every surface can say "this change adds the workflow" +instead of "this workflow declares no jobs". + +## The problem + +In #373, a projection of `.github/workflows/release.yml` is compared across a +pull request that adds the file. The base side's pane says "No jobs. This +revision of the workflow declares no jobs." That's wrong: the file doesn't exist +there. + +The information is there, but it gets lost on the way: + +1. The `github-actions-jobs` extractor checks the file with `input_exists`, + finds it missing, and returns an empty extraction. The SDK records the path + in `missingInputs`. +2. The CLI turns `missingInputs` into a comparison notice: "the file doesn't + exist at the base, so its contents show as added." +3. The viewer hides notices that mention paths, and the renderer never reads + `missingInputs`. So the pane falls back to its "present but empty" copy. + +For `github-actions-jobs`, "present but empty" can't even happen, because a +workflow with no jobs is an extraction error. So that empty state only ever +appears for an absent workflow, and its copy is wrong every time. + +The underlying gap is in the model. `missingInputs` means "some declared input +is missing". It doesn't mean "what this projection describes is missing". +Consumers infer absence with a heuristic: `missingInputs` is nonempty and there +are no items. That misfires when only an auxiliary input is missing and the +subject is empty, for example tetragon policies with no `agentValuesPath`. It +also can't help extractors that never record missing inputs, such as glob-based +and custom extractors. + +## The states + +| State | Representation | +| --------------------------------------- | ------------------------------------------------------------------------- | +| Projection not defined at the revision | Pairing notices, unchanged. A fact about the definition, not the subject. | +| Subject absent | `presence: "absent"`, no items, at least one `missingInputs` entry. | +| Subject present and empty | `presence: "present"` and zero items. | +| Subject partly present | `presence: "present"`, with `missingInputs` naming what's missing. | +| Subject present, some items unreadable | `present`, with `metadata.limitations`, unchanged. | +| Subject present but unreadable/invalid | The extraction fails, unchanged. Absence is never a recovered failure. | +| Presence not reported (older extractor) | `presence` omitted: unknown. | + +Presence is the only fact the protocol lacks, and it's binary. "Empty" is +present with zero items. "Partial" is present with `missingInputs` or +limitations. "Failed" means there's no extraction. Adding `empty`, `partial`, or +`failed` values would duplicate facts that already exist and permit +contradictions, such as `empty` with items. + +There are three kinds of subjects: + +- A single anchor, where one path names the subject: a workflow, a manifest, a + project, a plan. It's absent when the anchor is missing. +- Multiple anchors, a list of paths or globs: schema files, routes files, + tsconfigs, policy globs. It's absent when every anchor is missing. When only + some are missing, it's present but partial. +- Repository-wide, where the subject is the repository or project itself: code + statistics, a repository map. It's always present. An include glob that + matches nothing is an empty selection, not an absent subject. + +## The decision + +Presence is one extraction-level fact, `presence`, which extractors set through +the SDK helpers. Its values are `present` and `absent`, and it's optional in +`extraction/v0`: + +- `present`: the subject exists, though it may be empty. +- `absent`: the subject doesn't exist. The extraction has no entities or + relationships, and `missingInputs` names at least one missing anchor. +- Omitted: not reported, which means unknown, never present. Consumers treat an + omitted presence as unknown. They may fall back to the legacy heuristic (no + items and some `missingInputs` means absent) and say so, or show nothing. + +The Engine keeps `presence` exactly as written, either value, and includes it in +the canonical bytes. An extraction that omits it keeps the bytes and digest it +had before. Built-in extractors will always write it, so their digests change +once when they start. In `extraction/v1`, `presence` becomes required and the +heuristic goes away. + +Other designs were rejected: + +- Runner-detected presence from declared subject inputs. It would be a second + source of truth beside the extractor's own discovery rules, defaults, and + globs. It remains useful later as an optimization that produces the same + extraction (Phase 4). +- The heuristic alone. It misfires on missing auxiliary inputs and can't see + extractors that don't record missing inputs. It stays only as the fallback for + unreported presence. +- A root "subject" entity. It would change every digest, show up as a spurious + added or removed item, and force every renderer to special-case it. +- Failing the extraction when the subject is absent. That contradicts "absent + isn't failed", and every pull request that adds a workflow would fail. +- Presence in runner-written provenance. It isn't part of the canonical bytes, + and renderers don't receive it. +- A field on the comparison document. Comparators are pure functions over items, + and the pair's state can be derived from the two extractions every comparison + already carries. + +The field isn't named `subject`, because that word already means what a host +shows (`ViewSubject`) and the CI event (the artifact's `subject`). + +## Specification + +### Schema + +`extraction/v0` gains an optional `presence: "present" | "absent"`. Its JSON +Schema also requires that an `absent` extraction has no entities or +relationships, and has a nonempty `missingInputs`. + +### Engine + +- The Engine parses `presence` and keeps it as written. It rejects any other + value (`invalid-presence`), an absent extraction with items + (`absent-with-items`), and an absent extraction without missing inputs + (`absent-without-missing-input`). +- `presence` is part of the canonical bytes when written. +- A presence difference between reruns is non-determinism: `vary` reports + `/presence` beyond tolerance. +- One pure function derives the pair's state: + `projections_engine::presence_change`, the `presence` operation, and + `engine.presence(before, after)` in JavaScript, native and Wasm alike. Each + side is `present` or `absent` as reported. An omitted side is inferred + `present` when it has items, since an absent extraction can't have any. It's + inferred `absent` when it has no items and names missing inputs, which is the + legacy heuristic. Otherwise it's `unknown`. The result is + `{before, after, change, inferred}`, where `change` is `added`, `removed`, + `absent`, `present`, or `unknown` (when either side is unknown). `inferred` is + true when either side was inferred. +- `presenceChange` and `extractionPresence` in `@githubnext/projections-schemas` + mirror the function for synchronous callers such as a renderer's first paint. + The `presence` cases of the shared conformance corpus + (`packages/schemas/fixtures/conformance.json`) hold the Engine, native and + Wasm, and the mirror to the same answers. + +### SDK helpers + +- In Rust, `Context::subject_exists(path)` and + `Context::subject_matches(glob, files)` check an anchor of the subject and + record a missing one in `missingInputs`. `Context::finish` writes `presence` + when any anchor was checked: `absent` when none exists, `present` otherwise. + It fails when none exists and the extractor returned items. An extraction that + sets `presence` itself keeps its own value. `input_exists` stays for auxiliary + inputs and never affects presence. +- In Node, `request.subjectExists(path)` and `request.subjectMatches(glob)` do + the same over `request.files()`, and `extraction()` and `result()` fill in + `presence` and `missingInputs`. +- In Python, `request.subject_exists(path)` and `request.subject_matches(glob)` + do the same. +- `packages/schemas/fixtures/extractor-helpers.json` holds the Node and Python + helpers to the same behavior and messages. Globs use the Rust SDK's grammar. + +### Pair wording and presentation (Phase 3) + +- Added (absent before): "`release.yml` is new at `d0c4770e`. It doesn't exist + at `2749e6e7`, so everything in it shows as added." +- Removed (absent after): "`release.yml` is removed at `d0c4770e`. It exists at + `2749e6e7`, so everything in it shows as removed." +- Absent on both sides: "… doesn't exist at A or B, so there is nothing of it to + compare." +- Unknown: today's notices, unchanged. +- An absent pane shows an absent state, such as "Workflow not added yet" or + "Workflow removed", rather than the renderer's empty state. A present, empty + pane keeps the renderer's own copy, which is then accurate. +- Hosts show presence as structured UI (a chip or pane label: "Added in this + change"), not as a notice string, so a viewer that hides paths still shows it. +- Sweeps don't count a cell that's absent on both sides as an unchanged + judgment. They count added and removed cells separately. + +Comparisons stay item-level: a subject that goes from absent to present still +shows every item as added. + +## Migration + +- **Phase 0**: fix #373 without a schema change. The kit and viewer use the + heuristic. +- **Phase 1** (this change): the contract. Add the schema field, Engine parsing, + validation, encoding, the rerun check, and the pair-state function (native, + Wasm, and the TypeScript mirror). Add the SDK helpers in Rust, Node, and + Python, plus documentation. Existing extractions keep their digests. +- **Phase 2**: built-in extractors write `presence` on every extraction, both + values. Anchors switch from `input_exists` to `subject_exists`; auxiliary + inputs keep `input_exists`. Repository-wide extractors write `present`. + Built-in digests change once. +- **Phase 3**: consumers prefer `presence`: CLI notices and `check`, the kit and + hosts, sweeps, the CI summary, and PNG snapshots. They fall back to the + inferred state only when `presence` is omitted. +- **Phase 4** (deferred): descriptor-declared subject inputs, a runner short + circuit that skips launching toolchains when the subject is absent, and rename + following. +- **v1**: `presence` is required, and inference is removed. + +## Renames (deferred) + +A definition names one path. When a pull request renames `ci.yml` to +`build.yml`, the head side shows as absent and everything shows as removed. +Later, a descriptor could declare its subject inputs. When a declared subject +path is absent on one side, the runner could then ask Git for a rename and rerun +that side with the input remapped. It would record the followed path in +provenance and keep the extraction `present`. Presence stays binary: movement is +a fact about the pair, not about one revision. + +## Open questions + +- Older readers reject extractions with `presence`, because extraction objects + are closed. Only artifacts from newer CLIs are affected. That's the same + exposure `missingInputs` had. +- Should `projections check` still fail when only an auxiliary input is missing? + Today it fails on any missing input, and this proposal keeps that behavior. diff --git a/docs/guides/first-extractor.md b/docs/guides/first-extractor.md index 03fe2eb64..f841e8e85 100644 --- a/docs/guides/first-extractor.md +++ b/docs/guides/first-extractor.md @@ -203,8 +203,31 @@ contents show as added." That only applies when a file, folder, or glob is absent; a file that exists but fails to read or parse still raises an error. On its own, `projections show` notes that there is nothing to display at that revision, and `projections check` still fails since a missing input at the -checked revision indicates a broken definition. Custom extractors can opt into -the same behavior by setting `missingInputs`. +checked revision indicates a broken definition. + +Custom extractors get the same behavior from the helpers. Check whether the file +the projection describes exists before reading it. If it doesn't, return no +items: + +```python +from projections import request, result + +if not request.subject_exists("flags.yaml"): + result() # presence "absent", with flags.yaml in missingInputs +else: + ... # read flags.yaml and call result(entities=...) as before: presence "present" +``` + +In JavaScript the check is `request.subjectExists('flags.json')`, and +`request.subjectMatches('flags/*.json')` (`subject_matches` in Python) checks a +glob. Each call records the anchor in `missingInputs` when it's missing, and +`result()` writes `presence`. The extraction is `absent` when none of the +anchors you checked exists, and `present` otherwise. If an absent extraction +returns items, the helper raises an error. Hosts can then tell "the revision has +no `flags.yaml`" from "`flags.yaml` declares no flags" (see +[presence](../contracts/extractions.md#presence)). Use these checks only for the +files that make up the subject. A missing file whose absence leaves the subject +in place belongs in `missingInputs` on its own. Because the default comparator matches entities by `id`, pick IDs that stay stable when unrelated code changes. `flag:checkout-v2` is durable; `flag:3` (an diff --git a/docs/reference/extractor-sdk.md b/docs/reference/extractor-sdk.md index 26ea1f51d..a6c9acc86 100644 --- a/docs/reference/extractor-sdk.md +++ b/docs/reference/extractor-sdk.md @@ -498,7 +498,7 @@ same whoever starts it. | `exists` | `pub fn exists(&self, relative: &str) -> Result` | Whether `relative` is a file or directory of the examined revision: one of its files, or a directory some file is inside. A path Git ignores in a checkout isn't part of the revision. | | `extractor` | `pub fn extractor(&self) -> &str` | The name of the extractor this process runs. | | `files` | `pub fn files(&self) -> Result<&[String]>` | The project's files, as project-relative POSIX paths in byte order: everything materialized under it, what Git lists in a checkout (tracked and untracked, not ignored), or the Git tree's blobs; only those in the scope when one is declared. Files outside the project aren't listed, but a scope that includes them lets them be read with `..` paths. | -| `finish` | `pub fn finish(&self, extraction: Value) -> Value` | `extraction` with the missing inputs recorded during the run, as its `missingInputs`. `crate::serve` applies it to what an extractor returns. | +| `finish` | `pub fn finish(&self, extraction: Value) -> Result` | `extraction` with the missing inputs recorded during the run, as its `missingInputs`, and, when the extractor checked its subject's anchors (`Context::subject_exists`) and doesn't report `presence` itself, its `presence`: `absent` when none exists, else `present`. Fails when none exists but the extractor returned items: an absent subject has none. `crate::serve` applies it to what an extractor returns. | | `generations` | `pub fn generations(&self) -> Generations` | The generation store's snapshot the runner handed this run (`request.generations.file`), or an empty one: the first run, `--regenerate`, or an unreadable file. Reuse a value for an equal basis with `crate::Generations::generate`. | | `granted` | `pub fn granted(&self) -> Result>` | The names the definition grants through `execution.environment`. | | `helper` | `pub fn helper(&self, installed: &str, source: PathBuf) -> Result` | Locates a helper file or directory: `installed` relative to the helper directory, or `source`, its location in a source checkout. | @@ -522,6 +522,8 @@ same whoever starts it. | `root` | `pub fn root(&self) -> &Path` | The project's directory in the examined revision, canonicalized: in a temporary materialization, a workspace or the user's checkout read in place. It is the revision's root unless the definition belongs to a nested project (`repository.project`). | | `run` | `pub fn run(&self, cwd: &Path, argv: &[String], stdin: Option<&str>, environment: &BTreeMap) -> Result` | Runs a tool without a shell and records its stderr as a diagnostic. | | `scope` | `pub fn scope(&self) -> Option<&[String]>` | The declared scope, when the runner enforces one: repository-relative files and directories. Files outside it aren't listed and can't be read. | +| `subject_exists` | `pub fn subject_exists(&self, relative: &str) -> Result` | Whether `relative`, an anchor of what the projection describes (its subject: a workflow, a manifest, a schema file), exists at the examined revision. One that doesn't is recorded as a missing input, as `Context::input_exists` records it; when every anchor checked is missing, `Context::finish` marks the extraction absent, and present when any exists. Check auxiliary inputs, whose absence leaves the subject in place, with `Context::input_exists`. | +| `subject_matches` | `pub fn subject_matches(&self, pattern: &str, files: &[String]) -> Result` | `Context::subject_exists` for a glob anchor (in the grammar of `crate::glob`): whether it matches one of `files`, as the extractor lists them. One that matches none is recorded as a missing input. | | `trusted` | `pub fn trusted(&self) -> bool` | Whether the invocation explicitly trusts repository code and ecosystem tools. | | `upstream` | `pub fn upstream(&self, name: &str) -> Option<&Value>` | The extraction of the upstream built-in the definition's `extractor.upstream` names `name`, normalized, of the same revision. | | `with_comparisons` | `pub fn with_comparisons(self, comparisons: impl Fn(&ComparisonRequest<'_>) -> Result + Send + Sync + 'static) -> Self` | Compares extractions with `comparisons`, the runner's comparator sandbox, for `Context::compare`. Without it, `compare` fails. | diff --git a/docs/reference/renderer-kit.md b/docs/reference/renderer-kit.md index 566d33b75..cdb3f4d37 100644 --- a/docs/reference/renderer-kit.md +++ b/docs/reference/renderer-kit.md @@ -1445,7 +1445,7 @@ Linear presence for renderers without staged timing: arrivals fade in, departure ### `Extraction` ```ts -interface Extraction extends Omit<{ vocabularies?: ("dependency-injection/v0" | "infrastructure/v0" | "runtime-policy/v0" | "agentic-workflows/v0" | "scenarios/v0")[]; volatile?: { collection?: "entities" | "relationships"; generated?: true; kinds?: string[]; tolerance?: { absolute?: number; relative?: number; spread?: string; factor?: number; }; basis?: string; path: string; }[]; missingInputs?: string[]; metadata?: Record; protocolVersion: 0; schema: "graph/v0" | "dag/v0" | "treemap/v0" | "metrics/v0" | "api/v0" | "database/v0" | "architecture/v0"; entities: { data?: Record; previousIds?: string[]; evidence?: { location?: { column?: number; line: number; }; kind: string; source: string; }[]; confidence?: "authoritative" | "derived" | "inferred"; id: string; kind: string; label: string; }[]; relationships: { data?: Record; previousIds?: string[]; evidence?: { location?: { column?: number; line: number; }; kind: string; source: string; }[]; confidence?: "authoritative" | "derived" | "inferred"; label?: string; id: string; kind: string; from: string; to: string; }[]; }, "entities" | "relationships"> +interface Extraction extends Omit<{ vocabularies?: ("dependency-injection/v0" | "infrastructure/v0" | "runtime-policy/v0" | "agentic-workflows/v0" | "scenarios/v0")[]; volatile?: { collection?: "entities" | "relationships"; generated?: true; kinds?: string[]; tolerance?: { absolute?: number; relative?: number; spread?: string; factor?: number; }; basis?: string; path: string; }[]; missingInputs?: string[]; presence?: "present" | "absent"; metadata?: Record; protocolVersion: 0; schema: "graph/v0" | "dag/v0" | "treemap/v0" | "metrics/v0" | "api/v0" | "database/v0" | "architecture/v0"; entities: { data?: Record; previousIds?: string[]; evidence?: { location?: { column?: number; line: number; }; kind: string; source: string; }[]; confidence?: "authoritative" | "derived" | "inferred"; id: string; kind: string; label: string; }[]; relationships: { data?: Record; previousIds?: string[]; evidence?: { location?: { column?: number; line: number; }; kind: string; source: string; }[]; confidence?: "authoritative" | "derived" | "inferred"; label?: string; id: string; kind: string; from: string; to: string; }[]; }, "entities" | "relationships"> ``` One aspect of the code at one revision, as an extractor writes it to stdout. @@ -1455,6 +1455,7 @@ One aspect of the code at one revision, as an extractor writes it to stdout. | `entities` | `"entities": Array` | | | `metadata` | `"metadata"?: Record` | | | `missingInputs` | `"missingInputs"?: Array` | | +| `presence` | `"presence"?: "absent" \| "present"` | | | `protocolVersion` | `"protocolVersion": 0` | | | `relationships` | `"relationships": Array` | | | `schema` | `"schema": "api/v0" \| "architecture/v0" \| "dag/v0" \| "database/v0" \| "graph/v0" \| "metrics/v0" \| "treemap/v0"` | | diff --git a/docs/reference/schemas/extraction.md b/docs/reference/schemas/extraction.md index da09f6942..75e9c2b5b 100644 --- a/docs/reference/schemas/extraction.md +++ b/docs/reference/schemas/extraction.md @@ -16,10 +16,13 @@ definitions into [`packages/schemas/schemas/extraction/v0.json`](../../../packag | `relationships` | array of [`relationship`](#relationship) | Yes | At most 50000 items. | | `volatile` | array of [`volatile`](#volatile) | | Data that may vary between runs at the same revision, such as durations or measurements, and how much. Part of the digest. At most 256 items. | | `missingInputs` | array of string | | Declared inputs (repository-relative files, folders or globs) that don't exist at the examined revision. The extraction describes the revision without them, so a comparison shows their contents as added or removed, with a notice. Part of the digest. At most 256 items. Items are unique. | +| `presence` | `"present"` or `"absent"` | | Whether what the projection describes (its subject: a workflow, a manifest, a schema file) exists at the examined revision. `present`: it does, though it may be empty. `absent`: it doesn't (for example a workflow the revision predates), so the extraction has no entities or relationships and `missingInputs` names what is missing. Omitted: not reported, which is unknown, never present; v1 will require it. Part of the digest when written. | | `metadata` | [`data`](#data) | | | No other properties are allowed. +Further rules depend on these values; see the JSON Schema for them. + ## Definitions ### `text` diff --git a/packages/cli/node/extractor.mjs b/packages/cli/node/extractor.mjs index 294732265..0d6110b45 100644 --- a/packages/cli/node/extractor.mjs +++ b/packages/cli/node/extractor.mjs @@ -21,12 +21,87 @@ function described(value) { const made = value.constructor return made === Object || !made ? 'an object' : article(made.name) } +// src/extractor/subject.ts +/** UTF-8 byte order, as the Rust SDK and Python sort paths. */ +function byBytes(a, b) { + return Buffer.compare(Buffer.from(a), Buffer.from(b)) +} +const subject = { + checked: false, + found: false, + missing: /* @__PURE__ */ new Set(), +} +/** + * An anchor as the extraction names it: without a leading `./` or a trailing `/`; `""` for the project itself, which + * only a path anchor (`glob: false`) may name. + */ +function anchorName(anchor, {glob = false} = {}) { + const invalid = () => + /* @__PURE__ */ new TypeError(`An anchor of the subject is a nonempty project-relative path or glob, not ${quoted(anchor)}`) + if (typeof anchor !== 'string' || !anchor.trim()) throw invalid() + if (anchor.startsWith('/') || anchor.split('/').includes('..')) + throw new RangeError(`The anchor ${quoted(anchor)} isn't within the project; name it relative to the project`) + let start = 0 + while (anchor.startsWith('./', start)) start += 2 + let end = anchor.length + while (end > start && anchor[end - 1] === '/') end-- + const name = anchor.slice(start, end) + if (name === '.' || !name) { + if (glob) throw invalid() + return '' + } + return name +} +/** Records that the anchor `name` of the subject exists, or doesn't. */ +function recordAnchor(name, exists) { + subject.checked = true + subject.found ||= exists + if (!exists) subject.missing.add(name) +} +/** `pattern`, in the Rust SDK's glob grammar: `*` within a segment, `**` across them, `**\/` any folders, `?` one character. */ +function globExpression(pattern) { + let source = '^' + for (let index = 0; index < pattern.length; index++) { + const character = pattern.charAt(index) + if (character === '*' && pattern[index + 1] === '*') { + index++ + if (pattern[index + 1] === '/') { + index++ + source += '(?:.*/)?' + } else source += '.*' + } else if (character === '*') source += '[^/]*' + else if (character === '?') source += '[^/]' + else source += character.replace(/[\\^$.*+?()[\]{}|/]/gu, '\\$&') + } + return new RegExp(`${source}$`, 'u') +} +/** + * `document` with what the extractor found of its subject: the anchors it lacks added to `missingInputs`, and, when it + * checked any and `document` doesn't report `presence` itself, `presence`: `absent` when none exists, else `present`. + * Fails when none exists but `document` has items: an absent subject has none. + */ +function withSubject(document) { + if (subject.missing.size) { + const given = document.missingInputs + if (given === void 0 || Array.isArray(given)) + document.missingInputs = [.../* @__PURE__ */ new Set([...(given ?? []), ...subject.missing])].toSorted(byBytes) + } + if (subject.checked && document.presence === void 0) { + const items = [document.entities, document.relationships].some(list => Array.isArray(list) && list.length > 0) + if (!subject.found && items) + throw new Error( + `None of the extractor's subject exists at the revision (${[...subject.missing].toSorted(byBytes).join(', ')}), but its extraction has items; return none when its subject is absent`, + ) + document.presence = subject.found ? 'present' : 'absent' + } + return document +} // src/extractor/result.ts /** The extractor protocol's version, of requests and extractions. */ const PROTOCOL_VERSION = 0 /** The domain schema `result()` writes unless told otherwise: the general one. */ const DEFAULT_SCHEMA = 'graph/v0' -const optionalFields = /* @__PURE__ */ new Set(['metadata', 'missingInputs', 'vocabularies', 'volatile']) +const optionalFields = /* @__PURE__ */ new Set(['metadata', 'missingInputs', 'presence', 'vocabularies', 'volatile']) const requiredFields = { entities: ['kind', 'label'], relationships: ['kind', 'from', 'to'], @@ -70,7 +145,9 @@ function listed$1(items, field) { * The extraction `result()` writes, without writing it: `protocolVersion` and `schema` (default `graph/v0`) filled * in, and entities and relationships, given as lists or keyed by ID, in order of ID. Checks each item's basic shape * (an ID, unique across both; an entity's `kind` and `label`; a relationship's `kind`, `from` and `to`); the runner - * checks the rest. + * checks the rest. When the extractor checked its subject (`request.subjectExists()`, `request.subjectMatches()`), + * the anchors it lacks are added to `missingInputs`, and `presence` is filled in unless given: `absent` when none + * exists, which fails if there are items, else `present`. */ function extraction(fields = {}) { const {schema = DEFAULT_SCHEMA, entities = [], relationships = [], ...optional} = fields @@ -94,7 +171,7 @@ function extraction(fields = {}) { ) if (value !== void 0 && value !== null) document[name] = value } - return document + return withSubject(document) } let written = false /** @@ -152,10 +229,6 @@ function listed(directory) { } }) } -/** UTF-8 byte order, as the Rust SDK and Python sort paths. */ -function byBytes(a, b) { - return Buffer.compare(Buffer.from(a), Buffer.from(b)) -} /** * The extractor request: the protocol's JSON object, with accessors. `request.repository.root` and the rest of the * protocol still work; `JSON.stringify(request)` writes the request as it came. @@ -163,6 +236,7 @@ function byBytes(a, b) { var Request = class { #read #value + #files /** The request `value`; without one, the request on stdin, read the first time it is used. */ constructor(value) { this.#value = value @@ -227,6 +301,42 @@ var Request = class { const files = names.filter(path => path.startsWith(prefix) && inScope(path)).map(path => path.slice(prefix.length)) return [...new Set(files)].toSorted(byBytes) } + /** `files()`, listed once for the subject checks. */ + #listing() { + this.#files ??= this.files() + return this.#files + } + /** + * Whether `path`, an anchor of what the projection describes (its subject: a workflow, a manifest, a schema file), + * is one of the project's `files()` or a folder holding some. One that isn't is recorded as a missing input, and + * `result()` reports the subject's `presence`: `absent` when no anchor checked exists (the extraction must then have + * no items), else `present`. Don't check inputs whose absence leaves the subject in place this way. + */ + subjectExists(path) { + const name = anchorName(path) + const scope = this.repository.scope + const repositoryPath = this.project ? `${this.project}/${name}` : name + if (name && scope && !scope.some(entry => repositoryPath === entry || repositoryPath.startsWith(`${entry}/`))) + throw new RangeError( + `The anchor ${quoted(repositoryPath)} is outside the declared scope (${scope.join(', ')}); declare it in the definition's scope`, + ) + const files = this.#listing() + const exists = !name || files.some(file => file === name || file.startsWith(`${name}/`)) + recordAnchor(name, exists) + return exists + } + /** + * `subjectExists()` for a glob anchor: whether `pattern` (`*` within a folder, `**` across folders, `?` one + * character) matches one of the project's `files()`. One that matches none is recorded as a missing input. + */ + subjectMatches(pattern) { + const name = anchorName(pattern, {glob: true}) + const files = this.#listing() + const expression = globExpression(name) + const matches = files.some(file => expression.test(file)) + recordAnchor(name, matches) + return matches + } /** The project's directory where its dependencies (`node_modules`, a virtualenv) are installed, if anywhere. */ get checkout() { const checkout = this.repository.checkout diff --git a/packages/cli/python/projections/__init__.py b/packages/cli/python/projections/__init__.py index 2e5d6898a..05024e8cb 100644 --- a/packages/cli/python/projections/__init__.py +++ b/packages/cli/python/projections/__init__.py @@ -22,6 +22,7 @@ import json import os +import re import subprocess import sys from collections.abc import Iterable, Mapping @@ -34,7 +35,7 @@ DEFAULT_SCHEMA = "graph/v0" # An extraction's optional fields, besides its entities and relationships. -_OPTIONAL = ("metadata", "missingInputs", "vocabularies", "volatile") +_OPTIONAL = ("metadata", "missingInputs", "presence", "vocabularies", "volatile") _PYTHONIC = {"missing_inputs": "missingInputs"} _REQUIRED = { "entities": (("kind", "label"), "entity"), @@ -92,6 +93,42 @@ def in_scope(path): files = {path[len(prefix) :] for path in names if path.startswith(prefix) and in_scope(path)} return sorted(files, key=lambda name: name.encode("utf-8", "surrogateescape")) + def subject_exists(self, path): + """Whether `path`, an anchor of what the projection describes (its subject: a workflow, a manifest, a schema + file), is one of the project's `files()` or a folder holding some. + + One that isn't is recorded as a missing input, and `result()` reports the subject's `presence`: `absent` when no + anchor checked exists (the extraction must then have no items), else `present`. Don't check inputs whose + absence leaves the subject in place this way. + """ + name = _anchor_name(path) + # As the Rust SDK does, an anchor outside a declared scope is an error, not absence: the revision's files there aren't listed. + scope = self.repository.get("scope") + repository_path = f"{self.project}/{name}" if self.project else name + if name and scope is not None and not any(repository_path == entry or repository_path.startswith(entry + "/") for entry in scope): + raise ValueError( + f"The anchor {_quoted(repository_path)} is outside the declared scope ({', '.join(scope)}); " + "declare it in the definition's scope" + ) + files = self._listing() + exists = not name or any(file == name or file.startswith(name + "/") for file in files) + _anchor(name, exists) + return exists + + def subject_matches(self, pattern): + """`subject_exists()` for a glob anchor: whether `pattern` (`*` within a folder, `**` across folders, `?` one + character) matches one of the project's `files()`. One that matches none is recorded as a missing input.""" + name = _anchor_name(pattern, glob=True) + expression = _glob(name) + matches = any(expression.match(file) for file in self._listing()) + _anchor(name, matches) + return matches + + def _listing(self): + if not hasattr(self, "_files"): + self._files = self.files() + return self._files + @property def checkout(self): """The project's directory where its dependencies (a virtualenv, node_modules) are installed, or None.""" @@ -155,6 +192,78 @@ def _listed(directory): ] +# What the extractor found of its subject: `subject_exists()` and `subject_matches()` record each anchor they check, +# and `extraction()` reports it as `presence` and `missingInputs`, as the JavaScript helpers and the Rust SDK do. +_subject = {"checked": False, "found": False, "missing": set()} + + +def _anchor_name(anchor, glob=False): + # Without a leading `./` or a trailing `/`; "" for the project itself, which only a path anchor may name. + invalid = f"An anchor of the subject is a nonempty project-relative path or glob, not {_quoted(anchor)}" + if not isinstance(anchor, str) or not anchor.strip(): + raise TypeError(invalid) + if anchor.startswith("/") or ".." in anchor.split("/"): + raise ValueError(f"The anchor {_quoted(anchor)} isn't within the project; name it relative to the project") + name = anchor + while name.startswith("./"): + name = name[2:] + name = name.rstrip("/") + if name in ("", "."): + if glob: + raise TypeError(invalid) + return "" + return name + + +def _anchor(name, exists): + _subject["checked"] = True + _subject["found"] = _subject["found"] or exists + if not exists: + _subject["missing"].add(name) + + +def _glob(pattern): + # The Rust SDK's glob grammar: `*` within a segment, `**` across them, `**/` any folders, `?` one character. + source, index = "^", 0 + while index < len(pattern): + character = pattern[index] + if character == "*" and pattern[index + 1 : index + 2] == "*": + index += 1 + if pattern[index + 1 : index + 2] == "/": + index += 1 + source += "(?:.*/)?" + else: + source += ".*" + elif character == "*": + source += "[^/]*" + elif character == "?": + source += "[^/]" + else: + source += re.escape(character) + index += 1 + return re.compile(source + r"\Z") + + +def _by_bytes(name): + return name.encode("utf-8", "surrogateescape") + + +def _with_subject(document): + if _subject["missing"]: + given = document.get("missingInputs") + if given is None or isinstance(given, list): + document["missingInputs"] = sorted(set(given or []) | _subject["missing"], key=_by_bytes) + if _subject["checked"] and "presence" not in document: + if not _subject["found"] and (document["entities"] or document["relationships"]): + missing = ", ".join(sorted(_subject["missing"], key=_by_bytes)) + raise ValueError( + f"None of the extractor's subject exists at the revision ({missing}), " + "but its extraction has items; return none when its subject is absent" + ) + document["presence"] = "present" if _subject["found"] else "absent" + return document + + def _within(directory, project): return os.path.join(directory, *project.split("/")) if project else directory @@ -268,7 +377,11 @@ def extraction(entities=(), relationships=(), *, schema=None, **fields): them keyed by ID. Every entity needs `kind` and `label`; every relationship `kind`, `from` and `to`. `schema` is the domain schema (default `graph/v0`). `fields` adds the extraction's optional `metadata`, `volatile`, - `vocabularies` and `missingInputs` (or `missing_inputs`). + `vocabularies`, `presence` and `missingInputs` (or `missing_inputs`). + When the extractor checked its subject (`request.subject_exists()`, + `request.subject_matches()`), the anchors it lacks are added to + `missingInputs`, and `presence` is filled in unless given: `absent` when + none exists, which fails if there are items, else `present`. """ schema = DEFAULT_SCHEMA if schema is None else schema if not isinstance(schema, str) or "/" not in schema: @@ -293,7 +406,7 @@ def extraction(entities=(), relationships=(), *, schema=None, **fields): ) if value is not None: document[name] = value - return document + return _with_subject(document) _written = False diff --git a/packages/cli/templates/SKILL.md b/packages/cli/templates/SKILL.md index 44220f96e..f18171995 100644 --- a/packages/cli/templates/SKILL.md +++ b/packages/cli/templates/SKILL.md @@ -463,7 +463,8 @@ in the examined revision, `request.checkout` where its dependencies are, files in the revision, project-relative), and `result(entities=..., relationships=...)` writes the extraction, items as lists with an `id` or as dicts keyed by ID, sorted, `graph/v0` unless -`schema="..."`, with optional `metadata`, `volatile` and `missing_inputs`: +`schema="..."`, with optional `metadata`, `volatile`, `presence` and +`missing_inputs`: ```python from projections import request, result @@ -487,7 +488,17 @@ import {request, result} from '@githubnext/projections-sdk/extractor' result({entities: {'service:payments': {kind: 'service', label: 'Payments'}}}) ``` -In other languages, write the JSON above. +When what the projection describes may not exist at a revision (a workflow, +a manifest the revision predates), check it before reading it: +`request.subject_exists("flags.yaml")` in Python, +`request.subjectExists('flags.json')` in JavaScript, or `subject_matches` / +`subjectMatches` for a glob. If none of the anchors you checked exists, return +no items. `result()` then writes `presence: "absent"` with the path in +`missingInputs`, and hosts show the subject as added or removed rather than +empty. Don't fail, and don't return a bare empty extraction. + +In other languages, write the JSON above, with `"presence": "absent"` and the +missing path in `missingInputs` when the subject doesn't exist. {{schemas}} diff --git a/packages/cli/test/extractor-helpers.test.mjs b/packages/cli/test/extractor-helpers.test.mjs index e4e4128ce..8cd110dd4 100644 --- a/packages/cli/test/extractor-helpers.test.mjs +++ b/packages/cli/test/extractor-helpers.test.mjs @@ -30,8 +30,29 @@ const helpers = { ], } +/** A case's `files`, written to a fresh directory that becomes its request's `repository.root`. */ +function revision(testCase) { + if (!testCase.files) return testCase + const root = mkdtempSync(join(tmpdir(), 'projections-subject-')) + for (const name of testCase.files) { + mkdirSync(join(root, name, '..'), {recursive: true}) + writeFileSync(join(root, name), '') + } + const stdin = {...testCase.stdin, repository: {...testCase.stdin.repository, root}} + return {...testCase, stdin, root} +} + /** What a helper did with a case: `{value}`, its output, or `{error}`, its message. */ -function run(helper, testCase) { +function run(helper, given) { + const testCase = revision(given) + try { + return attempt(helper, testCase) + } finally { + if (testCase.root) rmSync(testCase.root, {recursive: true, force: true}) + } +} + +function attempt(helper, testCase) { const [program, argv, variables] = helpers[helper](JSON.stringify(testCase)) const input = testCase.stdinText ?? JSON.stringify(testCase.stdin) const outcome = spawnSync(program, argv, {input, encoding: 'utf8', env: {...environment, ...variables}}) diff --git a/packages/cli/test/extractor-helpers/driver.mjs b/packages/cli/test/extractor-helpers/driver.mjs index 6173651cf..5b4e61e0e 100644 --- a/packages/cli/test/extractor-helpers/driver.mjs +++ b/packages/cli/test/extractor-helpers/driver.mjs @@ -1,6 +1,6 @@ // Runs one case of packages/schemas/fixtures/extractor-helpers.json (its JSON is the argument) through // `@githubnext/projections-sdk/extractor`, as an extractor imports it: the accessors' values, what the methods named in -// `calls` return, or the extraction on stdout, or +// `calls` return, what the `checks` return, or the extraction on stdout (after the `checks`), or // `error: ` on stderr. extractor-helpers.test.mjs runs it with the runner's preload. import {request, result} from '@githubnext/projections-sdk/extractor' @@ -10,7 +10,11 @@ try { process.stdout.write(JSON.stringify(Object.fromEntries(testCase.accessors.map(name => [name, request[name] ?? null])))) } else if (testCase.calls) { process.stdout.write(JSON.stringify(Object.fromEntries(testCase.calls.map(name => [name, request[name]()])))) - } else result(testCase.result) + } else { + const checked = (testCase.checks ?? []).map(([name, argument]) => request[name](argument)) + if (testCase.result) result(testCase.result) + else process.stdout.write(JSON.stringify(checked)) + } } catch (error) { process.stderr.write(`error: ${error.message}\n`) process.exitCode = 1 diff --git a/packages/cli/test/extractor-helpers/driver.py b/packages/cli/test/extractor-helpers/driver.py index 6a39a7dfc..9bef00ff0 100644 --- a/packages/cli/test/extractor-helpers/driver.py +++ b/packages/cli/test/extractor-helpers/driver.py @@ -1,6 +1,6 @@ # Runs one case of packages/schemas/fixtures/extractor-helpers.json (its JSON is the argument) through the # `projections` Python module, as an extractor imports it: the accessors' values, what the methods named in `calls` -# return, or the extraction on stdout, or +# return, what the `checks` return, or the extraction on stdout (after the `checks`), or # `error: ` on stderr. extractor-helpers.test.mjs runs it with the module on PYTHONPATH. import json import re @@ -17,7 +17,14 @@ values = {name: getattr(projections.request, re.sub("([A-Z])", r"_\1", name).lower())() for name in case["calls"]} sys.stdout.write(json.dumps(values, ensure_ascii=False)) else: - projections.result(**case["result"]) + checked = [ + getattr(projections.request, re.sub("([A-Z])", r"_\1", name).lower())(argument) + for name, argument in case.get("checks", []) + ] + if "result" in case: + projections.result(**case["result"]) + else: + sys.stdout.write(json.dumps(checked, ensure_ascii=False)) except Exception as error: sys.stderr.write(f"error: {error}\n") sys.exit(1) diff --git a/packages/engine/js/scripts/browser-test.mjs b/packages/engine/js/scripts/browser-test.mjs index 20d7f2b97..dc6a6a3b0 100644 --- a/packages/engine/js/scripts/browser-test.mjs +++ b/packages/engine/js/scripts/browser-test.mjs @@ -18,7 +18,7 @@ for (const browserName of ['chromium', 'webkit']) { ? [json] : operation === 'validate-comparison' ? [before, after, comparison] - : operation === 'vary' || operation === 'pair' + : operation === 'vary' || operation === 'pair' || operation === 'presence' ? [before, after] : operation === 'review' ? [comparison] diff --git a/packages/engine/js/src/engine.ts b/packages/engine/js/src/engine.ts index c0931c11e..6be2bd081 100644 --- a/packages/engine/js/src/engine.ts +++ b/packages/engine/js/src/engine.ts @@ -10,6 +10,8 @@ import type { Extraction, Json, PairingSide, + PresenceChange, + PresenceSide, ProjectionEngine, Variation, } from '@githubnext/projections-schemas' @@ -27,6 +29,16 @@ function pairingSide(document: PairingSide): unknown { } } +/** Only what presence reads: an extraction's presence, missing inputs and at most one item of each collection. */ +function presenceSide(extraction: PresenceSide): unknown { + if (typeof extraction !== 'object' || (extraction as unknown) === null) return extraction + const {presence, missingInputs, entities, relationships} = extraction + // Presence reads only whether a collection has an item; one that isn't an array goes as it is, for the engine to report. + const first = (items: unknown) => (Array.isArray(items) ? items.slice(0, 1) : items) + const side = {presence, missingInputs, entities: first(entities), relationships: first(relationships)} + return Object.fromEntries(Object.entries(side).filter(([, field]) => field !== undefined)) +} + /** * Builds the `ProjectionEngine` API over one transport, which every factory (`createNativeEngine`, `createWasmEngine`, * `createWorkerEngine`) wraps. Each operation sends one `version: 0` request to `invoke`; a response with `ok: false` @@ -76,6 +88,8 @@ export function engine( const changes = (comparison as Partial | undefined)?.changes return result({version: 0, operation: 'review', comparison: changes === undefined ? {} : {changes}}) }, + presence: (before, after) => + result({version: 0, operation: 'presence', before: presenceSide(before), after: presenceSide(after)}), pair: (before, after) => result({version: 0, operation: 'pair', before: pairingSide(before), after: pairingSide(after)}), async compare(before, after, options: DefaultComparatorOptions = {}) { diff --git a/packages/engine/js/test/engine.test.mjs b/packages/engine/js/test/engine.test.mjs index c09971fa0..4c65cf6d1 100644 --- a/packages/engine/js/test/engine.test.mjs +++ b/packages/engine/js/test/engine.test.mjs @@ -24,7 +24,7 @@ const argumentsOf = ({operation, extraction, before, after, comparison, json}) = ? [json] : operation === 'validate-comparison' ? [before, after, comparison] - : operation === 'vary' || operation === 'pair' + : operation === 'vary' || operation === 'pair' || operation === 'presence' ? [before, after] : operation === 'review' ? [comparison] diff --git a/packages/engine/src/lib.rs b/packages/engine/src/lib.rs index f0685f124..4f4b7c364 100644 --- a/packages/engine/src/lib.rs +++ b/packages/engine/src/lib.rs @@ -8,6 +8,7 @@ mod data_rules; pub mod model; pub mod pairing; mod parse; +pub mod presence; pub mod review; mod validate; pub mod volatility; @@ -26,6 +27,7 @@ pub use parse::{ canonical, canonicalize, check_comparison, content, content_value, diagnostic_response, handle, normalize, parse_json, semantic, validate_comparison, }; +pub use presence::{Presence, PresenceChange, SidePresence, Transition, presence_change}; /// The Engine's formally verified decisions (see `VERIFICATION.md`). pub use projections_engine_verified as verified; pub use review::{Review, review}; diff --git a/packages/engine/src/model/extraction.rs b/packages/engine/src/model/extraction.rs index 38075b2d3..b37f68615 100644 --- a/packages/engine/src/model/extraction.rs +++ b/packages/engine/src/model/extraction.rs @@ -1,4 +1,5 @@ use super::{Collection, Fields, Number}; +use crate::presence::{Presence, Side}; use crate::volatility::Declaration; /// How sure an extractor is of an item. @@ -126,6 +127,8 @@ pub struct Extraction { pub(crate) schema: &'static str, pub(crate) vocabularies: Vec<&'static str>, pub(crate) missing_inputs: Vec, + /// Whether its subject exists, as written; `None` when it isn't reported. + pub(crate) presence: Option, pub(crate) volatile: Vec, pub(crate) entities: Vec, pub(crate) relationships: Vec, @@ -142,6 +145,22 @@ impl Extraction { &self.vocabularies } + /// Its `presence`, as written; `None` when it doesn't report it. + pub fn presence(&self) -> Option { + self.presence + } + + /// The declared inputs it lacks, in canonical order. + pub fn missing_inputs(&self) -> &[String] { + &self.missing_inputs + } + + /// Its subject's presence, reported or inferred ([`crate::presence::side`]). + pub fn subject(&self) -> Side { + let items = !self.entities.is_empty() || !self.relationships.is_empty(); + crate::presence::side(self.presence, !self.missing_inputs.is_empty(), items) + } + /// The volatile declarations, normalized and sorted. pub fn volatile(&self) -> &[Declaration] { &self.volatile diff --git a/packages/engine/src/parse/encode.rs b/packages/engine/src/parse/encode.rs index 37dbc0a2f..2f4fd8aec 100644 --- a/packages/engine/src/parse/encode.rs +++ b/packages/engine/src/parse/encode.rs @@ -149,6 +149,7 @@ entries!(Extraction, |this| [ ("schema", Some(Field::Text(this.schema))), ("vocabularies", nonempty(&this.vocabularies).map(Field::Names)), ("missingInputs", nonempty(&this.missing_inputs).map(Field::Texts)), + ("presence", this.presence.map(|presence| Field::Text(presence.name()))), ("metadata", this.metadata.as_ref().map(Field::Fields)), ("volatile", nonempty(&this.volatile).map(Field::Declarations)), ("entities", Some(Field::Entities(&this.entities))), diff --git a/packages/engine/src/parse/extraction.rs b/packages/engine/src/parse/extraction.rs index e5eb42674..885bd9932 100644 --- a/packages/engine/src/parse/extraction.rs +++ b/packages/engine/src/parse/extraction.rs @@ -7,6 +7,7 @@ use super::volatile::declarations; use crate::canonical::{canonical_order, word}; use crate::data_rules::VOCABULARIES; use crate::model::{Extraction, Number}; +use crate::presence; use crate::validate::{MAX_ENTITIES, MAX_EXTRACTION_BYTES, MAX_RELATIONSHIPS, SCHEMAS, check_identities, sort_items, validate_domain}; use crate::volatility::check_bases; use crate::{Failure, fail, pointer}; @@ -30,6 +31,7 @@ pub(crate) fn read(value: &Value, path: &str) -> Result { "relationships", "volatile", "missingInputs", + "presence", "metadata", ], path, @@ -50,6 +52,7 @@ pub(crate) fn read(value: &Value, path: &str) -> Result { schema, vocabularies, missing_inputs: optional(value, "missingInputs", path, missing_inputs)?.unwrap_or_default(), + presence: optional(value, "presence", path, presence::read)?, volatile: optional(value, "volatile", path, declarations)?.unwrap_or_default(), entities: Vec::new(), relationships: Vec::new(), @@ -58,6 +61,8 @@ pub(crate) fn read(value: &Value, path: &str) -> Result { let mut ids = HashSet::new(); extraction.entities = collection(value, path, "entities", MAX_ENTITIES, &mut ids, entity)?; extraction.relationships = collection(value, path, "relationships", MAX_RELATIONSHIPS, &mut ids, relationship)?; + let items = !extraction.entities.is_empty() || !extraction.relationships.is_empty(); + presence::check(extraction.presence, !extraction.missing_inputs.is_empty(), items, path)?; check_identities(&extraction, path)?; extraction.metadata = optional(value, "metadata", path, |metadata, path| data_fields(object(metadata, path)?, path))?; validate_domain(&extraction, path)?; diff --git a/packages/engine/src/parse/request.rs b/packages/engine/src/parse/request.rs index 9baf7a43d..f5451efbc 100644 --- a/packages/engine/src/parse/request.rs +++ b/packages/engine/src/parse/request.rs @@ -55,6 +55,10 @@ fn execute(request: &Value) -> Result { fields(request, &["version", "operation", "comparison"], "")?; crate::review(&request["comparison"]).map(|review| review.to_json()) } + "presence" => { + fields(request, &["version", "operation", "before", "after"], "")?; + crate::presence::presence_change(&request["before"], &request["after"]).map(|change| change.to_json()) + } "vary" => { fields(request, &["version", "operation", "before", "after"], "")?; vary(&request["before"], &request["after"]).map(|variation| variation.to_json()) diff --git a/packages/engine/src/presence.rs b/packages/engine/src/presence.rs new file mode 100644 index 000000000..2a8f8874a --- /dev/null +++ b/packages/engine/src/presence.rs @@ -0,0 +1,198 @@ +//! Whether what a projection describes (its subject: a workflow, a manifest, +//! a schema file) exists at a revision, and what that makes of a pair of +//! extractions. An extraction reports it in `presence`: `present` or +//! `absent`. Omitted, it isn't reported, which is unknown, never present: an +//! omitted side is inferred absent when it names missing inputs and has no +//! items (the legacy reading, which v1 removes by requiring `presence`) and +//! inferred present when it has items, which an absent extraction can't. The +//! CLI, hosts and the kit read the pair's state from here (the `presence` +//! operation, `engine.presence`); `@githubnext/projections-schemas` mirrors it +//! for synchronous callers, and the shared conformance corpus holds both to it. + +use crate::parse::{choice, object}; +use crate::{Failure, fail, pointer}; +use serde_json::{Value, json}; + +/// What an extraction reports of its subject. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Presence { + /// It exists at the revision, though it may be empty. + Present, + /// It doesn't: the extraction has no items and names what is missing. + Absent, +} + +impl Presence { + pub const ALL: [Presence; 2] = [Presence::Present, Presence::Absent]; + + pub fn name(self) -> &'static str { + match self { + Presence::Present => "present", + Presence::Absent => "absent", + } + } +} + +/// What is known of one side's subject: reported or inferred, else unknown. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SidePresence { + Present, + Absent, + Unknown, +} + +impl SidePresence { + pub fn name(self) -> &'static str { + match self { + SidePresence::Present => "present", + SidePresence::Absent => "absent", + SidePresence::Unknown => "unknown", + } + } +} + +/// What a pair's subject did between before and after. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Transition { + /// Absent before, present after: the change adds it. + Added, + /// Present before, absent after: the change removes it. + Removed, + /// Absent on both sides: there is nothing of it to compare. + Absent, + /// Present on both sides. + Present, + /// A side's presence is unknown. + Unknown, +} + +impl Transition { + pub fn name(self) -> &'static str { + match self { + Transition::Added => "added", + Transition::Removed => "removed", + Transition::Absent => "absent", + Transition::Present => "present", + Transition::Unknown => "unknown", + } + } +} + +/// One side's presence and whether it was inferred rather than reported. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Side { + pub presence: SidePresence, + pub inferred: bool, +} + +impl Side { + pub fn to_json(&self) -> Value { + json!({"presence": self.presence.name(), "inferred": self.inferred}) + } +} + +/// The presence of a pair's subject on each side and what the change did to it. +/// `inferred` is true when either side's presence was inferred. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PresenceChange { + pub before: SidePresence, + pub after: SidePresence, + pub change: Transition, + pub inferred: bool, +} + +impl PresenceChange { + pub fn to_json(&self) -> Value { + json!({"before": self.before.name(), "after": self.after.name(), "change": self.change.name(), + "inferred": self.inferred}) + } +} + +/// One side's presence from what it reports (`reported`), whether it names +/// missing inputs and whether it has items. +pub fn side(reported: Option, missing_inputs: bool, items: bool) -> Side { + let (presence, inferred) = match reported { + Some(Presence::Present) => (SidePresence::Present, false), + Some(Presence::Absent) => (SidePresence::Absent, false), + None if items => (SidePresence::Present, true), + None if missing_inputs => (SidePresence::Absent, true), + None => (SidePresence::Unknown, false), + }; + Side { presence, inferred } +} + +/// What the change did to the subject, from each side's presence. +pub fn change(before: Side, after: Side) -> PresenceChange { + use SidePresence::{Absent, Present, Unknown}; + let change = match (before.presence, after.presence) { + (Absent, Present) => Transition::Added, + (Present, Absent) => Transition::Removed, + (Absent, Absent) => Transition::Absent, + (Present, Present) => Transition::Present, + (Unknown, _) | (_, Unknown) => Transition::Unknown, + }; + PresenceChange { + before: before.presence, + after: after.presence, + change, + inferred: before.inferred || after.inferred, + } +} + +/// An extraction's `presence`: `present` or `absent`. +pub(crate) fn read(value: &Value, path: &str) -> Result { + choice(value, &Presence::ALL, Presence::name, path, "Expected present or absent") + .map_err(|_| fail("invalid-presence", path, "Expected present or absent")) +} + +/// Fails when an extraction reports its subject absent but has items, or names +/// nothing missing: absence is always of something nameable. `path` is the +/// extraction's. +pub(crate) fn check(presence: Option, missing_inputs: bool, items: bool, path: &str) -> Result<(), Failure> { + if presence != Some(Presence::Absent) { + return Ok(()); + } + let at = pointer(path, "presence"); + if items { + return Err(fail( + "absent-with-items", + &at, + "An absent extraction has no entities or relationships", + )); + } + if !missing_inputs { + return Err(fail( + "absent-without-missing-input", + &at, + "An absent extraction names what is missing in missingInputs", + )); + } + Ok(()) +} + +/// One side as `presence_change` reads it: only its `presence`, `missingInputs`, +/// `entities` and `relationships`, each optional, at `path`. +pub fn read_side(value: &Value, path: &str) -> Result { + object(value, path)?; + let reported = match value.get("presence") { + None => None, + Some(field) => Some(read(field, &pointer(path, "presence"))?), + }; + let nonempty = |key: &str| match value.get(key) { + None => Ok(false), + Some(Value::Array(items)) => Ok(!items.is_empty()), + Some(_) => Err(fail("invalid-type", &pointer(path, key), "Expected an array")), + }; + let missing_inputs = nonempty("missingInputs")?; + let (entities, relationships) = (nonempty("entities")?, nonempty("relationships")?); + let items = entities || relationships; + check(reported, missing_inputs, items, path)?; + Ok(side(reported, missing_inputs, items)) +} + +/// The presence of a pair's subject: each side's, and what the change did to +/// it. It reads only what [`read_side`] does of each extraction, so a host can +/// send them trimmed. +pub fn presence_change(before: &Value, after: &Value) -> Result { + Ok(change(read_side(before, "/before")?, read_side(after, "/after")?)) +} diff --git a/packages/engine/src/volatility/rerun.rs b/packages/engine/src/volatility/rerun.rs index 70ba94572..5abaac795 100644 --- a/packages/engine/src/volatility/rerun.rs +++ b/packages/engine/src/volatility/rerun.rs @@ -78,13 +78,14 @@ pub fn rerun(before: &Extraction, after: &Extraction, equal: bool) -> Variation } /// The top-level differences between two runs: schema, vocabularies, -/// declarations and missing inputs. +/// declarations, missing inputs and presence. fn top_level(before: &Extraction, after: &Extraction) -> Vec { [ ("schema", before.schema != after.schema), ("vocabularies", before.vocabularies != after.vocabularies), ("volatile", before.volatile != after.volatile), ("missingInputs", before.missing_inputs != after.missing_inputs), + ("presence", before.presence != after.presence), ] .into_iter() .filter(|(_, differs)| *differs) diff --git a/packages/engine/tests/validation.rs b/packages/engine/tests/validation.rs index 6a731362f..317832d48 100644 --- a/packages/engine/tests/validation.rs +++ b/packages/engine/tests/validation.rs @@ -101,6 +101,87 @@ fn normalization_sorts_items_and_identity_claims_and_defaults_data() { assert_eq!(accepts(&with("data", json!({"k": 1})))["entities"][0]["data"], json!({"k": 1})); } +#[test] +fn presence_is_kept_as_written_and_absent_is_checked() { + let canonical = |value: &Value| projections_engine::canonicalize(&accepts(value)).unwrap(); + // Unreported, an extraction's canonical bytes (and so its digest) are as before presence existed. + let mut unreported = graph(json!([]), json!([])); + unreported["missingInputs"] = json!(["a.yml"]); + assert_eq!( + canonical(&unreported).0, + r#"{"entities":[],"missingInputs":["a.yml"],"protocolVersion":0,"relationships":[],"schema":"graph/v0"}"# + ); + // Written, either value is kept, and each is a different digest from unreported. + let mut present = graph(json!([node("a")]), json!([])); + present["presence"] = json!("present"); + assert_eq!(accepts(&present)["presence"], "present"); + let mut empty = graph(json!([]), json!([])); + empty["presence"] = json!("present"); + let mut absent = unreported.clone(); + absent["presence"] = json!("absent"); + assert_eq!(accepts(&absent)["presence"], "absent"); + let digests = [&unreported, &empty, &absent].map(|value| canonical(value).1); + assert!(digests[0] != digests[1] && digests[1] != digests[2] && digests[0] != digests[2]); + // Only present or absent. + for value in [json!("missing"), json!(""), json!(null), json!(true)] { + let mut invalid = graph(json!([]), json!([])); + invalid["presence"] = value; + rejects(&invalid, "invalid-presence", "/x/presence"); + } + // An absent extraction has no items and names what is missing. + let mut with_entity = absent.clone(); + with_entity["entities"] = json!([node("a")]); + rejects(&with_entity, "absent-with-items", "/x/presence"); + let mut with_relationship = absent.clone(); + with_relationship["entities"] = json!([node("a"), node("b")]); + with_relationship["relationships"] = json!([edge("e", "a", "b")]); + rejects(&with_relationship, "absent-with-items", "/x/presence"); + let mut nothing_missing = graph(json!([]), json!([])); + nothing_missing["presence"] = json!("absent"); + rejects(¬hing_missing, "absent-without-missing-input", "/x/presence"); + nothing_missing["missingInputs"] = json!([]); + rejects(¬hing_missing, "absent-without-missing-input", "/x/presence"); +} + +#[test] +fn an_extraction_reads_its_subject_reported_or_inferred() { + use projections_engine::{Extraction, Presence}; + let read = |value: &Value| Extraction::from_json(value, "").unwrap(); + let mut missing = graph(json!([]), json!([])); + missing["missingInputs"] = json!(["b.yml", "a.yml"]); + let extraction = read(&missing); + assert_eq!(extraction.missing_inputs(), ["a.yml", "b.yml"]); + assert_eq!(extraction.presence(), None); + // Unreported: absent when it has no items and names missing inputs, present with items, else unknown. + assert_eq!(extraction.subject().to_json(), json!({"presence": "absent", "inferred": true})); + assert_eq!( + read(&graph(json!([node("a")]), json!([]))).subject().to_json(), + json!({"presence": "present", "inferred": true}) + ); + let mut items_and_missing = graph(json!([node("a"), node("b")]), json!([edge("e", "a", "b")])); + items_and_missing["missingInputs"] = json!(["a.yml"]); + assert_eq!( + read(&items_and_missing).subject().to_json(), + json!({"presence": "present", "inferred": true}) + ); + assert_eq!( + read(&graph(json!([]), json!([]))).subject().to_json(), + json!({"presence": "unknown", "inferred": false}) + ); + // Reported, it's taken as written. + let mut absent = missing.clone(); + absent["presence"] = json!("absent"); + assert_eq!(read(&absent).presence(), Some(Presence::Absent)); + assert_eq!(read(&absent).subject().to_json(), json!({"presence": "absent", "inferred": false})); + let mut present = missing; + present["presence"] = json!("present"); + assert_eq!(read(&present).presence(), Some(Presence::Present)); + assert_eq!( + read(&present).subject().to_json(), + json!({"presence": "present", "inferred": false}) + ); +} + #[test] fn missing_inputs_are_distinct_paths_sorted_and_part_of_the_digest() { let mut value = graph(json!([]), json!([])); diff --git a/packages/engine/tests/volatility.rs b/packages/engine/tests/volatility.rs index 2137b8a0b..4bd8837a8 100644 --- a/packages/engine/tests/volatility.rs +++ b/packages/engine/tests/volatility.rs @@ -726,6 +726,14 @@ fn reruns_are_reproducible_when_nothing_varies_beyond_tolerance() { let mut other = first.clone(); other["schema"] = json!("dag/v0"); assert_eq!(vary(&first, &other).unwrap().beyond[0].path, "/schema"); + // So is presence: an extractor that reports its subject differently between runs isn't deterministic. + let mut absent = json!({"protocolVersion": 0, "schema": "graph/v0", "entities": [], "relationships": [], "missingInputs": ["a.yml"]}); + let unreported = absent.clone(); + absent["presence"] = json!("absent"); + assert_eq!( + vary(&unreported, &absent).unwrap().to_json()["beyond"], + json!([{"path": "/presence", "reason": "The runs' presence differ"}]) + ); // Inputs are validated. let failure = vary(&json!({}), &first).unwrap_err(); assert_eq!(failure[0].path, "/before/protocolVersion"); diff --git a/packages/extractors/go-public-api/src/lib.rs b/packages/extractors/go-public-api/src/lib.rs index 243fe12c9..535580811 100644 --- a/packages/extractors/go-public-api/src/lib.rs +++ b/packages/extractors/go-public-api/src/lib.rs @@ -146,7 +146,7 @@ mod tests { stderr: String::new(), }) }); - let result = collect(&cx).map(|extraction| cx.finish(extraction)); + let result = collect(&cx).and_then(|extraction| cx.finish(extraction)); let directory = directory.lock().unwrap().clone(); (result, directory) } diff --git a/packages/extractors/prisma-schema/tests/prisma.rs b/packages/extractors/prisma-schema/tests/prisma.rs index 112e2446c..0500c18ec 100644 --- a/packages/extractors/prisma-schema/tests/prisma.rs +++ b/packages/extractors/prisma-schema/tests/prisma.rs @@ -400,24 +400,24 @@ fn a_schema_the_revision_lacks_extracts_as_empty_and_is_recorded_as_missing() { }; // Missing whole: an empty schema that names the missing file. let cx = context(json!({"schema":"packages/api/prisma/schema.prisma"})); - let absent = cx.finish(collect(&cx).unwrap()); + let absent = cx.finish(collect(&cx).unwrap()).unwrap(); assert_eq!(absent["entities"], json!([])); assert_eq!(absent["relationships"], json!([])); assert_eq!(absent["missingInputs"], json!(["packages/api/prisma/schema.prisma"])); assert!(projections_engine::normalize(&absent, "").is_ok()); // Missing in part: the rest is extracted. let cx = context(json!({"schemas":["schema.prisma", "packages/api/prisma/"]})); - let partial = cx.finish(collect(&cx).unwrap()); + let partial = cx.finish(collect(&cx).unwrap()).unwrap(); assert_eq!(semantic(&partial), semantic(&extracted(&["schema.prisma"]))); assert_eq!(partial["missingInputs"], json!(["packages/api/prisma"])); // A missing snapshot is an empty schema too. let cx = context(json!({"snapshot":"schema.json"})); - let snapshot = cx.finish(collect(&cx).unwrap()); + let snapshot = cx.finish(collect(&cx).unwrap()).unwrap(); assert_eq!(snapshot["entities"], json!([])); assert_eq!(snapshot["missingInputs"], json!(["schema.json"])); // Present, with nothing missing, records nothing. let cx = context(json!({"schema":"schema.prisma"})); - assert!(cx.finish(collect(&cx).unwrap()).get("missingInputs").is_none()); + assert!(cx.finish(collect(&cx).unwrap()).unwrap().get("missingInputs").is_none()); } #[test] diff --git a/packages/extractors/sdk/src/context.rs b/packages/extractors/sdk/src/context.rs index 2b3c41ce5..43aaf14fc 100644 --- a/packages/extractors/sdk/src/context.rs +++ b/packages/extractors/sdk/src/context.rs @@ -62,6 +62,18 @@ pub struct Context { comparisons: Option>, diagnostics: Mutex, missing: Mutex>, + subject: Mutex, +} + +/// The anchors of an extraction's subject checked during a run. +#[derive(Default)] +struct Subject { + /// Whether any was checked. + checked: bool, + /// Whether any of those exists. + found: bool, + /// Those that don't, in byte order. + missing: BTreeSet, } impl Context { @@ -137,6 +149,7 @@ impl Context { comparisons: None, diagnostics: Mutex::default(), missing: Mutex::default(), + subject: Mutex::default(), }) } @@ -362,6 +375,45 @@ impl Context { Ok(exists) } + /// Whether `relative`, an anchor of what the projection describes (its + /// subject: a workflow, a manifest, a schema file), exists at the examined + /// revision. One that doesn't is recorded as a missing input, as + /// [`Context::input_exists`] records it; when every anchor checked is + /// missing, [`Context::finish`] marks the extraction absent, and present + /// when any exists. Check auxiliary inputs, whose absence leaves the + /// subject in place, with [`Context::input_exists`]. + pub fn subject_exists(&self, relative: &str) -> Result { + let exists = self.input_exists(relative)?; + self.anchor(relative, exists); + Ok(exists) + } + + /// [`Context::subject_exists`] for a glob anchor (in the grammar of + /// [`crate::glob`]): whether it matches one of `files`, as the extractor + /// lists them. One that matches none is recorded as a missing input. + pub fn subject_matches(&self, pattern: &str, files: &[String]) -> Result { + let pattern = pattern.trim_start_matches("./").trim_end_matches('/'); + ensure!(!pattern.is_empty(), "An anchor of the subject is a nonempty project-relative glob"); + let glob = crate::glob(pattern)?; + let matches = files.iter().any(|file| glob.is_match(file)); + if !matches { + self.missing_input(pattern); + } + self.anchor(pattern, matches); + Ok(matches) + } + + fn anchor(&self, input: &str, exists: bool) { + let mut subject = self.subject.lock().expect("subject lock"); + subject.checked = true; + subject.found |= exists; + if !exists { + subject + .missing + .insert(input.trim_start_matches("./").trim_end_matches('/').to_owned()); + } + } + /// Records a declared input the examined revision lacks: a path that doesn't /// exist, or a glob that matches no file. pub fn missing_input(&self, input: &str) { @@ -375,13 +427,36 @@ impl Context { } /// `extraction` with the missing inputs recorded during the run, as its - /// `missingInputs`. [`crate::serve`] applies it to what an extractor returns. - pub fn finish(&self, mut extraction: Value) -> Value { + /// `missingInputs`, and, when the extractor checked its subject's anchors + /// ([`Context::subject_exists`]) and doesn't report `presence` itself, its + /// `presence`: `absent` when none exists, else `present`. Fails when none + /// exists but the extractor returned items: an absent subject has none. + /// [`crate::serve`] applies it to what an extractor returns. + pub fn finish(&self, mut extraction: Value) -> Result { let missing = self.missing_inputs(); - if !missing.is_empty() && extraction.is_object() { - extraction["missingInputs"] = Value::from(missing); + let Some(object) = extraction.as_object_mut() else { + return Ok(extraction); + }; + if !missing.is_empty() { + object.insert("missingInputs".to_owned(), Value::from(missing)); + } + let subject = self.subject.lock().expect("subject lock"); + if subject.checked && !object.contains_key("presence") { + if !subject.found { + let items = ["entities", "relationships"] + .iter() + .any(|key| object.get(*key).and_then(Value::as_array).is_some_and(|items| !items.is_empty())); + ensure!( + !items, + "{} found none of its subject ({}) but returned items; return none when its subject is absent", + self.extractor, + subject.missing.iter().cloned().collect::>().join(", ") + ); + } + let presence = if subject.found { "present" } else { "absent" }; + object.insert("presence".to_owned(), Value::from(presence)); } - extraction + Ok(extraction) } /// One of the revision's files: whether it is a symlink, and its size. diff --git a/packages/extractors/sdk/src/entry.rs b/packages/extractors/sdk/src/entry.rs index f5131d234..2bccb417a 100644 --- a/packages/extractors/sdk/src/entry.rs +++ b/packages/extractors/sdk/src/entry.rs @@ -41,7 +41,7 @@ pub fn main(extractor: &str, collect: impl FnOnce(&Context) -> Result) -> pub fn serve(context: Result, collect: impl FnOnce(&Context) -> Result) -> ExitCode { let (result, diagnostics) = match context { Ok(cx) => ( - collect(&cx).and_then(|value| Ok(serde_json::to_string(&cx.finish(value))?)), + collect(&cx).and_then(|value| Ok(serde_json::to_string(&cx.finish(value)?)?)), cx.diagnostics(), ), Err(error) => (Err(error), String::new()), diff --git a/packages/extractors/sdk/tests/source.rs b/packages/extractors/sdk/tests/source.rs index abe748430..16bd931e1 100644 --- a/packages/extractors/sdk/tests/source.rs +++ b/packages/extractors/sdk/tests/source.rs @@ -162,7 +162,7 @@ fn a_declared_input_the_revision_lacks_is_recorded_as_missing_however_it_is_read assert!(!cx.input_exists("./deploy/").unwrap()); cx.missing_input("deploy/*.yaml"); assert_eq!(cx.missing_inputs(), ["deploy", "deploy/*.yaml", "packages/api/schema.prisma"]); - let finished = cx.finish(json!({"entities": []})); + let finished = cx.finish(json!({"entities": []})).unwrap(); assert_eq!( finished["missingInputs"], json!(["deploy", "deploy/*.yaml", "packages/api/schema.prisma"]) @@ -183,5 +183,68 @@ fn a_declared_input_the_revision_lacks_is_recorded_as_missing_however_it_is_read assert!(!in_place.exists("ignored.log").unwrap()); // Nothing missing adds nothing. let clean = Context::new("t", request(json!({"mode": "in-place", "root": root.path()}))).unwrap(); - assert_eq!(clean.finish(json!({"entities": []})), json!({"entities": []})); + assert_eq!(clean.finish(json!({"entities": []})).unwrap(), json!({"entities": []})); +} + +fn checkout(root: &Path) -> Context { + Context::new("t", request(json!({"mode": "in-place", "root": root}))).unwrap() +} + +fn empty() -> Value { + json!({"protocolVersion": 0, "schema": "graph/v0", "entities": [], "relationships": []}) +} + +#[test] +fn a_subject_none_of_whose_anchors_exists_is_absent() { + let (root, _) = repository(); + let cx = checkout(root.path()); + assert!(!cx.subject_exists(".github/workflows/ci.yml").unwrap()); + assert!(!cx.subject_matches("deploy/*.yaml", cx.files().unwrap()).unwrap()); + let absent = cx.finish(empty()).unwrap(); + assert_eq!(absent["presence"], "absent"); + assert_eq!(absent["missingInputs"], json!([".github/workflows/ci.yml", "deploy/*.yaml"])); + assert!(projections_engine::normalize(&absent, "").is_ok()); + // Returning items anyway is the extractor's error, naming what it didn't find. + let mut items = empty(); + items["entities"] = json!([{"id": "a", "kind": "entity", "label": "a"}]); + let error = cx.finish(items).unwrap_err().to_string(); + assert_eq!( + error, + "t found none of its subject (.github/workflows/ci.yml, deploy/*.yaml) but returned items; return none when its subject is absent" + ); +} + +#[test] +fn a_subject_some_of_whose_anchors_exist_is_present_and_names_the_rest() { + let (root, _) = repository(); + let cx = checkout(root.path()); + assert!(cx.subject_exists("a.txt").unwrap()); + assert!(!cx.subject_exists("./b.txt").unwrap()); + assert!(cx.subject_matches("src/*.json", cx.files().unwrap()).unwrap()); + // Written from the project, as the Node and Python helpers accept it. + assert!(cx.subject_matches("./src/*.json", cx.files().unwrap()).unwrap()); + assert!(cx.subject_matches("./", cx.files().unwrap()).is_err()); + // An auxiliary input's absence is recorded but leaves the subject as it is. + assert!(!cx.input_exists("values.yaml").unwrap()); + let mut items = empty(); + items["entities"] = json!([{"id": "a", "kind": "entity", "label": "a"}]); + let present = cx.finish(items).unwrap(); + assert_eq!(present["presence"], "present"); + assert_eq!(present["missingInputs"], json!(["b.txt", "values.yaml"])); + // Present and empty is present too. + assert_eq!(cx.finish(empty()).unwrap()["presence"], "present"); +} + +#[test] +fn presence_is_left_unreported_without_anchors_and_as_written_when_the_extractor_reports_it() { + let (root, _) = repository(); + let cx = checkout(root.path()); + assert!(!cx.input_exists("values.yaml").unwrap()); + let unreported = cx.finish(empty()).unwrap(); + assert!(unreported.get("presence").is_none()); + assert_eq!(unreported["missingInputs"], json!(["values.yaml"])); + assert!(!cx.subject_exists("ci.yml").unwrap()); + let mut reported = empty(); + reported["presence"] = json!("present"); + assert_eq!(cx.finish(reported).unwrap()["presence"], "present"); } diff --git a/packages/extractors/tetragon-policies/tests/extractions.rs b/packages/extractors/tetragon-policies/tests/extractions.rs index d86db4f4c..ace48b0a9 100644 --- a/packages/extractors/tetragon-policies/tests/extractions.rs +++ b/packages/extractors/tetragon-policies/tests/extractions.rs @@ -322,7 +322,7 @@ fn declared_inputs_the_revision_lacks_are_missing_not_errors() { &root, json!({"id":"runtime-policies","extractor":"tetragon-policies","inputs":inputs}), ); - cx.finish(collect(&cx).unwrap()) + cx.finish(collect(&cx).unwrap()).unwrap() }; // None of the policies exist yet: an empty extraction naming what's missing. let absent = run(json!({ diff --git a/packages/extractors/workspace-dependencies/tests/managers.rs b/packages/extractors/workspace-dependencies/tests/managers.rs index de9d704ff..00de770a5 100644 --- a/packages/extractors/workspace-dependencies/tests/managers.rs +++ b/packages/extractors/workspace-dependencies/tests/managers.rs @@ -247,7 +247,7 @@ fn a_missing_root_manifest_is_named_as_missing_instead_of_extracting_nothing_sil &scratch.0, json!({"id":"workspace-dependencies","extractor":"workspace-dependencies","inputs":inputs}), ); - let extraction = cx.finish(collect(&cx).unwrap()); + let extraction = cx.finish(collect(&cx).unwrap()).unwrap(); assert_eq!(extraction["entities"], json!([])); assert_eq!(extraction["missingInputs"], json!([missing])); } diff --git a/packages/schemas/fixtures/conformance.json b/packages/schemas/fixtures/conformance.json index 1e875a7be..f686282bf 100644 --- a/packages/schemas/fixtures/conformance.json +++ b/packages/schemas/fixtures/conformance.json @@ -123,7 +123,24 @@ {"id": "review-identity-only", "request": {"version": 0, "operation": "review", "comparison": {"protocolVersion": 0, "changes": [{"id": "service:new", "collection": "entities", "before": ["service:old"], "after": ["service:new"], "status": "unchanged", "correspondence": "declared"}], "steps": []}}, "expectedResult": {"status": "changed", "reviewable": 1, "content": 0, "identity": 1, "variation": 0}}, {"id": "review-content", "request": {"version": 0, "operation": "review", "comparison": {"protocolVersion": 0, "changes": [{"id": "a", "collection": "entities", "before": [], "after": ["a"], "status": "added", "correspondence": "none"}, {"id": "b", "collection": "entities", "before": ["b"], "after": ["b"], "status": "modified", "correspondence": "exact"}], "steps": []}}, "expectedResult": {"status": "changed", "reviewable": 2, "content": 2, "identity": 0, "variation": 0}}, {"id": "review-mixed", "request": {"version": 0, "operation": "review", "comparison": {"protocolVersion": 0, "changes": [{"id": "a", "collection": "entities", "before": ["old"], "after": ["a"], "status": "modified", "correspondence": "declared"}, {"id": "b", "collection": "entities", "before": ["b"], "after": [], "status": "removed", "correspondence": "none"}, {"id": "test:c", "collection": "entities", "before": ["test:c"], "after": ["test:c"], "status": "unchanged", "correspondence": "exact", "varied": [{"path": "/data/durationMs", "within": true}]}], "steps": []}}, "expectedResult": {"status": "changed", "reviewable": 2, "content": 2, "identity": 1, "variation": 1}}, - {"id": "review-unknown-status", "request": {"version": 0, "operation": "review", "comparison": {"protocolVersion": 0, "changes": [{"id": "a", "collection": "entities", "before": ["a"], "after": ["a"], "status": "changed", "correspondence": "exact"}], "steps": []}}, "expectError": "invalid-type", "expectedErrorPath": "/comparison/changes/0/status"} + {"id": "review-unknown-status", "request": {"version": 0, "operation": "review", "comparison": {"protocolVersion": 0, "changes": [{"id": "a", "collection": "entities", "before": ["a"], "after": ["a"], "status": "changed", "correspondence": "exact"}], "steps": []}}, "expectError": "invalid-type", "expectedErrorPath": "/comparison/changes/0/status"}, + {"id": "presence-added", "request": {"version": 0, "operation": "presence", "before": {"protocolVersion": 0, "schema": "graph/v0", "presence": "absent", "entities": [], "relationships": [], "missingInputs": [".github/workflows/ci.yml"]}, "after": {"protocolVersion": 0, "schema": "graph/v0", "presence": "present", "entities": [{"id": "a", "kind": "entity", "label": "a"}], "relationships": []}}, "expectedResult": {"before": "absent", "after": "present", "change": "added", "inferred": false}}, + {"id": "presence-removed", "request": {"version": 0, "operation": "presence", "before": {"protocolVersion": 0, "schema": "graph/v0", "presence": "present", "entities": [{"id": "a", "kind": "entity", "label": "a"}], "relationships": []}, "after": {"protocolVersion": 0, "schema": "graph/v0", "presence": "absent", "entities": [], "relationships": [], "missingInputs": [".github/workflows/ci.yml"]}}, "expectedResult": {"before": "present", "after": "absent", "change": "removed", "inferred": false}}, + {"id": "presence-absent-on-both-sides", "request": {"version": 0, "operation": "presence", "before": {"protocolVersion": 0, "schema": "graph/v0", "presence": "absent", "entities": [], "relationships": [], "missingInputs": [".github/workflows/ci.yml"]}, "after": {"protocolVersion": 0, "schema": "graph/v0", "presence": "absent", "entities": [], "relationships": [], "missingInputs": [".github/workflows/ci.yml"]}}, "expectedResult": {"before": "absent", "after": "absent", "change": "absent", "inferred": false}}, + {"id": "presence-present-and-empty", "request": {"version": 0, "operation": "presence", "before": {"protocolVersion": 0, "schema": "graph/v0", "presence": "present", "entities": [], "relationships": []}, "after": {"protocolVersion": 0, "schema": "graph/v0", "presence": "present", "entities": [], "relationships": []}}, "expectedResult": {"before": "present", "after": "present", "change": "present", "inferred": false}}, + {"id": "presence-reported-over-a-missing-auxiliary-input", "request": {"version": 0, "operation": "presence", "before": {"protocolVersion": 0, "schema": "graph/v0", "presence": "present", "entities": [], "relationships": [], "missingInputs": [".github/workflows/ci.yml"]}, "after": {"protocolVersion": 0, "schema": "graph/v0", "presence": "present", "entities": [{"id": "a", "kind": "entity", "label": "a"}], "relationships": []}}, "expectedResult": {"before": "present", "after": "present", "change": "present", "inferred": false}}, + {"id": "presence-added-inferred", "request": {"version": 0, "operation": "presence", "before": {"protocolVersion": 0, "schema": "graph/v0", "entities": [], "relationships": [], "missingInputs": [".github/workflows/ci.yml"]}, "after": {"protocolVersion": 0, "schema": "graph/v0", "entities": [{"id": "a", "kind": "entity", "label": "a"}], "relationships": []}}, "expectedResult": {"before": "absent", "after": "present", "change": "added", "inferred": true}}, + {"id": "presence-removed-inferred", "request": {"version": 0, "operation": "presence", "before": {"protocolVersion": 0, "schema": "graph/v0", "entities": [{"id": "a", "kind": "entity", "label": "a"}], "relationships": []}, "after": {"protocolVersion": 0, "schema": "graph/v0", "entities": [], "relationships": [], "missingInputs": [".github/workflows/ci.yml"]}}, "expectedResult": {"before": "present", "after": "absent", "change": "removed", "inferred": true}}, + {"id": "presence-one-side-reported", "request": {"version": 0, "operation": "presence", "before": {"protocolVersion": 0, "schema": "graph/v0", "presence": "absent", "entities": [], "relationships": [], "missingInputs": [".github/workflows/ci.yml"]}, "after": {"protocolVersion": 0, "schema": "graph/v0", "entities": [{"id": "a", "kind": "entity", "label": "a"}], "relationships": []}}, "expectedResult": {"before": "absent", "after": "present", "change": "added", "inferred": true}}, + {"id": "presence-unreported-and-empty-is-unknown", "request": {"version": 0, "operation": "presence", "before": {"protocolVersion": 0, "schema": "graph/v0", "entities": [], "relationships": []}, "after": {"protocolVersion": 0, "schema": "graph/v0", "entities": [{"id": "a", "kind": "entity", "label": "a"}], "relationships": []}}, "expectedResult": {"before": "unknown", "after": "present", "change": "unknown", "inferred": true}}, + {"id": "presence-unknown-on-both-sides", "request": {"version": 0, "operation": "presence", "before": {"protocolVersion": 0, "schema": "graph/v0", "entities": [], "relationships": []}, "after": {"protocolVersion": 0, "schema": "graph/v0", "entities": [], "relationships": []}}, "expectedResult": {"before": "unknown", "after": "unknown", "change": "unknown", "inferred": false}}, + {"id": "presence-absent-with-items", "request": {"version": 0, "operation": "presence", "before": {"protocolVersion": 0, "schema": "graph/v0", "presence": "absent", "entities": [{"id": "a", "kind": "entity", "label": "a"}], "relationships": [], "missingInputs": [".github/workflows/ci.yml"]}, "after": {"protocolVersion": 0, "schema": "graph/v0", "presence": "present", "entities": [{"id": "a", "kind": "entity", "label": "a"}], "relationships": []}}, "expectError": "absent-with-items", "expectedErrorPath": "/before/presence"}, + {"id": "presence-absent-without-missing-input", "request": {"version": 0, "operation": "presence", "before": {"protocolVersion": 0, "schema": "graph/v0", "presence": "present", "entities": [{"id": "a", "kind": "entity", "label": "a"}], "relationships": []}, "after": {"protocolVersion": 0, "schema": "graph/v0", "presence": "absent", "entities": [], "relationships": []}}, "expectError": "absent-without-missing-input", "expectedErrorPath": "/after/presence"}, + {"id": "presence-malformed-relationships-beside-entities", "request": {"version": 0, "operation": "presence", "before": {"entities": [{"id": "a"}], "relationships": "invalid"}, "after": {}}, "expectError": "invalid-type", "expectedErrorPath": "/before/relationships"}, + {"id": "presence-invalid", "request": {"version": 0, "operation": "presence", "before": {"protocolVersion": 0, "schema": "graph/v0", "presence": "gone", "entities": [], "relationships": [], "missingInputs": [".github/workflows/ci.yml"]}, "after": {"protocolVersion": 0, "schema": "graph/v0", "presence": "present", "entities": [{"id": "a", "kind": "entity", "label": "a"}], "relationships": []}}, "expectError": "invalid-presence", "expectedErrorPath": "/before/presence"}, + {"id": "canonical-absent", "request": {"version": 0, "operation": "canonicalize", "extraction": {"protocolVersion": 0, "schema": "graph/v0", "presence": "absent", "entities": [], "relationships": [], "missingInputs": [".github/workflows/ci.yml"]}}, "expectedCanonical": "{\"entities\":[],\"missingInputs\":[\".github/workflows/ci.yml\"],\"presence\":\"absent\",\"protocolVersion\":0,\"relationships\":[],\"schema\":\"graph/v0\"}"}, + {"id": "normalize-absent-with-items", "request": {"version": 0, "operation": "normalize", "extraction": {"protocolVersion": 0, "schema": "graph/v0", "presence": "absent", "entities": [{"id": "a", "kind": "entity", "label": "a"}], "relationships": [], "missingInputs": [".github/workflows/ci.yml"]}}, "expectError": "absent-with-items", "expectedErrorPath": "/extraction/presence"}, + {"id": "normalize-absent-without-missing-input", "request": {"version": 0, "operation": "normalize", "extraction": {"protocolVersion": 0, "schema": "graph/v0", "presence": "absent", "entities": [], "relationships": []}}, "expectError": "absent-without-missing-input", "expectedErrorPath": "/extraction/presence"} ], "comparisons": [ { diff --git a/packages/schemas/fixtures/extractor-helpers.json b/packages/schemas/fixtures/extractor-helpers.json index c49e77690..ce1b7b3c7 100644 --- a/packages/schemas/fixtures/extractor-helpers.json +++ b/packages/schemas/fixtures/extractor-helpers.json @@ -1,6 +1,6 @@ { "version": 0, - "description": "The extractor helpers' shared behaviour: the Python module (packages/cli/python/projections) and @githubnext/projections-sdk/extractor (packages/sdk/src/extractor) read each request, answer each accessor and write each extraction alike, failing with the same messages. A case reads `stdin` (or the text `stdinText`) as the request, then either reads the `accessors` named (JavaScript's names; Python's in snake_case) or calls result() with `result`; it expects their values or the extraction (`expected`), or an `error` message (or one starting with `errorStartsWith`). Paths are written with `/`, which Windows separators are compared as.", + "description": "The extractor helpers' shared behaviour: the Python module (packages/cli/python/projections) and @githubnext/projections-sdk/extractor (packages/sdk/src/extractor) read each request, answer each accessor and write each extraction alike, failing with the same messages. A case reads `stdin` (or the text `stdinText`) as the request, then either reads the `accessors` named (JavaScript's names; Python's in snake_case) or calls the request methods in `checks` (each `[name, argument]`, on a revision holding just `files`, written to a fresh `repository.root`) and then result() with `result`; it expects their values or the extraction (`expected`), or an `error` message (or one starting with `errorStartsWith`). Paths are written with `/`, which Windows separators are compared as.", "cases": [ { "id": "accessors-at-the-root", @@ -502,7 +502,21 @@ "capabilities": {"trusted":true,"network":false} }, "result": {"colour":"red"}, - "error": "An extraction has no field \"colour\"; besides its entities and relationships it may have metadata, missingInputs, vocabularies, volatile" - } + "error": "An extraction has no field \"colour\"; besides its entities and relationships it may have metadata, missingInputs, presence, vocabularies, volatile" + }, + {"id": "subject-checks-answer-whether-anchors-exist", "stdin": {"protocolVersion": 0, "projection": {"id": "ci", "definition": {"id": "ci"}}, "repository": {"mode": "materialized", "root": "/revision", "project": "", "revision": {"kind": "commit", "ref": "HEAD", "commit": "0123456789abcdef0123456789abcdef01234567", "dirty": false}}, "capabilities": {"trusted": true, "network": false}}, "files": [".github/workflows/ci.yml", "docs/a.md", "src/app/main.py"], "checks": [["subjectExists", ".github/workflows/ci.yml"], ["subjectExists", "./src/app/"], ["subjectExists", "gone.yml"], ["subjectMatches", "docs/*.md"], ["subjectMatches", "**/*.py"], ["subjectMatches", "*.md"], ["subjectMatches", "src/**"]], "expected": [true, true, false, true, true, false, true]}, + {"id": "a-subject-none-of-whose-anchors-exists-is-absent", "stdin": {"protocolVersion": 0, "projection": {"id": "ci", "definition": {"id": "ci"}}, "repository": {"mode": "materialized", "root": "/revision", "project": "", "revision": {"kind": "commit", "ref": "HEAD", "commit": "0123456789abcdef0123456789abcdef01234567", "dirty": false}}, "capabilities": {"trusted": true, "network": false}}, "files": ["README.md"], "checks": [["subjectExists", ".github/workflows/ci.yml"], ["subjectMatches", "deploy/*.yaml"]], "result": {"schema": "dag/v0"}, "expected": {"protocolVersion": 0, "schema": "dag/v0", "entities": [], "relationships": [], "missingInputs": [".github/workflows/ci.yml", "deploy/*.yaml"], "presence": "absent"}}, + {"id": "a-subject-some-of-whose-anchors-exist-is-present", "stdin": {"protocolVersion": 0, "projection": {"id": "ci", "definition": {"id": "ci"}}, "repository": {"mode": "materialized", "root": "/revision", "project": "", "revision": {"kind": "commit", "ref": "HEAD", "commit": "0123456789abcdef0123456789abcdef01234567", "dirty": false}}, "capabilities": {"trusted": true, "network": false}}, "files": ["schema/a.prisma"], "checks": [["subjectExists", "schema/a.prisma"], ["subjectExists", "schema/b.prisma"]], "result": {"entities": [{"id": "model:A", "kind": "model", "label": "A"}], "missingInputs": ["values.yaml"]}, "expected": {"protocolVersion": 0, "schema": "graph/v0", "entities": [{"id": "model:A", "kind": "model", "label": "A"}], "relationships": [], "missingInputs": ["schema/b.prisma", "values.yaml"], "presence": "present"}}, + {"id": "a-subject-present-and-empty-is-present", "stdin": {"protocolVersion": 0, "projection": {"id": "ci", "definition": {"id": "ci"}}, "repository": {"mode": "materialized", "root": "/revision", "project": "", "revision": {"kind": "commit", "ref": "HEAD", "commit": "0123456789abcdef0123456789abcdef01234567", "dirty": false}}, "capabilities": {"trusted": true, "network": false}}, "files": ["schema/a.prisma"], "checks": [["subjectExists", "schema/a.prisma"]], "result": {}, "expected": {"protocolVersion": 0, "schema": "graph/v0", "entities": [], "relationships": [], "presence": "present"}}, + {"id": "a-subject-in-a-nested-project-is-checked-there", "stdin": {"protocolVersion": 0, "projection": {"id": "ci", "definition": {"id": "ci"}}, "repository": {"mode": "materialized", "root": "/revision", "project": "packages/app", "revision": {"kind": "commit", "ref": "HEAD", "commit": "0123456789abcdef0123456789abcdef01234567", "dirty": false}}, "capabilities": {"trusted": true, "network": false}}, "files": ["workflow.yml", "packages/app/src/a.ts"], "checks": [["subjectExists", "workflow.yml"]], "result": {}, "expected": {"protocolVersion": 0, "schema": "graph/v0", "entities": [], "relationships": [], "missingInputs": ["workflow.yml"], "presence": "absent"}}, + {"id": "an-absent-subject-with-items-is-an-error", "stdin": {"protocolVersion": 0, "projection": {"id": "ci", "definition": {"id": "ci"}}, "repository": {"mode": "materialized", "root": "/revision", "project": "", "revision": {"kind": "commit", "ref": "HEAD", "commit": "0123456789abcdef0123456789abcdef01234567", "dirty": false}}, "capabilities": {"trusted": true, "network": false}}, "files": ["README.md"], "checks": [["subjectExists", "ci.yml"], ["subjectExists", "build.yml"]], "result": {"entities": [{"id": "job:a", "kind": "job", "label": "a"}]}, "error": "None of the extractor's subject exists at the revision (build.yml, ci.yml), but its extraction has items; return none when its subject is absent"}, + {"id": "presence-the-extractor-gives-is-kept", "stdin": {"protocolVersion": 0, "projection": {"id": "ci", "definition": {"id": "ci"}}, "repository": {"mode": "materialized", "root": "/revision", "project": "", "revision": {"kind": "commit", "ref": "HEAD", "commit": "0123456789abcdef0123456789abcdef01234567", "dirty": false}}, "capabilities": {"trusted": true, "network": false}}, "files": ["README.md"], "checks": [["subjectExists", "ci.yml"]], "result": {"presence": "present"}, "expected": {"protocolVersion": 0, "schema": "graph/v0", "entities": [], "relationships": [], "missingInputs": ["ci.yml"], "presence": "present"}}, + {"id": "presence-without-checks-is-as-given", "stdin": {"protocolVersion": 0, "projection": {"id": "ci", "definition": {"id": "ci"}}, "repository": {"mode": "materialized", "root": "/revision", "project": "", "revision": {"kind": "commit", "ref": "HEAD", "commit": "0123456789abcdef0123456789abcdef01234567", "dirty": false}}, "capabilities": {"trusted": true, "network": false}}, "result": {"presence": "absent", "missingInputs": ["ci.yml"]}, "expected": {"protocolVersion": 0, "schema": "graph/v0", "entities": [], "relationships": [], "presence": "absent", "missingInputs": ["ci.yml"]}}, + {"id": "an-anchor-outside-the-project", "stdin": {"protocolVersion": 0, "projection": {"id": "ci", "definition": {"id": "ci"}}, "repository": {"mode": "materialized", "root": "/revision", "project": "", "revision": {"kind": "commit", "ref": "HEAD", "commit": "0123456789abcdef0123456789abcdef01234567", "dirty": false}}, "capabilities": {"trusted": true, "network": false}}, "files": ["README.md"], "checks": [["subjectExists", "../ci.yml"]], "error": "The anchor \"../ci.yml\" isn't within the project; name it relative to the project"}, + {"id": "an-anchor-that-is-not-a-path", "stdin": {"protocolVersion": 0, "projection": {"id": "ci", "definition": {"id": "ci"}}, "repository": {"mode": "materialized", "root": "/revision", "project": "", "revision": {"kind": "commit", "ref": "HEAD", "commit": "0123456789abcdef0123456789abcdef01234567", "dirty": false}}, "capabilities": {"trusted": true, "network": false}}, "files": ["README.md"], "checks": [["subjectMatches", ""]], "error": "An anchor of the subject is a nonempty project-relative path or glob, not \"\""}, + {"id": "a-subject-glob-written-from-the-project", "stdin": {"protocolVersion": 0, "projection": {"id": "ci", "definition": {"id": "ci"}}, "repository": {"mode": "materialized", "root": "/revision", "project": "", "revision": {"kind": "commit", "ref": "HEAD", "commit": "0123456789abcdef0123456789abcdef01234567", "dirty": false}}, "capabilities": {"trusted": true, "network": false}}, "files": ["src/b.json"], "checks": [["subjectMatches", "./src/*.json"]], "expected": [true]}, + {"id": "an-anchor-outside-the-scope", "stdin": {"protocolVersion": 0, "projection": {"id": "ci", "definition": {"id": "ci"}}, "repository": {"mode": "materialized", "root": "/revision", "project": "", "revision": {"kind": "commit", "ref": "HEAD", "commit": "0123456789abcdef0123456789abcdef01234567", "dirty": false}, "scope": ["src"]}, "capabilities": {"trusted": true, "network": false}}, "files": ["ci.yml", "src/b.json"], "checks": [["subjectExists", "ci.yml"]], "error": "The anchor \"ci.yml\" is outside the declared scope (src); declare it in the definition's scope"}, + {"id": "an-anchor-at-the-root-of-the-file-system", "stdin": {"protocolVersion": 0, "projection": {"id": "ci", "definition": {"id": "ci"}}, "repository": {"mode": "materialized", "root": "/revision", "project": "", "revision": {"kind": "commit", "ref": "HEAD", "commit": "0123456789abcdef0123456789abcdef01234567", "dirty": false}}, "capabilities": {"trusted": true, "network": false}}, "files": ["README.md"], "checks": [["subjectExists", "/"]], "error": "The anchor \"/\" isn't within the project; name it relative to the project"}, + {"id": "a-subject-glob-that-names-the-project", "stdin": {"protocolVersion": 0, "projection": {"id": "ci", "definition": {"id": "ci"}}, "repository": {"mode": "materialized", "root": "/revision", "project": "", "revision": {"kind": "commit", "ref": "HEAD", "commit": "0123456789abcdef0123456789abcdef01234567", "dirty": false}}, "capabilities": {"trusted": true, "network": false}}, "files": ["README.md"], "checks": [["subjectMatches", "./"]], "error": "An anchor of the subject is a nonempty project-relative path or glob, not \"./\""} ] } diff --git a/packages/schemas/internal/conformance.json b/packages/schemas/internal/conformance.json index 09956d8a9..2677b4740 100644 --- a/packages/schemas/internal/conformance.json +++ b/packages/schemas/internal/conformance.json @@ -19,7 +19,7 @@ "properties": { "version": {"type": "number", "const": 0}, "operation": { - "enum": ["decode", "normalize", "canonicalize", "pair", "vary", "review", "validate-comparison"] + "enum": ["decode", "normalize", "canonicalize", "pair", "presence", "vary", "review", "validate-comparison"] } }, "description": "An engine request; the other fields are the operation's." diff --git a/packages/schemas/internal/extractor-helpers.json b/packages/schemas/internal/extractor-helpers.json index 6aca3206f..73ccfaf47 100644 --- a/packages/schemas/internal/extractor-helpers.json +++ b/packages/schemas/internal/extractor-helpers.json @@ -39,9 +39,29 @@ } } }, - {"type": "object", "required": ["result"], "properties": {"result": {}}} + {"type": "object", "required": ["result"], "properties": {"result": {}}}, + { + "type": "object", + "required": ["checks"], + "properties": { + "checks": { + "type": "array", + "items": { + "type": "array", + "prefixItems": [{"type": "string", "pattern": "^[a-zA-Z][a-zA-Z0-9]*$"}, {}], + "items": false, + "minItems": 2 + }, + "minItems": 1 + } + } + } ] }, + { + "type": "object", + "properties": {"files": {"type": "array", "items": {"type": "string", "minLength": 1}, "minItems": 1}} + }, { "anyOf": [ {"type": "object", "required": ["expected"], "properties": {"expected": {}}}, diff --git a/packages/schemas/schemas/extraction/v0.json b/packages/schemas/schemas/extraction/v0.json index 8bac4421c..3499a665b 100644 --- a/packages/schemas/schemas/extraction/v0.json +++ b/packages/schemas/schemas/extraction/v0.json @@ -30,8 +30,20 @@ "maxItems": 256, "uniqueItems": true }, + "presence": { + "description": "Whether what the projection describes (its subject: a workflow, a manifest, a schema file) exists at the examined revision. `present`: it does, though it may be empty. `absent`: it doesn't (for example a workflow the revision predates), so the extraction has no entities or relationships and `missingInputs` names what is missing. Omitted: not reported, which is unknown, never present; v1 will require it. Part of the digest when written.", + "anyOf": [ + {"type": "string", "const": "present"}, + {"type": "string", "const": "absent"} + ] + }, "metadata": {"$ref": "#/$defs/data"} }, + "if": {"required": ["presence"], "properties": {"presence": {"const": "absent"}}}, + "then": { + "required": ["missingInputs"], + "properties": {"entities": {"maxItems": 0}, "relationships": {"maxItems": 0}, "missingInputs": {"minItems": 1}} + }, "allOf": [ { "if": {"required": ["schema"], "properties": {"schema": {"const": "graph/v0"}}}, diff --git a/packages/schemas/src/index.ts b/packages/schemas/src/index.ts index 03270539f..1d0db6a04 100644 --- a/packages/schemas/src/index.ts +++ b/packages/schemas/src/index.ts @@ -1,6 +1,7 @@ import type {Static} from 'typebox' import type {DomainSchema, Json, Vocabulary} from './constants.js' import type {DataOf, TypedKind} from './domains.js' +import type {PresenceChange, PresenceSide} from './presence.js' import type {ChangeSchema, ComparisonSchema, ContextSchema, StepSchema, VariedSchema} from './typebox/comparison.js' import type { DefaultComparatorSchema, @@ -38,6 +39,8 @@ import type {ScenarioComparatorSchema, ScenarioSchema, ScenariosDocumentSchema} // published JSON Schemas. This entry imports them as types only, so it never loads TypeBox at runtime. export {customComparator, isComparatorFile} from './comparator.js' +export {extractionPresence, presenceChange} from './presence.js' +export type {ExtractionPresence, PresenceChange, PresenceSide, PresenceTransition, SidePresence} from './presence.js' export { comparisonModes, domainSchemas, @@ -366,8 +369,8 @@ export interface Variation { within: {collection: 'entities' | 'relationships'; id: string; path: string}[] /** * Everything else that differs: volatile values beyond tolerance, other fields (`/label`, `/data/`), - * items in one run only (an empty path) and, without a collection or ID, `/schema`, `/vocabularies` or - * `/volatile`. + * items in one run only (an empty path) and, without a collection or ID, `/schema`, `/vocabularies`, + * `/volatile`, `/missingInputs` or `/presence`. */ beyond: {collection?: 'entities' | 'relationships'; id?: string; path: string; reason: string}[] } @@ -419,12 +422,16 @@ export type EngineRequest = | {version: 0; operation: 'vary'; before: unknown; after: unknown} | {version: 0; operation: 'pair'; before: unknown; after: unknown} | {version: 0; operation: 'review'; comparison: unknown} + | {version: 0; operation: 'presence'; before: unknown; after: unknown} | {version: 0; operation: 'decode'; json: string} | {version: 0; operation: 'parse-json'; json: string} /** The engine's reply to one request: the operation's `result`, or at least one error diagnostic. */ export type EngineResponse = - | {ok: true; result: Extraction | CanonicalExtraction | Comparison | Variation | DefinitionPairing | ComparisonReview | Json} + | { + ok: true + result: Extraction | CanonicalExtraction | Comparison | Variation | DefinitionPairing | ComparisonReview | PresenceChange | Json + } | {ok: false; diagnostics: Diagnostic[]} /** @@ -465,6 +472,13 @@ export interface ProjectionEngine { * The one classification every host and the CLI use; read it here, never by counting `changes` yourself. */ review: (comparison: Pick) => Promise + /** + * Whether what two extractions describe exists on each side, and what the change did to it: `added`, `removed`, + * `absent` (on both sides), `present` or `unknown`. A side that omits `presence` is unknown unless it's inferred: + * `present` with items, `absent` with none and missing inputs (`inferred: true`). Rejects an `absent` side with items + * or without missing inputs. `presenceChange` is the same rule without the engine. + */ + presence: (before: PresenceSide, after: PresenceSide) => Promise /** Runs the default comparator module and validates its result. */ compare: (before: unknown, after: unknown, options?: DefaultComparatorOptions) => Promise /** Identity of the default comparator module this engine runs. */ diff --git a/packages/schemas/src/presence.ts b/packages/schemas/src/presence.ts new file mode 100644 index 000000000..004a3db8e --- /dev/null +++ b/packages/schemas/src/presence.ts @@ -0,0 +1,64 @@ +// Whether what a projection describes exists at each side of a pair, and what the change did to it: the TypeScript +// mirror of the engine's `presence` module (packages/engine/src/presence.rs), for callers that can't wait on the +// engine, such as a renderer's first paint. The shared conformance corpus (fixtures/conformance.json, its `presence` +// cases) holds both to the same answers; prefer `ProjectionEngine.presence` where it's at hand. +import type {Extraction} from './index.js' + +/** What is known of one extraction's subject: reported, inferred or `unknown`. */ +export type SidePresence = 'present' | 'absent' | 'unknown' + +/** + * What a pair's subject did: `added` (absent before, present after), `removed` (present before, absent after), + * `absent` (on both sides), `present` (on both sides), or `unknown` when either side's presence is. + */ +export type PresenceTransition = 'added' | 'removed' | 'absent' | 'present' | 'unknown' + +/** One extraction's presence, and whether it was inferred rather than reported. */ +export interface ExtractionPresence { + presence: SidePresence + inferred: boolean +} + +/** + * A pair's presence (`ProjectionEngine.presence`, `presenceChange`): each side's and what the change did to the + * subject. `inferred` is true when either side's presence was inferred rather than reported. + */ +export interface PresenceChange { + before: SidePresence + after: SidePresence + change: PresenceTransition + inferred: boolean +} + +/** What presence reads of an extraction: a whole `Extraction` will do. */ +export type PresenceSide = Partial> + +/** + * One extraction's presence. A reported `presence` is taken as written. Omitted, it isn't reported, which is unknown, + * never present; it is inferred `present` when the extraction has items (an absent one can't), and `absent` when it + * has none and names missing inputs (the legacy reading, which v1 removes by requiring `presence`). + */ +export function extractionPresence(extraction: PresenceSide): ExtractionPresence { + const {presence} = extraction + if (presence === 'present' || presence === 'absent') return {presence, inferred: false} + if ((extraction.entities?.length ?? 0) > 0 || (extraction.relationships?.length ?? 0) > 0) return {presence: 'present', inferred: true} + if ((extraction.missingInputs?.length ?? 0) > 0) return {presence: 'absent', inferred: true} + return {presence: 'unknown', inferred: false} +} + +/** What the change between `before` and `after` did to their subject, from each side's `extractionPresence`. */ +export function presenceChange(before: PresenceSide, after: PresenceSide): PresenceChange { + const [first, second] = [extractionPresence(before), extractionPresence(after)] + const pair = `${first.presence}/${second.presence}` + const change: PresenceTransition = + pair === 'absent/present' + ? 'added' + : pair === 'present/absent' + ? 'removed' + : pair === 'absent/absent' + ? 'absent' + : pair === 'present/present' + ? 'present' + : 'unknown' + return {before: first.presence, after: second.presence, change, inferred: first.inferred || second.inferred} +} diff --git a/packages/schemas/src/repository/fixtures.ts b/packages/schemas/src/repository/fixtures.ts index 6a1acb0f1..e4e8fd542 100644 --- a/packages/schemas/src/repository/fixtures.ts +++ b/packages/schemas/src/repository/fixtures.ts @@ -59,7 +59,7 @@ export const ConformanceSchema = Closed({ request: Type.Object( { version: Type.Literal(0), - operation: Type.Enum(['decode', 'normalize', 'canonicalize', 'pair', 'vary', 'review', 'validate-comparison']), + operation: Type.Enum(['decode', 'normalize', 'canonicalize', 'pair', 'presence', 'vary', 'review', 'validate-comparison']), }, {description: "An engine request; the other fields are the operation's."}, ), @@ -82,8 +82,10 @@ export const ConformanceSchema = Closed({ /** * `packages/schemas/fixtures/extractor-helpers.json`: the cases the Python and Node extractor helpers must agree on. - * Each reads `stdin` (deliberately any JSON, valid requests or not) or `stdinText`, then reads `accessors` or calls - * result() with `result`, and expects `expected`, an `error` or a message starting with `errorStartsWith`. + * Each reads `stdin` (deliberately any JSON, valid requests or not) or `stdinText`, with `files` written to a fresh + * `repository.root`, then reads `accessors`, calls the request's methods in `checks` (each `[name, argument]`) and + * calls result() with `result`, and expects `expected` (the checks' values without a `result`), an `error` or a + * message starting with `errorStartsWith`. */ export const ExtractorHelpersSchema = Closed({ version: Type.Literal(0), @@ -99,7 +101,23 @@ export const ExtractorHelpersSchema = Closed({ Type.Union([ Type.Object({accessors: Type.Array(Type.String({pattern: '^[a-zA-Z][a-zA-Z0-9]*$'}), {minItems: 1})}), Type.Object({result: Type.Unknown()}, {required: ['result']}), + Type.Object( + { + checks: Type.Array( + // A pair, as JSON Schema 2020-12 writes one: the method's name and its argument. + Type.Unsafe<[string, unknown]>({ + type: 'array', + prefixItems: [{type: 'string', pattern: '^[a-zA-Z][a-zA-Z0-9]*$'}, {}], + items: false, + minItems: 2, + }), + {minItems: 1}, + ), + }, + {required: ['checks']}, + ), ]), + Type.Object({files: Type.Optional(Type.Array(Type.String({minLength: 1}), {minItems: 1}))}), Type.Union([ Type.Object({expected: Type.Unknown()}, {required: ['expected']}), Type.Object({error: Text}), diff --git a/packages/schemas/src/typebox/extraction.ts b/packages/schemas/src/typebox/extraction.ts index b76740986..6b756b2b4 100644 --- a/packages/schemas/src/typebox/extraction.ts +++ b/packages/schemas/src/typebox/extraction.ts @@ -181,8 +181,24 @@ export const ExtractionSchema = define( "Declared inputs (repository-relative files, folders or globs) that don't exist at the examined revision. The extraction describes the revision without them, so a comparison shows their contents as added or removed, with a notice. Part of the digest.", }), ), + presence: Type.Optional( + Type.Union([Type.Literal('present'), Type.Literal('absent')], { + description: + 'Whether what the projection describes (its subject: a workflow, a manifest, a schema file) exists at the examined revision. ' + + "`present`: it does, though it may be empty. `absent`: it doesn't (for example a workflow the revision predates), so the " + + 'extraction has no entities or relationships and `missingInputs` names what is missing. Omitted: not reported, which is ' + + 'unknown, never present; v1 will require it. Part of the digest when written.', + }), + ), metadata: Type.Optional(Data), }, - {description: 'One aspect of the code at one revision, as produced by an extractor on stdout.'}, + { + description: 'One aspect of the code at one revision, as produced by an extractor on stdout.', + if: {properties: {presence: {const: 'absent'}}, required: ['presence']}, + then: { + properties: {entities: {maxItems: 0}, relationships: {maxItems: 0}, missingInputs: {minItems: 1}}, + required: ['missingInputs'], + }, + }, ), ) diff --git a/packages/schemas/test/contracts.test.mjs b/packages/schemas/test/contracts.test.mjs index 8a0e629dc..e438db097 100644 --- a/packages/schemas/test/contracts.test.mjs +++ b/packages/schemas/test/contracts.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict' import {readFileSync} from 'node:fs' import {test} from 'node:test' -import {domainSchemas, protocolVersion} from '../dist/index.js' +import {domainSchemas, extractionPresence, presenceChange, protocolVersion} from '../dist/index.js' test('the public contract has seven domain schemas and no extractor catalog dependency', () => { assert.equal(protocolVersion, 0) @@ -32,9 +32,19 @@ test('the shared native/Wasm conformance corpus covers raw input, comparison int assert.ok(corpus.comparisons.some(item => item.expected?.changes.some(change => change.correspondence === 'split'))) assert.ok(corpus.comparisons.some(item => item.expectError === 'ambiguous-correspondence')) assert.ok(corpus.cases.some(item => item.request.operation === 'vary' && item.expectedResult)) + assert.ok(corpus.cases.some(item => item.request.operation === 'presence' && item.expectedResult?.change === 'added')) assert.ok(corpus.comparisons.some(item => item.expected?.variation)) for (const item of corpus.cases) assert.equal(item.request.version, 0) for (const item of corpus.comparisons) { for (const side of [item.before, item.after]) assert.equal(side.protocolVersion, 0) } }) + +// The TypeScript mirror of the engine's presence rule gives the engine's answer on every valid case of the shared corpus. +test('presenceChange mirrors the engine on the shared corpus', () => { + const corpus = JSON.parse(readFileSync(new URL('../fixtures/conformance.json', import.meta.url), 'utf8')) + const cases = corpus.cases.filter(item => item.request.operation === 'presence' && item.expectedResult) + assert.ok(cases.length >= 8) + for (const {id, request, expectedResult} of cases) assert.deepEqual(presenceChange(request.before, request.after), expectedResult, id) + assert.deepEqual(extractionPresence({}), {presence: 'unknown', inferred: false}) +}) diff --git a/packages/sdk/src/extractor/request.ts b/packages/sdk/src/extractor/request.ts index 800779ab7..d1e3880a1 100644 --- a/packages/sdk/src/extractor/request.ts +++ b/packages/sdk/src/extractor/request.ts @@ -9,6 +9,7 @@ import {isatty} from 'node:tty' import type {Definition, Extraction, ExtractorRequest} from '@githubnext/projections-schemas' import {quoted} from './messages.ts' import {PROTOCOL_VERSION} from './result.ts' +import {anchorName, byBytes, globExpression, recordAnchor} from './subject.ts' /** The project's directory under `directory`, as Python's `os.path.join` makes it, so both helpers agree. */ function within(directory: string, project: string): string { @@ -46,11 +47,6 @@ function listed(directory: string): string[] { }) } -/** UTF-8 byte order, as the Rust SDK and Python sort paths. */ -function byBytes(a: string, b: string): number { - return Buffer.compare(Buffer.from(a), Buffer.from(b)) -} - /** * The extractor request: the protocol's JSON object, with accessors. `request.repository.root` and the rest of the * protocol still work; `JSON.stringify(request)` writes the request as it came. @@ -58,6 +54,7 @@ function byBytes(a: string, b: string): number { export class Request { readonly #read: () => ExtractorRequest #value: ExtractorRequest | undefined + #files: string[] | undefined /** The request `value`; without one, the request on stdin, read the first time it is used. */ constructor(value?: ExtractorRequest) { @@ -137,6 +134,47 @@ export class Request { return [...new Set(files)].toSorted(byBytes) } + /** `files()`, listed once for the subject checks. */ + #listing(): string[] { + this.#files ??= this.files() + return this.#files + } + + /** + * Whether `path`, an anchor of what the projection describes (its subject: a workflow, a manifest, a schema file), + * is one of the project's `files()` or a folder holding some. One that isn't is recorded as a missing input, and + * `result()` reports the subject's `presence`: `absent` when no anchor checked exists (the extraction must then have + * no items), else `present`. Don't check inputs whose absence leaves the subject in place this way. + */ + subjectExists(path: string): boolean { + const name = anchorName(path) + // As the Rust SDK does, an anchor outside a declared scope is an error, not absence: the revision's files there aren't listed. + const scope = this.repository.scope + const repositoryPath = this.project ? `${this.project}/${name}` : name + if (name && scope && !scope.some(entry => repositoryPath === entry || repositoryPath.startsWith(`${entry}/`))) { + throw new RangeError( + `The anchor ${quoted(repositoryPath)} is outside the declared scope (${scope.join(', ')}); declare it in the definition's scope`, + ) + } + const files = this.#listing() + const exists = !name || files.some(file => file === name || file.startsWith(`${name}/`)) + recordAnchor(name, exists) + return exists + } + + /** + * `subjectExists()` for a glob anchor: whether `pattern` (`*` within a folder, `**` across folders, `?` one + * character) matches one of the project's `files()`. One that matches none is recorded as a missing input. + */ + subjectMatches(pattern: string): boolean { + const name = anchorName(pattern, {glob: true}) + const files = this.#listing() + const expression = globExpression(name) + const matches = files.some(file => expression.test(file)) + recordAnchor(name, matches) + return matches + } + /** The project's directory where its dependencies (`node_modules`, a virtualenv) are installed, if anywhere. */ get checkout(): string | undefined { const checkout = this.repository.checkout diff --git a/packages/sdk/src/extractor/result.ts b/packages/sdk/src/extractor/result.ts index c033fa3bd..2a3f5db73 100644 --- a/packages/sdk/src/extractor/result.ts +++ b/packages/sdk/src/extractor/result.ts @@ -2,6 +2,7 @@ // entities and relationships given as lists or keyed by ID, sorted in the Engine's order and checked for basic shape. import type {Entity, Extraction, Relationship} from '@githubnext/projections-schemas' import {article, described, isObject, quoted} from './messages.ts' +import {withSubject} from './subject.ts' /** The extractor protocol's version, of requests and extractions. */ export const PROTOCOL_VERSION = 0 @@ -22,7 +23,7 @@ export interface ExtractionFields extends Partial | undefined } -const optionalFields = new Set(['metadata', 'missingInputs', 'vocabularies', 'volatile']) +const optionalFields = new Set(['metadata', 'missingInputs', 'presence', 'vocabularies', 'volatile']) const requiredFields = {entities: ['kind', 'label'], relationships: ['kind', 'from', 'to']} as const const singular = {entities: 'entity', relationships: 'relationship'} as const @@ -63,7 +64,9 @@ function listed(items: unknown, field: 'entities' | 'relationships'): Record()} + +/** + * An anchor as the extraction names it: without a leading `./` or a trailing `/`; `""` for the project itself, which + * only a path anchor (`glob: false`) may name. + */ +export function anchorName(anchor: unknown, {glob = false} = {}): string { + const invalid = () => new TypeError(`An anchor of the subject is a nonempty project-relative path or glob, not ${quoted(anchor)}`) + if (typeof anchor !== 'string' || !anchor.trim()) throw invalid() + if (anchor.startsWith('/') || anchor.split('/').includes('..')) { + throw new RangeError(`The anchor ${quoted(anchor)} isn't within the project; name it relative to the project`) + } + let start = 0 + while (anchor.startsWith('./', start)) start += 2 + let end = anchor.length + while (end > start && anchor[end - 1] === '/') end-- + const name = anchor.slice(start, end) + if (name === '.' || !name) { + if (glob) throw invalid() + return '' + } + return name +} + +/** Records that the anchor `name` of the subject exists, or doesn't. */ +export function recordAnchor(name: string, exists: boolean): void { + subject.checked = true + subject.found ||= exists + if (!exists) subject.missing.add(name) +} + +/** `pattern`, in the Rust SDK's glob grammar: `*` within a segment, `**` across them, `**\/` any folders, `?` one character. */ +export function globExpression(pattern: string): RegExp { + let source = '^' + for (let index = 0; index < pattern.length; index++) { + const character = pattern.charAt(index) + if (character === '*' && pattern[index + 1] === '*') { + index++ + if (pattern[index + 1] === '/') { + index++ + source += '(?:.*/)?' + } else source += '.*' + } else if (character === '*') source += '[^/]*' + else if (character === '?') source += '[^/]' + else source += character.replace(/[\\^$.*+?()[\]{}|/]/gu, '\\$&') + } + return new RegExp(`${source}$`, 'u') +} + +/** + * `document` with what the extractor found of its subject: the anchors it lacks added to `missingInputs`, and, when it + * checked any and `document` doesn't report `presence` itself, `presence`: `absent` when none exists, else `present`. + * Fails when none exists but `document` has items: an absent subject has none. + */ +export function withSubject(document: Record): Record { + if (subject.missing.size) { + const given = document.missingInputs + if (given === undefined || Array.isArray(given)) { + document.missingInputs = [...new Set([...((given as string[] | undefined) ?? []), ...subject.missing])].toSorted(byBytes) + } + } + if (subject.checked && document.presence === undefined) { + const items = [document.entities, document.relationships].some(list => Array.isArray(list) && list.length > 0) + if (!subject.found && items) { + throw new Error( + `None of the extractor's subject exists at the revision (${[...subject.missing].toSorted(byBytes).join(', ')}), ` + + 'but its extraction has items; return none when its subject is absent', + ) + } + document.presence = subject.found ? 'present' : 'absent' + } + return document +}