<pblock label="Plan artifact repair" kind="repair">
Plan Artifact Repair
Drydock accepted the Plan response shape but rejected the emitted Blueprint artifact(s) below. Repair only the deterministic defect. Preserve all unrelated content, contracts, headings, decisions, and acceptance assertions byte-for-byte where possible. Preserve valid assertions and the required behavior coverage. Keep a supplied-suite gate as a suite gate; never add vacuous assertions to satisfy a count. Every DECISIONS.json is the sole decision disclosure surface; do not emit Markdown question sections. Each criterion is an isolated script: import or assign every name inside that criterion, including Decimal and rounding constants. Declare every external import and transport inside its AC block. Preserve published text without converting it into an arithmetic oracle. Derive expected row order from fixture data and the declared sort keys, including ties. Server-start criteria use bounded endpoint/port readiness probes and retain diagnostics. For a selection-probe defect, preserve the product, corpus path, selected scope and assertions. Author runner arguments as string literals or literal string bindings; canonical os.path.abspath("literal-path") with import os is also supported. Avoid getcwd f-strings, dynamic imports and runtime argument construction. Use only listing flags and count formats the supplied runner implements; never remove the probe.
Emit each artifact below in exactly this form, and emit no other text:
=== BEGIN ARTIFACT <FILENAME> === <the complete file body> === END ARTIFACT ===
The filename appears once, in the opening delimiter. The closing delimiter is the constant token above and never carries a name. Before sending, count opening and closing artifact lines: the counts must match. Finish every body before writing its complete closing line; reserve room for it. The final nonblank line of the response is exactly '=== END ARTIFACT ===', including all trailing equals signs.
Emit exactly one such block for each of: FEATURE-Assignment.md, FEATURE-Bindings.md, FEATURE-CollectionBuiltins.md, FEATURE-Collections.md, FEATURE-Command.md.
Repair pass: 3
Deterministic validation defect: FEATURE-Assignment.md [assignment-conformance]: line 7: sources/run_conformance.py --select '^(?:\\.message = \\"goodbye\\"|\\.foo = \\.bar|\\.foo \\|= \\.\\+1|setpath\\(\\[-1\\]; 1\\)|map\\(getpath\\(\\[2\\]\\)\\), map\\(setpath\\(\\[2\\]; 42\\)\\), map\\(delpaths\\(\\[\\[2\\]\\]\\)\\))$' selects a subset of a staged corpus: Probe: 'JQ=./jq python3 sources/run_conformance.py --select \'^(?:\\.message = "goodbye"|\\.foo = \\.bar|\\.foo \\|= \\.\\+1|setpath\\(\\[-1\\]; 1\\)|map\\(getpath\\(\\[2\\]\\)\\), map\\(setpath\\(\\[2\\]; 42\\)\\), map\\(delpaths\\(\\[\\[2\\]\\]\\)\\))$\' --json' is empty or not a plain flag literal FEATURE-Bindings.md [bindings-corpus]: line 7: sources/run_conformance.py --select '^1 as \\$x \\| 2 as \\$y|^1 as \\$x \\| \\[\\$x|^def f: \\(1000,2000\\); f$|^def a: 0; \\. \\| a$' selects a subset of a staged corpus: Probe: "JQ=./jq python3 sources/run_conformance.py --select '^1 as \\$x \\| 2 as \\$y|^1 as \\$x \\| \\[\\$x|^def f: \\(1000,2000\\); f$|^def a: 0; \\. \\| a$' --json" is empty or not a plain flag literal FEATURE-CollectionBuiltins.md [collection-builtins-conformance]: line 7: sources/run_conformance.py --select '^(?:sort|unique|flatten|flatten\\(0\\)|flatten\\(2\\)|transpose|to_entries|from_entries|map\\(has\\(2\\)\\)|map\\(keys\\)|map_values\\(\\.\\+1\\)|contains\\(\\"bar\\"\\))$' selects a subset of a staged corpus: Probe: 'JQ=./jq python3 sources/run_conformance.py --select \'^(?:sort|unique|flatten|flatten\\(0\\)|flatten\\(2\\)|transpose|to_entries|from_entries|map\\(has\\(2\\)\\)|map\\(keys\\)|map_values\\(\\.\\+1\\)|contains\\("bar"\\))$\' --json' is empty or not a plain flag literal FEATURE-Collections.md [collections-corpus]: line 7: sources/run_conformance.py --select '^\\{a: 1\\}$|^\\.foo$|^\\.\\[\\]$|^\\[\\.\\]$|^\\[\\{\\}\\]$' selects a subset of a staged corpus: Probe: "JQ=./jq python3 sources/run_conformance.py --select '^\\{a: 1\\}$|^\\.foo$|^\\.\\[\\]$|^\\[\\.\\]$|^\\[\\{\\}\\]$' --json" is empty or not a plain flag literal FEATURE-Command.md [command-corpus]: line 7: sources/run_conformance.py --select '^\\.$' selects a subset of a staged corpus: Probe: "JQ=./jq python3 sources/run_conformance.py --select '^\\.$' --json" is empty or not a plain flag literal FEATURE-Assignment.md [assignment-conformance]: story assignment is not the terminal story (terminal-verification) and its acceptance executes the authoritative runner sources/run_conformance.py. Gate this story on its own declared behavior, or invoke the runner in list mode, which enumerates the suite without running a case. FEATURE-Bindings.md [bindings-corpus]: story bindings is not the terminal story (terminal-verification) and its acceptance executes the authoritative runner sources/run_conformance.py. Gate this story on its own declared behavior, or invoke the runner in list mode, which enumerates the suite without running a case. FEATURE-CollectionBuiltins.md [collection-builtins-conformance]: story collection-builtins is not the terminal story (terminal-verification) and its acceptance executes the authoritative runner sources/run_conformance.py. Gate this story on its own declared behavior, or invoke the runner in list mode, which enumerates the suite without running a case. FEATURE-Collections.md [collections-corpus]: story constructors is not the terminal story (terminal-verification) and its acceptance executes the authoritative runner sources/run_conformance.py. Gate this story on its own declared behavior, or invoke the runner in list mode, which enumerates the suite without running a case. FEATURE-Command.md [command-corpus]: story cli is not the terminal story (terminal-verification) and its acceptance executes the authoritative runner sources/run_conformance.py. Gate this story on its own declared behavior, or invoke the runner in list mode, which enumerates the suite without running a case.
Normative Compass sections. They bind every assertion you write or retain, including one you add to satisfy the defect above.
Constraints
- Implement in Python using only the standard library.
- Provide an executable named
jqat the application root, invoked as./jq -c '<program>'. -cis the only option exercised. No other command-line option is required.- Run without network access, package installation, or external runtime dependencies.
- Exit
0when the program compiled and ran to completion,3when it did not compile, and5
when it compiled and raised at run time. The harness grades on this distinction.
- Diagnostics go to standard error and are never compared.
Guardrails
- Do not shell out to a system
jqexecutable. - Do not use a third-party jq implementation or binding.
- Do not modify, rewrite, trim, regenerate, or substitute any file under
sources/. Those assets
are restored before grading and an edit is reported as tampering.
- Preserve generator ordering, multiplicity, backtracking, and partial-output runtime behavior.
- Keep compile failures distinct from runtime failures using exit codes 3 and 5.
Verification Protocol
This section is normative. It governs which story may invoke the supplied harness, and how.
Invoking the harness
sources/run_conformance.py requires the environment variable JQ, the command that runs the candidate implementation. Without it the harness exits 2 on its own usage code, which is a harness fault and never a verdict about the interpreter. Every invocation, in every acceptance criterion and every developer command, supplies it:
JQ="$PWD/jq" python3 sources/run_conformance.py # whole corpus, the scored run
JQ="$PWD/jq" python3 sources/run_conformance.py --select 'reduce' # run one construct for real
Those two commands are the only ways this build runs the harness. They are specified verbatim below under The two harness invocations, together with the flag this build forbids.
sources/ is read only. No story edits, patches, or regenerates sources/run_conformance.py, sources/jq.test, or sources/exclusions.txt; a harness defect is reported, not repaired in place. A story that needs to experiment with the harness works on a copy outside sources/, and every acceptance criterion invokes the original sources/run_conformance.py.
An acceptance criterion written in Python supplies it by extending the inherited environment, never by replacing it:
env={**os.environ, "JQ": str(build_dir / "jq")}
env={"JQ": ...} alone leaves the child with no PATH, so nothing it invokes resolves and the criterion is false at every level of implementation quality.
sources/full_test.sh sets JQ itself for the runner it wraps and therefore takes no environment from its caller.
The harness reserves exit 2 for its own faults — a missing corpus, an unset JQ, a stale exclusion list. Exit 2 never means the interpreter is wrong.
The summary line is:
jq conformance: NNN passed, N failed, N errored, N skipped (corpus jq.test @ jq-1.8.2)
The two harness invocations
An acceptance criterion that runs sources/run_conformance.py uses one of these two commands. No criterion in this build passes any other flag to the harness.
| Story kind | Command | Executes cases? | Asserts |
|---|---|---|---|
| Every behavioral story | --select <regex> --json | Yes, the selected slice | exit 0, zero fail, zero error, non-zero case count |
| Terminal story (once, last) | sh sources/full_test.sh | Yes, all of them | exit 0 |
The staging story does not appear in this table. It does not run the harness at all; see The staging story below.
--list is never run
sources/run_conformance.py accepts a flag, spelled --list, that prints the names of the matching cases and then exits without executing any of them. sources/INSTRUCTIONS.md, the file header, and --help all document it.
This build never runs it. Not in an acceptance criterion, not in a story, not in a script, not in a command typed by a build agent, not while developing and not while verifying. The string --list does not appear anywhere in this project's output. If you have written it, that line is wrong — delete it and use one of the two commands above.
A Drydock build is headless. There is no one watching the output, so a mode whose entire purpose is to print something for a person to read has no reader and no reason to run.
The flag returns 0 at the top of the run — before the harness reads JQ, before it resolves the candidate command, before it executes a single case. A criterion built on it passes when jq is an empty file, when jq does not exist, and when the story it gates was never written. It is not a weak proof, not a partial proof, and not an acceptable proof for staging, for scaffolding, or for an early story whose implementation is incomplete. It is not a proof. Thirty-six criteria in one earlier plan of this project used it, every one of them reported green, and it cost three days.
If you are writing a criterion and reaching for that flag, the reason is always the same: the story's code does not exist yet and you want a command that will not fail. That is the definition of a criterion that proves nothing. Write the --select ... --json form instead and let it be red until the story makes it green. A criterion is supposed to fail before its story is built.
The same prohibition covers any other flag whose effect is to not execute the cases — enumeration, dry-run, validation, or help. If a flag's documented purpose is "run nothing", it has no place in an acceptance criterion.
Behavioral criterion — copy this, changing only SELECT
import json
import os
import subprocess
import sys
SELECT = r"reduce"
result = subprocess.run(
[sys.executable, "sources/run_conformance.py", "--select", SELECT, "--json"],
capture_output=True,
text=True,
env={**os.environ, "JQ": f"{os.getcwd()}/jq"},
)
print(result.stdout)
print(result.stderr, file=sys.stderr)
report = json.loads(result.stdout)
tally = report["summary"]
assert sum(tally.values()) > 0, f"selector matched no case: {SELECT}"
assert tally["fail"] == 0 and tally["error"] == 0, tally
assert result.returncode == 0, result.returncode
Three assertions, and all three are required.
- The selector matched something.
--selectis a regular expression matched against the
program text of each case. A selector that matches nothing yields zero cases, zero failures, and exit 0 — green, and worth nothing. Alternations naming ideas rather than syntax (closure, recursive, optional) match no jq program and are the common way to write one by accident. Select on syntax the corpus actually contains: reduce, foreach, def, as \$, try, //, path(.
- No case failed or errored. Read off the parsed JSON tally, not off any printed line.
- The exit status is
0. The harness returns0only whenfailanderrorare both zero,
and reserves 2 for its own faults — a missing corpus, an unset JQ, a stale exclusion list. Exit 2 is never a verdict about the interpreter.
--json writes the report and nothing else to stdout, so json.loads(result.stdout) is total. Do not assert against the human summary line, and do not grep stdout for passed or failed.
The terminal story
The terminal story is the last story in the build order: the one on which every other story is a transitive dependency, and after which no further story runs. It is a verification story. Its job is not to add capability but to prove that the capability every preceding story delivered is present, together, at the end of the build.
The terminal story of this project runs sh sources/full_test.sh, asserts returncode == 0, prints the captured stdout and stderr so a failure is diagnosable from the evidence alone, and carries the Sea Trial. It is the only story permitted to run the whole corpus.
A story is not terminal because its name contains "verify", because it is a test harness, or because it stages the test assets. Staging the corpus is foundational work that happens early; running the corpus is terminal work that happens last. Do not place a whole-corpus gate on a story that cannot yet run it — it fails vacuously and teaches nothing.
Scope of every other story
Every non-terminal story is gated on its own declared behavior only, through --select against the constructs that story implements, and the criterion asserts the selected slice passes. A non-terminal story never invokes sources/full_test.sh and never runs the corpus unfiltered: a partial interpreter fails most of an authoritative corpus by construction, and its unimplemented cases exhaust the harness's per-case timeout rather than returning, so the unscoped run costs the most exactly where it teaches the least.
Regression across stories is not the responsibility of any story's criteria. Drydock re-runs every previously proven criterion after each block and attributes a criterion that was green and is now red to the block that broke it, so a criterion proven at story 2 and broken at story 6 fails story
- Do not author a mid-build story whose purpose is to re-run earlier stories' checks.
The staging story
The story that stages the conformance assets is gated on the assets being present, complete, and mutually consistent — not on a bare file-existence assertion, and not on the corpus running. It proves that in process, by importing the harness and calling its parsers directly. It never launches the harness, so the question of which flags to pass does not arise:
import sys
sys.path.insert(0, "sources")
import run_conformance as harness
EXPECTED_CASES = 550
EXPECTED_EXCLUSIONS = 13
cases = harness.parse_corpus(harness.CORPUS.read_text(encoding="utf-8"))
excluded = harness.apply_exclusions(cases, harness.parse_exclusions(harness.EXCLUSIONS))
assert len(cases) == EXPECTED_CASES, len(cases)
assert len(excluded) == EXPECTED_EXCLUSIONS, len(excluded)
This reads state rather than output: the harness module imports, the corpus parses into the expected number of cases, and every exclusion still matches a case — apply_exclusions raises on a stale entry, so a corpus and an exclusion list that have drifted apart fail here rather than silently skipping cases later.
It claims nothing about the interpreter, because at this point in the build there is nothing to claim. Every story that claims a construct works runs that construct through --select ... --json.
Original FEATURE-Assignment.md, in the same form your reply must use: === BEGIN ARTIFACT FEATURE-Assignment.md ===
FEATURE: Path Mutation
| Field | Value |
|---|---|
| Version | 20261028 V1 |
| Description | Update and delete jq values through path expressions. |
| Depends On | FEATURE-Paths.md |
| Provides | jq path mutation |
| Consumes | jq path lookup |
Purpose
Provide immutable path-based mutation through setpath, delpaths, del, and assignment expressions. Filters receive the original input value; mutation emits replacement values without changing other references to that input.
Behavior
setpath creates missing objects and arrays as required by a path. delpaths removes the supplied paths, and del derives those paths from its filter argument. Respect jq's array index, negative-index, slice, type, and depth rules, including errors and deletion of multiple array locations.
For plain =, evaluate the right side against the original input and emit a separate updated input for each right-side result. For |=, evaluate the update against each selected old value, use only its first result, and delete that path if it produces no result. Arithmetic and alternative updates follow their jq definitions, including the evaluation context of their operands. Path expressions retain generator order and invalid path expressions raise runtime errors.
Programmatic Acceptance
=== AC assignment-conformance ===
Intent: Path mutation and assignment cases execute with the jq output and error behavior specified by the corpus.
Suite: scoped
Requires: executable=python3; scope=test
Probe: JQ=./jq python3 sources/run_conformance.py --select '^(?:\.message = "goodbye"|\.foo = \.bar|\.foo \|= \.\+1|setpath\(\[-1\]; 1\)|map\(getpath\(\[2\]\)\), map\(setpath\(\[2\]; 42\)\), map\(delpaths\(\[\[2\]\]\)\))$' --json
import json import os import subprocess import sys
SELECT = r"^(?:\.message = \"goodbye\"|\.foo = \.bar|\.foo \|= \.\+1|setpath\(\[-1\]; 1\)|map\(getpath\(\[2\]\)\), map\(setpath\(\[2\]; 42\)\), map\(delpaths\(\[\[2\]\]\)\))$" result = subprocess.run( [sys.executable, "sources/run_conformance.py", "--select", SELECT, "--json"], capture_output=True, text=True, env={**os.environ, "JQ": os.path.abspath("jq")}, ) print(result.stdout) print(result.stderr, file=sys.stderr) report = json.loads(result.stdout) tally = report["summary"] assert sum(tally.values()) > 0, SELECT assert tally["fail"] == 0 and tally["error"] == 0, tally assert result.returncode == 0, result.returncode === END AC assignment-conformance ===
User Acceptance
- None.
Guardrails
- Do not mutate any file under
sources/. - Preserve output order, multiplicity, and partial output before runtime errors.
- Cross-feature corpus cases requiring later builtins remain covered by scoped integration.
=== END ARTIFACT ===
Original FEATURE-Bindings.md, in the same form your reply must use: === BEGIN ARTIFACT FEATURE-Bindings.md ===
FEATURE: Bindings and Functions
| Field | Value |
|---|---|
| Version | 20261028 V1 |
| Description | Provide lexical bindings, destructuring, and user-defined jq functions. |
| Depends On | FEATURE-Control.md |
| Provides | jq lexical bindings and functions |
| Consumes | jq conditional and error control |
Behavior
An as binding evaluates its source as a generator and runs the remaining expression once per result against the original input with lexical bindings in scope. Array and object patterns bind nested values, using null for missing elements or fields. Destructuring alternatives try subsequent patterns when binding or the downstream expression raises an error; variables absent from the successful pattern are null.
Function definitions are lexically scoped by name and arity, support shadowing and recursion, and capture their defining environment. Filter arguments remain filters evaluated with their invocation input; value parameters bind each argument result at the call site. Preserve backtracking and ordered multiplicity across function calls and returns. Reject undefined symbols and invalid patterns at compile time.
Programmatic Acceptance
=== AC bindings-corpus ===
Intent: Bindings and function definitions execute the selected corpus cases with lexical scope and generator semantics.
Suite: scoped
Requires: executable=python3; scope=test
Probe: JQ=./jq python3 sources/run_conformance.py --select '^1 as \$x \| 2 as \$y|^1 as \$x \| \[\$x|^def f: \(1000,2000\); f$|^def a: 0; \. \| a$' --json
import json import os import subprocess import sys
SELECT = r"^1 as \$x \| 2 as \$y|^1 as \$x \| \[\$x|^def f: \(1000,2000\); f$|^def a: 0; \. \| a$" result = subprocess.run( [sys.executable, "sources/run_conformance.py", "--select", SELECT, "--json"], capture_output=True, text=True, env={**os.environ, "JQ": os.path.abspath("jq")}, ) print(result.stdout) print(result.stderr, file=sys.stderr) report = json.loads(result.stdout) tally = report["summary"] print(f"{tally['pass']} passed, {tally['fail']} failed, {tally['error']} errored") assert sum(tally.values()) > 0 assert tally["fail"] == 0 and tally["error"] == 0, tally assert result.returncode == 0, result.returncode === END AC bindings-corpus ===
User Acceptance
- None.
Guardrails
- Preserve lexical scope, lazy evaluation, and generator ordering.
- Defer cases combining bindings with later capabilities to scoped integration.
=== END ARTIFACT ===
Original FEATURE-CollectionBuiltins.md, in the same form your reply must use: === BEGIN ARTIFACT FEATURE-CollectionBuiltins.md ===
FEATURE: Collection Builtins
| Field | Value |
|---|---|
| Version | 20261028 V1 |
| Description | Transform, compare, and organize jq arrays and objects. |
| Depends On | FEATURE-Conversion.md |
| Provides | jq collection builtins |
| Consumes | jq type and conversion builtins |
Purpose
Provide the collection filters described by the manual and the definitions in sources/builtin.jq.
Behavior
Implement map, map_values, select, type selectors, keys and membership operations, entries conversion, addition and containment, sorting, grouping, uniqueness, extrema, reverse, flatten, transpose, combinations, binary search, and related collection utilities exercised by the corpus.
map collects every result for every element. map_values uses the first update result and removes a value when the update is empty. Sorting and grouping use jq's total value ordering and evaluate filter keys as ordered streams. Containment recursively follows jq's array and object rules. Preserve argument Cartesian products, stable result order where specified, empty inputs, and jq errors and depth boundaries.
Programmatic Acceptance
=== AC collection-builtins-conformance ===
Intent: Collection transformations, ordering, membership, and containment pass their applicable corpus cases.
Suite: scoped
Requires: executable=python3; scope=test
Probe: JQ=./jq python3 sources/run_conformance.py --select '^(?:sort|unique|flatten|flatten\(0\)|flatten\(2\)|transpose|to_entries|from_entries|map\(has\(2\)\)|map\(keys\)|map_values\(\.\+1\)|contains\("bar"\))$' --json
import json import os import subprocess import sys
SELECT = r"^(?:sort|unique|flatten|flatten\(0\)|flatten\(2\)|transpose|to_entries|from_entries|map\(has\(2\)\)|map\(keys\)|map_values\(\.\+1\)|contains\(\"bar\"\))$" result = subprocess.run( [sys.executable, "sources/run_conformance.py", "--select", SELECT, "--json"], capture_output=True, text=True, env={**os.environ, "JQ": os.path.abspath("jq")}, ) print(result.stdout) print(result.stderr, file=sys.stderr) report = json.loads(result.stdout) tally = report["summary"] assert sum(tally.values()) > 0, SELECT assert tally["fail"] == 0 and tally["error"] == 0, tally assert result.returncode == 0, result.returncode === END AC collection-builtins-conformance ===
User Acceptance
- None.
Guardrails
- Do not mutate any file under
sources/. - Preserve jq value ordering and generator semantics rather than Python's default mixed-type ordering.
- Cross-feature cases requiring later builtins remain covered by scoped integration.
=== END ARTIFACT ===
Original FEATURE-Collections.md, in the same form your reply must use: === BEGIN ARTIFACT FEATURE-Collections.md ===
FEATURE: Collection Expressions
| Field | Value |
|---|---|
| Version | 20261028 V1 |
| Description | Construct, access, and iterate jq arrays and objects. |
| Depends On | FEATURE-GeneratorCore.md |
| Provides | jq collection expressions |
| Consumes | jq generator evaluation |
Behavior
Array construction collects every output of its enclosed filter into one array, including an empty array when the filter yields nothing. Object construction evaluates key and value expressions against the original input and emits combinations in generator order. Support identifier, string, expression, and variable key forms and the documented shorthand forms as their prerequisites become available.
Field access, computed indexing, iteration, and slices compose with other filters. Missing object fields and out-of-range array indices produce null; negative indices count from the end. Iteration yields array elements or object values in order. Slices use inclusive start and exclusive end, accept omitted and negative bounds, and operate on arrays and strings. Invalid operand types raise jq runtime errors.
Programmatic Acceptance
=== AC collections-corpus ===
Intent: Collection construction and access execute the selected corpus programs with the required output streams.
Suite: scoped
Requires: executable=python3; scope=test
Probe: JQ=./jq python3 sources/run_conformance.py --select '^\{a: 1\}$|^\.foo$|^\.\[\]$|^\[\.\]$|^\[\{\}\]$' --json
import json import os import subprocess import sys
SELECT = r"^\{a: 1\}$|^\.foo$|^\.\[\]$|^\[\.\]$|^\[\{\}\]$" result = subprocess.run( [sys.executable, "sources/run_conformance.py", "--select", SELECT, "--json"], capture_output=True, text=True, env={**os.environ, "JQ": os.path.abspath("jq")}, ) print(result.stdout) print(result.stderr, file=sys.stderr) report = json.loads(result.stdout) tally = report["summary"] print(f"{tally['pass']} passed, {tally['fail']} failed, {tally['error']} errored") assert sum(tally.values()) > 0 assert tally["fail"] == 0 and tally["error"] == 0, tally assert result.returncode == 0, result.returncode === END AC collections-corpus ===
User Acceptance
- None.
Guardrails
- Preserve ordered generator multiplicity and partial output on runtime errors.
- Use the supplied corpus unchanged; mixed cases requiring later capabilities belong to scoped integration.
=== END ARTIFACT ===
Original FEATURE-Command.md, in the same form your reply must use: === BEGIN ARTIFACT FEATURE-Command.md ===
FEATURE: Command Interface
| Field | Value |
|---|---|
| Version | 20261028 V1 |
| Description | Run jq filters on standard input through the root executable. |
| Depends On | FEATURE-SqlBuiltins.md |
| Provides | ./jq -c |
| Consumes | jq SQL-style builtins and inventory |
Purpose and behavior
Invoke the executable at the application root as ./jq -c '<program>'. Compile the supplied jq program, read JSON values from standard input, and evaluate the program on each input using the shared generator and input stream. Emit each produced value as compact JSON on its own standard-output line, preserving order and multiplicity.
Exit 0 when compilation and execution complete, 3 for a compile or static error, and 5 for a runtime error. Retain values emitted before a runtime error. Send diagnostics to standard error. Only -c is required.
Programmatic Acceptance
=== AC command-stream ===
Intent: The command returns each input unchanged in order as a compact JSON value.
Requires: executable=python3; scope=test
import json import subprocess import sys
values = [{"a": [1, 2]}, [3, 4]] payload = "\n".join(json.dumps(value) for value in values) + "\n" result = subprocess.run(["./jq", "-c", "."], input=payload, capture_output=True, text=True) print(result.stdout) print(result.stderr, file=sys.stderr) assert result.returncode == 0 assert [json.loads(line) for line in result.stdout.splitlines()] == values assert all(line == json.dumps(json.loads(line), separators=(",", ":")) for line in result.stdout.splitlines()) === END AC command-stream ===
=== AC command-errors ===
Intent: Compilation and runtime failures have distinct exit statuses, and prior output survives a runtime failure.
Requires: executable=python3; scope=test
import json import subprocess import sys
invalid = subprocess.run(["./jq", "-c", "{"], input="null", capture_output=True, text=True) print(invalid.stdout) print(invalid.stderr, file=sys.stderr) assert invalid.returncode == 3
value = 7 runtime = subprocess.run( ["./jq", "-c", "., error"], input=json.dumps(value), capture_output=True, text=True ) print(runtime.stdout) print(runtime.stderr, file=sys.stderr) assert runtime.returncode == 5 assert [json.loads(line) for line in runtime.stdout.splitlines()] == [value] === END AC command-errors ===
=== AC command-corpus ===
Intent: Identity programs execute successfully through the command and supplied corpus runner.
Suite: scoped
Requires: executable=python3; scope=test
Probe: JQ=./jq python3 sources/run_conformance.py --select '^\.$' --json
import json import os import subprocess import sys
SELECT = r"^\.$" result = subprocess.run( [sys.executable, "sources/run_conformance.py", "--select", SELECT, "--json"], capture_output=True, text=True, env={**os.environ, "JQ": os.path.abspath("jq")}, ) print(result.stdout) print(result.stderr, file=sys.stderr) report = json.loads(result.stdout) tally = report["summary"] print(f"{tally['pass']} passed, {tally['fail']} failed, {tally['error']} errored") assert sum(tally.values()) > 0, f"selector matched no case: {SELECT}" assert tally["fail"] == 0 and tally["error"] == 0, tally assert result.returncode == 0, result.returncode === END AC command-corpus ===
User Acceptance
- None.
Guardrails
- Implement in Python with only standard-library runtime dependencies.
- Do not shell out to system jq or use a third-party jq implementation.
- Do not modify staged source assets.
=== END ARTIFACT ===
Read-only runner contract: sources/run_conformance.py
#!/usr/bin/env python3
"""Run the upstream jq conformance corpus against a candidate implementation.
This is the scoring instrument. It is supplied, not authored: it is staged verbatim into the
build directory, hash-verified against the import, and restored before grading. Its exit status
is the acceptance verdict.
It is deliberately external to the implementation. Upstream jq grades itself, through its own
``--run-tests`` flag; a self-graded suite proves nothing here, so this runner re-implements the
corpus protocol and drives the candidate as a subprocess, one process per case.
Imported sources land in ``sources/`` inside the application directory, so this is normally
invoked as ``python3 sources/run_conformance.py`` from that directory.
Usage:
JQ=./jq python3 sources/run_conformance.py # full corpus, the scored run
JQ=./jq python3 sources/run_conformance.py -v # list passing cases too
JQ=./jq python3 sources/run_conformance.py --json # machine-readable report
JQ=./jq python3 sources/run_conformance.py --list # print cases, run nothing
JQ=./jq python3 sources/run_conformance.py --select 'reduce' # develop one construct
Environment:
JQ command that runs the candidate. Required -- this harness is language-neutral
and deliberately has no default implementation language.
Exit codes:
0 every case that ran passed
1 at least one case failed or errored
2 the harness could not run: bad usage, missing corpus, or a stale exclusion
"""
from __future__ import annotations
import argparse
import json
import os
import re
import shlex
import subprocess
import sys
from dataclasses import dataclass, field
from pathlib import Path
HERE = Path(__file__).resolve().parent
CORPUS = HERE / "jq.test"
EXCLUSIONS = HERE / "exclusions.txt"
#: A case that has not produced output in this long is not going to. jq's own suite runs the
#: whole corpus in under a second; anything near this bound is a runaway generator.
DEFAULT_TIMEOUT = 10.0
PASS, FAIL, ERROR, SKIP = "pass", "fail", "error", "skip"
#: jq's documented exit codes, which this kit's interface contract adopts. The distinction is
#: load-bearing: the corpus's %%FAIL cases are programs that must not compile, while an ordinary
#: case may legitimately raise at run time part-way through its output and still be correct.
EXIT_COMPILE_ERROR = 3
EXIT_RUNTIME_ERROR = 5
def split_lines(text: str) -> list[str]:
"""Split on newlines only.
``str.splitlines`` is Unicode-aware and also breaks on U+000B, U+000C, U+0085, U+2028, and
U+2029. The corpus contains cases whose expected output embeds those code points inside JSON
strings -- ``trim, ltrim, rtrim`` over the Unicode whitespace set is one -- and splitting
there shreds one JSON value into several, failing a correct implementation.
"""
lines = text.split("\n")
if lines and lines[-1] == "":
lines.pop()
return lines
@dataclass
class Case:
"""One corpus case: a program, an input, and what it must produce.
``expect_failure`` cases are the corpus's ``%%FAIL`` blocks. Upstream compares their
diagnostic text; this runner requires only that the candidate reject the program. The
expected strings are jq's exact C-implementation diagnostics, down to the caret art
underlining the offending token -- reproducing them is reverse-engineering an
implementation, not conforming to a specification. The text is parsed and reported so a
reader can see what upstream said, and is never compared.
"""
line: int
program: str
stdin: str = ""
expected: list[str] = field(default_factory=list)
expect_failure: bool = False
diagnostic: str = ""
@dataclass
class Result:
case: Case
status: str
detail: str = ""
actual: list[str] = field(default_factory=list)
return_code: int | None = None
stderr: str = ""
class HarnessError(Exception):
"""A fault in the kit or its invocation, never a fault in the candidate."""
# --------------------------------------------------------------------------------------------
# Corpus parsing
# --------------------------------------------------------------------------------------------
def parse_corpus(text: str) -> list[Case]:
"""Parse the jq test corpus.
The format is documented in the corpus's own header: cases are groups of lines separated by
blank lines; blank lines and lines starting with ``#`` are ignored. A case is a program
line, an input line, and then zero or more expected output lines. A case preceded by a
``%%FAIL`` or ``%%FAIL IGNORE MSG`` marker is a program line followed by the diagnostic
upstream jq emits, which may itself span several lines of source excerpt and caret art.
"""
cases: list[Case] = []
block: list[tuple[int, str]] = []
expect_failure = False
lines = split_lines(text)
def flush() -> None:
nonlocal block, expect_failure
if block:
cases.append(_case_from_block(block, expect_failure))
block = []
expect_failure = False
for number, raw in enumerate(lines, start=1):
stripped = raw.strip()
if not stripped:
flush()
continue
if raw.startswith("%%FAIL"):
flush()
expect_failure = True
continue
# A '#' comment closes nothing: upstream places section banners between cases, always
# with blank lines around them, and never inside a case.
if raw.lstrip().startswith("#") and not block:
continue
if raw.lstrip().startswith("#"):
continue
block.append((number, raw))
flush()
return cases
def _case_from_block(block: list[tuple[int, str]], expect_failure: bool) -> Case:
line, program = block[0]
if expect_failure:
diagnostic = "\n".join(text for _, text in block[1:])
return Case(line=line, program=program, expect_failure=True, diagnostic=diagnostic)
if len(block) < 2:
raise HarnessError(
f"{CORPUS.name}:{line}: case has a program but no input line; the corpus is malformed"
)
return Case(
line=line,
program=program,
stdin=block[1][1],
expected=[text for _, text in block[2:]],
)
# --------------------------------------------------------------------------------------------
# Exclusions
# --------------------------------------------------------------------------------------------
def parse_exclusions(path: Path) -> list[str]:
"""Read the declared exclusions: one verbatim program line per entry, ``#`` for reasons."""
if not path.is_file():
return []
return [
line
for line in split_lines(path.read_text(encoding="utf-8"))
if line.strip() and not line.lstrip().startswith("#")
]
def apply_exclusions(cases: list[Case], exclusions: list[str]) -> set[int]:
"""Return the corpus line numbers of excluded cases.
An exclusion that matches nothing is a hard error rather than a shrug. The corpus is pinned
by hash, so a stale exclusion means the pin moved without the exclusion list being revisited
-- and a silent no-op there would quietly re-admit a case the kit cannot run.
"""
by_program: dict[str, list[Case]] = {}
for case in cases:
by_program.setdefault(case.program, []).append(case)
excluded: set[int] = set()
stale: list[str] = []
for program in exclusions:
matched = by_program.get(program)
if not matched:
stale.append(program)
continue
excluded.update(case.line for case in matched)
if stale:
listed = "\n".join(f" {program}" for program in stale)
raise HarnessError(
f"{EXCLUSIONS.name}: these exclusions match no case in {CORPUS.name}:\n{listed}\n"
"The corpus and the exclusion list have drifted apart."
)
return excluded
# --------------------------------------------------------------------------------------------
# Comparison
# --------------------------------------------------------------------------------------------
def jv_equal(left: object, right: object) -> bool:
"""Compare two decoded JSON values the way jq's own ``jv_equal`` does.
Structural, not textual: ``1`` and ``1.0`` are the same jq value and the corpus relies on
that. Python's ``==`` almost does this, but it also equates ``True`` with ``1`` and
``False`` with ``0``, which jq does not; booleans are therefore matched by identity of type
before anything else.
"""
if isinstance(left, bool) or isinstance(right, bool):
return isinstance(left, bool) and isinstance(right, bool) and left is right
if isinstance(left, (int, float)) and isinstance(right, (int, float)):
return left == right
if isinstance(left, list) and isinstance(right, list):
return len(left) == len(right) and all(jv_equal(a, b) for a, b in zip(left, right))
if isinstance(left, dict) and isinstance(right, dict):
return left.keys() == right.keys() and all(jv_equal(left[k], right[k]) for k in left)
if type(left) is not type(right):
return False
return left == right
def _decode(line: str) -> tuple[bool, object]:
try:
return True, json.loads(line)
except ValueError:
return False, line
def outputs_match(expected: list[str], actual: list[str]) -> bool:
if len(expected) != len(actual):
return False
for want, got in zip(expected, actual):
want_ok, want_value = _decode(want)
got_ok, got_value = _decode(got)
if want_ok and got_ok:
if not jv_equal(want_value, got_value):
return False
elif want.strip() != got.strip():
return False
return True
# --------------------------------------------------------------------------------------------
# Execution
# --------------------------------------------------------------------------------------------
def run_case(case: Case, argv: list[str], timeout: float) -> Result:
try:
completed = subprocess.run(
[*argv, "-c", case.program],
input=case.stdin,
capture_output=True,
text=True,
timeout=timeout,
)
except subprocess.TimeoutExpired:
return Result(case, ERROR, detail=f"timed out after {timeout:g}s")
except OSError as exc:
raise HarnessError(f"cannot execute {shlex.join(argv)}: {exc}") from exc
actual = split_lines(completed.stdout)
stderr = completed.stderr.strip()
code = completed.returncode
first_diagnostic = split_lines(stderr)[0] if stderr else ""
if case.expect_failure:
# The corpus's %%FAIL cases are programs that must be rejected at compile time. Accepting
# one and then failing at run time is a different, wrong behaviour, so the compile-error
# code specifically -- not merely a non-zero exit -- is what passes here.
if code == EXIT_COMPILE_ERROR:
return Result(case, PASS, return_code=code, stderr=stderr)
detail = (
"program was accepted, but the corpus marks it %%FAIL"
if code == 0
else f"exited {code}; a rejected program must exit {EXIT_COMPILE_ERROR}"
)
return Result(case, FAIL, detail=detail, actual=actual, return_code=code, stderr=stderr)
if code == EXIT_COMPILE_ERROR:
return Result(
case,
FAIL,
detail=f"program did not compile: {first_diagnostic}",
actual=actual,
return_code=code,
stderr=stderr,
)
if code not in (0, EXIT_RUNTIME_ERROR):
# A runtime error is legitimate: several cases raise part-way through a generator and are
# judged on the outputs produced before the raise, exactly as upstream judges them. Any
# other non-zero status is the program failing in a way the contract does not describe.
return Result(
case,
FAIL,
detail=f"exited {code}: {first_diagnostic}",
actual=actual,
return_code=code,
stderr=stderr,
)
if not outputs_match(case.expected, actual):
return Result(
case,
FAIL,
detail="output mismatch",
actual=actual,
return_code=code,
stderr=stderr,
)
return Result(case, PASS, actual=actual, return_code=code, stderr=stderr)
# --------------------------------------------------------------------------------------------
# Reporting
# --------------------------------------------------------------------------------------------
def _render_failure(result: Result) -> str:
case = result.case
lines = [
f"FAIL {CORPUS.name}:{case.line} {result.detail}",
f" program: {case.program}",
]
if not case.expect_failure:
lines.append(f" input: {case.stdin}")
lines.append(f" expected: {case.expected if case.expected else '(no output)'}")
lines.append(f" actual: {result.actual if result.actual else '(no output)'}")
if result.stderr:
lines.append(f" stderr: {split_lines(result.stderr)[0]}")
return "\n".join(lines)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description="Run the upstream jq conformance corpus against a candidate implementation.",
)
parser.add_argument("--jq", default=None, help="candidate command (default: $JQ)")
parser.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT, help="seconds per case")
parser.add_argument("--json", action="store_true", help="machine-readable report")
parser.add_argument("-v", "--verbose", action="store_true", help="list passing cases too")
parser.add_argument("--list", action="store_true", help="print the cases and run nothing")
parser.add_argument(
"--select",
default=None,
metavar="REGEX",
help="run only cases whose program matches REGEX (development aid; the acceptance "
"gate always runs the whole corpus)",
)
args = parser.parse_args(argv)
try:
return _run(args)
except HarnessError as exc:
print(f"error: {exc}", file=sys.stderr)
return 2
def _run(args: argparse.Namespace) -> int:
if not CORPUS.is_file():
raise HarnessError(f"corpus not found at {CORPUS}")
cases = parse_corpus(CORPUS.read_text(encoding="utf-8"))
excluded = apply_exclusions(cases, parse_exclusions(EXCLUSIONS))
selector = re.compile(args.select) if args.select else None
if selector is not None:
cases = [case for case in cases if selector.search(case.program)]
if args.list:
for case in cases:
mark = "skip" if case.line in excluded else "run "
print(f"{mark} {CORPUS.name}:{case.line} {case.program}")
print(f"\n{len(cases)} cases, {sum(1 for c in cases if c.line in excluded)} excluded")
return 0
command = args.jq or os.environ.get("JQ") or ""
if not command.strip():
raise HarnessError(
"JQ is not set; give the command that runs your implementation, e.g.\n"
' JQ="$PWD/jq" python3 sources/run_conformance.py'
)
jq_argv = shlex.split(command)
results: list[Result] = []
for case in cases:
if case.line in excluded:
results.append(Result(case, SKIP, detail="declared in exclusions.txt"))
continue
results.append(run_case(case, jq_argv, args.timeout))
tally = {status: sum(1 for r in results if r.status == status) for status in
(PASS, FAIL, ERROR, SKIP)}
summary = (
f"jq conformance: {tally[PASS]} passed, {tally[FAIL]} failed, "
f"{tally[ERROR]} errored, {tally[SKIP]} skipped "
f"(corpus {CORPUS.name} @ jq-1.8.2)"
)
if args.json:
print(json.dumps(
{
"candidate": jq_argv,
"corpus": CORPUS.name,
"summary": tally,
"cases": [
{
"line": r.case.line,
"program": r.case.program,
"status": r.status,
"detail": r.detail,
"expect_failure": r.case.expect_failure,
"expected": r.case.expected,
"actual": r.actual,
}
for r in results
if args.verbose or r.status != PASS
],
},
indent=2,
))
else:
for result in results:
if result.status in (FAIL, ERROR):
print(_render_failure(result))
elif args.verbose and result.status == PASS:
print(f"ok {CORPUS.name}:{result.case.line} {result.case.program}")
elif args.verbose and result.status == SKIP:
print(f"skip {CORPUS.name}:{result.case.line} {result.case.program}")
print(summary)
return 0 if tally[FAIL] == 0 and tally[ERROR] == 0 else 1
if __name__ == "__main__":
raise SystemExit(main())
</pblock>