Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions changelog.d/414.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
section: behaviour-changes
---

- **Built-in extractors report whether their subject is present, and their digests change once** (#414). Every built-in extraction now carries `presence`, `present` or `absent` ([presence](docs/contracts/extractions.md#presence)), so every built-in extraction digest changes once. Saved documents, caches and digests recorded by earlier versions won't match new ones for the same revision. An extraction whose subject doesn't exist at the revision, such as a workflow the revision predates, is `absent`, and a pull request that adds it shows it as added rather than as an empty extraction. Built-ins that describe the whole repository (`code-statistics`, `repository-map`, `terraform-modules`, `renderer-scenarios`) and `command-output` are always `present`.
- When a built-in discovers its files itself and finds none, its extraction is now absent instead of an error or a silent empty extraction. This covers `prisma-schema` with no `.prisma` files (previously an error), `rails-routes`, `rails-schema`, `nuget-dependencies`, `xcode-modules`, `tetragon-policies` with its default globs, and `github-agentic-workflows`. The extraction names the globs it looked for in `missingInputs`.
- `django-schema` is absent when the revision has no file that could be its settings module. `rust-public-api` is absent when no `Cargo.toml` declares the requested `package`. `go-public-api` is absent when none of the local package directories its `patterns` name exist.
- A `github-agentic-workflows` `paths` glob that matches no workflow is now listed in `missingInputs`, as `tetragon-policies` already does, so `projections check` reports it.
- **An empty selection is now an error**: `paths: []` in `tetragon-policies`, `routes: []` in `rails-routes`, `assetsPaths: []` or `projects: []` in `nuget-dependencies` and `projects: []` in `xcode-modules` fail with a message saying the input must name at least one file, where they used to return an empty extraction. Remove the input to discover the files, or list them.
- With `helm` or `kustomize` set and no `paths`, `tetragon-policies` no longer reads the default YAML globs when the chart or kustomization is missing, as its documentation says; the policy set is absent instead.
- **`github-agentic-workflows` rejects `paths: []`**, which can break an existing definition that sets it: extraction fails with "inputs.paths must name at least one glob" where it used to return an empty extraction. Remove `paths` to read the default `.github/workflows/*.md`, or list the globs that select your workflows.
2 changes: 1 addition & 1 deletion docs/builtins/extractors/go-public-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ repository. `projections explore` proposes the root module when there is a root

Source locations are always relative to the repository root, including for a
module below it. A revision without the module's `go.mod` (before it was added)
yields an empty API rather than failing.
yields an absent, empty API rather than failing.

Each importable package becomes a `package` entity, and each exported symbol
becomes a `constant`, `variable`, `function`, or `type`, with `method` entities
Expand Down
12 changes: 9 additions & 3 deletions docs/contracts/extractions.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,9 +171,15 @@ 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.
Built-in extractors write `presence` on every extraction, both values, so their
digests changed once when they started. A built-in that describes the whole
repository (`code-statistics`, `repository-map`, `terraform-modules`,
`renderer-scenarios`) or a command's output (`command-output`) is always
`present`. One that discovers its files when its inputs don't name them
(`prisma-schema`, `rails-routes`, `rails-schema`, `nuget-dependencies`,
`xcode-modules`, `tetragon-policies`, `github-agentic-workflows`) is `absent`
when it discovers none, and names the globs it looked for in `missingInputs`. In
`extraction/v1`, `presence` will be required, and the inference will go away.

## Volatile data

Expand Down
16 changes: 10 additions & 6 deletions docs/design/proposals/subject-presence.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# Proposal: subject presence

Status: **in progress**. Phase 1 (the contract: schema, Engine and SDK helpers)
is implemented; the other phases are proposals. Trigger:
and Phase 2 (built-in extractors write `presence`) are 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
Expand Down Expand Up @@ -184,14 +185,17 @@ shows every item as added.

- **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 1**: 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.
Built-in digests change once. Discovery that finds nothing (Prisma, Rails,
NuGet, Xcode, Tetragon and agentic-workflow globs) is absent rather than an
error or a silent empty extraction, and a Django settings module with no file
anywhere in the revision is absent.
- **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.
Expand Down
2 changes: 1 addition & 1 deletion packages/extractors/azure-what-if/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ fn extract(cx: &Context) -> Result<Value> {
let absent = json!({"status": "Succeeded", "changes": []});
let (result, template) = if inputs.get("whatIfJsonPath").is_some() {
let file = input(definition, "whatIfJsonPath", None)?;
if !cx.input_exists(file)? {
if !cx.subject_exists(file)? {
return infrastructure(&absent, None);
}
let template = match inputs.get("templateJsonPath") {
Expand Down
2 changes: 1 addition & 1 deletion packages/extractors/azure-what-if/src/native.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub(crate) fn native(root: &Path, d: &Value, cx: &Context) -> Result<Option<(Val
cx.require_trust()?;
let az = input(d, "azPath", Some("az"))?.to_owned();
let relative = input(d, "templateFile", None).context("azure-what-if needs whatIfJsonPath, or templateFile to run what-if")?;
if !cx.input_exists(relative)? {
if !cx.subject_exists(relative)? {
return Ok(None);
}
let template = path(root, relative, false, false)?;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,7 @@
"sourceConfidence": "authoritative",
"unmatchedTemplateDependencies": 0
},
"presence": "present",
"protocolVersion": 0,
"relationships": [
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,7 @@
"sourceConfidence": "authoritative",
"unmatchedTemplateDependencies": 0
},
"presence": "present",
"protocolVersion": 0,
"relationships": [
{
Expand Down
7 changes: 5 additions & 2 deletions packages/extractors/azure-what-if/tests/what_if.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
//! scenario.

use projections_extractor_azure_what_if::collect;
use projections_extractor_sdk::testing::{Process, golden};
use projections_extractor_sdk::testing::{self, Process, golden};
use serde_json::{Value, json};
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
Expand All @@ -27,7 +27,10 @@ fn id(path: &str) -> String {
fn extract(inputs: Value) -> anyhow::Result<Value> {
let root = fixtures();
let definition = json!({"id":"azure","extractor":"azure-what-if","inputs":inputs});
let extraction = collect(&Process::new(&root).context(&root, Value::clone(&definition)).with_files(vec![]))?;
let extraction = testing::extract(
&Process::new(&root).context(&root, Value::clone(&definition)).with_files(vec![]),
collect,
)?;
projections_engine::normalize(&extraction, "").unwrap();
Ok(extraction)
}
Expand Down
2 changes: 1 addition & 1 deletion packages/extractors/cargo-dependencies/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ fn cargo(root: &Path, d: &Value, cx: &Context) -> Result<Value> {
None => input(d, "manifestPath", Some("Cargo.toml"))?,
};
// A revision without the declared metadata or manifest (before it was added) has no packages.
if !cx.input_exists(declared)? {
if !cx.subject_exists(declared)? {
return Ok(extraction(
"graph/v0",
vec![],
Expand Down
4 changes: 4 additions & 0 deletions packages/extractors/catalog/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,7 @@ projections-extractor-xcode-modules = { path = "../xcode-modules" }
projections-extractor-typescript-public-api = { path = "../typescript-public-api" }
projections-extractor-workspace-dependencies = { path = "../workspace-dependencies" }
serde_json = { version = "1", features = ["float_roundtrip"] }

[dev-dependencies]
projections-extractor-sdk = { path = "../sdk", features = ["testing"] }
tempfile = "3"
145 changes: 145 additions & 0 deletions packages/extractors/catalog/tests/presence.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
//! Every built-in extractor reports its subject's `presence` on every path: absent
//! at a revision without what its inputs name, present for the repository-wide
//! ones, and in every golden extraction its own tests keep.

use projections_extractor_catalog::{IDS, collect};
use projections_extractor_sdk::testing::{Process, Runner};
use projections_extractor_sdk::{Output, normalize_extraction};
use serde_json::{Value, json};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;

/// Inputs naming what an empty revision lacks, and the presence expected there.
fn cases() -> Vec<(&'static str, Value, &'static str)> {
vec![
("workspace-dependencies", json!({}), "absent"),
("repository-map", json!({}), "present"),
("typescript-public-api", json!({"tsconfig": "tsconfig.json"}), "absent"),
("rust-public-api", json!({"rustdocJson": "target/doc/api.json"}), "absent"),
("go-public-api", json!({"module": "services/ledger"}), "absent"),
("swift-public-api", json!({"symbolGraphPath": "graphs"}), "absent"),
("cargo-dependencies", json!({}), "absent"),
("swift-package-dependencies", json!({}), "absent"),
("xcode-modules", json!({}), "absent"),
("nuget-dependencies", json!({}), "absent"),
("terraform-infrastructure", json!({"planJsonPath": "plan.json"}), "absent"),
("terraform-modules", json!({}), "present"),
("azure-what-if", json!({"whatIfJsonPath": "what-if.json"}), "absent"),
("github-actions-jobs", json!({"workflowPath": ".github/workflows/ci.yml"}), "absent"),
("github-agentic-workflows", json!({}), "absent"),
("tetragon-policies", json!({}), "absent"),
("dotnet-public-api", json!({"snapshot": "api.json"}), "absent"),
("dotnet-di", json!({"snapshot": "di.json"}), "absent"),
("nestjs-di", json!({"entry": "src/main.ts"}), "absent"),
("spring-di", json!({"project": "services/api"}), "absent"),
("openrewrite-data-tables", json!({"tables": "rewrite"}), "absent"),
("efcore-schema", json!({"snapshot": "model.json"}), "absent"),
("django-schema", json!({"settings": "shop.settings"}), "absent"),
("code-statistics", json!({}), "present"),
("prisma-schema", json!({}), "absent"),
("rails-schema", json!({}), "absent"),
("rails-routes", json!({}), "absent"),
("renderer-scenarios", json!({}), "present"),
("scip-file-references", json!({"index": "index.scip"}), "absent"),
(
"command-output",
json!({"commands": [{"id": "version", "label": "Version", "command": ["tool", "--version"]}]}),
"present",
),
]
}

#[test]
fn every_built_in_reports_presence_at_a_revision_without_its_subject() {
let cases = cases();
let covered: Vec<&str> = cases.iter().map(|(id, _, _)| *id).collect();
for id in IDS {
assert!(covered.contains(id), "add a case for built-in {id}");
}
let scratch = tempfile::tempdir().unwrap();
let root = scratch.path().canonicalize().unwrap();
// A revision with only an unrelated file; a tool that runs prints a line.
fs::write(root.join("NOTES.txt"), "nothing to describe\n").unwrap();
let runner: Arc<Runner> = Arc::new(|_, _| {
Ok(Output {
stdout: "1.0\n".into(),
stderr: String::new(),
})
});
let process = Process {
trusted: true,
checkout: root.clone(),
runner: Some(runner),
};
for (id, inputs, expected) in cases {
let cx = process.context(&root, json!({"id": "subject", "extractor": id, "inputs": inputs}));
let extraction = collect(id, &cx)
.and_then(|extraction| cx.finish(extraction))
.unwrap_or_else(|error| panic!("{id}: {error:#}"));
assert_eq!(extraction["presence"], expected, "{id}: {extraction}");
normalize_extraction(&extraction).unwrap_or_else(|error| panic!("{id}: {error:#}"));
}
}

fn goldens(directory: &Path, found: &mut Vec<PathBuf>) {
for entry in fs::read_dir(directory).unwrap() {
let path = entry.unwrap().path();
let name = path.file_name().unwrap().to_string_lossy().into_owned();
if path.is_dir() {
goldens(&path, found);
} else if name == "expected.json" || name.ends_with(".expected.json") {
found.push(path);
}
}
}

#[test]
fn every_golden_extraction_of_a_built_in_reports_presence() {
let extractors = Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap();
let mut files = vec![];
for id in IDS {
let tests = extractors.join(id).join("tests");
if tests.is_dir() {
goldens(&tests, &mut files);
}
}
let mut extractions = 0;
for file in &files {
let value: Value = serde_json::from_str(&fs::read_to_string(file).unwrap()).unwrap();
if value.get("protocolVersion").is_none() {
continue;
}
extractions += 1;
assert!(
matches!(value["presence"].as_str(), Some("present" | "absent")),
"{} doesn't report presence",
file.display()
);
}
assert!(extractions >= 30, "found only {extractions} golden extractions");
}

#[test]
fn an_empty_selection_is_an_error_rather_than_an_unreported_presence() {
let scratch = tempfile::tempdir().unwrap();
let root = scratch.path().canonicalize().unwrap();
fs::write(root.join("policy.yaml"), "kind: ConfigMap\n").unwrap();
let process = Process {
trusted: true,
checkout: root.clone(),
runner: None,
};
for (id, inputs) in [
("nuget-dependencies", json!({"assetsPaths": []})),
("nuget-dependencies", json!({"projects": []})),
("rails-routes", json!({"routes": []})),
("xcode-modules", json!({"projects": []})),
("tetragon-policies", json!({"paths": []})),
("github-agentic-workflows", json!({"paths": []})),
] {
let cx = process.context(&root, json!({"id": "subject", "extractor": id, "inputs": inputs}));
let error = collect(id, &cx).map_err(|error| format!("{error:#}")).unwrap_err();
assert!(error.contains("at least one"), "{id} {inputs}: {error}");
}
}
5 changes: 4 additions & 1 deletion packages/extractors/code-statistics/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,10 @@ pub fn requires_trust(_inputs: &Value) -> bool {
}

pub fn collect(cx: &Context) -> Result<Value> {
statistics(cx, cx.files()?, cx.definition())
let mut extraction = statistics(cx, cx.files()?, cx.definition())?;
// The repository is what it describes, so it is always present.
extraction["presence"] = json!("present");
Ok(extraction)
}

/// The language tokei assigns a path by filename or extension.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@
"unrecognized": 0
}
},
"presence": "present",
"protocolVersion": 0,
"relationships": [],
"schema": "metrics/v0"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,7 @@
"unrecognized": 2
}
},
"presence": "present",
"protocolVersion": 0,
"relationships": [],
"schema": "metrics/v0"
Expand Down
2 changes: 1 addition & 1 deletion packages/extractors/code-statistics/tests/golden.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ fn case(name: &str) -> Value {
.map(|text| serde_json::from_str(&text).unwrap())
.unwrap_or_else(|_| json!({}));
let definition = json!({"id":"statistics","extractor":"code-statistics","inputs":inputs});
let extraction = collect(&testing::context(&root, definition)).unwrap();
let extraction = testing::extract(&testing::context(&root, definition), collect).unwrap();
golden(&directory.join("expected.json"), &extraction);
extraction
}
Expand Down
7 changes: 5 additions & 2 deletions packages/extractors/command-output/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,14 @@ pub fn collect(cx: &Context) -> Result<Value> {
nodes.push(json!({"id":format!("output:{id}"),"kind":"output","label":label,
"data":{"text":output,"presentation":presentation},"confidence":"authoritative"}));
}
Ok(extraction(
let mut extraction = extraction(
"graph/v0",
nodes,
vec![],
Some(json!({"source":"CLI stdout",
"limitations":["Command output may depend on external state or tool versions; run in a pinned, trusted environment."]})),
))
);
// What the commands print is what it describes: always present, even when empty.
extraction["presence"] = json!("present");
Ok(extraction)
}
4 changes: 4 additions & 0 deletions packages/extractors/django-schema/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,7 @@ rust-version.workspace = true
anyhow = "1"
projections-extractor-sdk = { path = "../sdk" }
serde_json = { version = "1", features = ["float_roundtrip"] }

[dev-dependencies]
projections-extractor-sdk = { path = "../sdk", features = ["testing"] }
tempfile = "3"
Loading
Loading