Skip to content
Merged
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
6 changes: 4 additions & 2 deletions .changeset/conformance-rule-defect-outcome.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
"@thomasfosterau/effect-jsonapi": minor
---

A `Conformance` rule that dies no longer loses the whole report. In 0.16.3 a defect in any one rule (a fixture that throws, a transport that falls over) failed `Conformance.verify` / `verifyWith` outright, so every other rule's outcome — and, with this release's write fixture, the `Report.writes` ledger of what the kit created and whether it was removed — went unreported. The rule now gets a new `Errored` outcome (`Conformance.Outcome` gains a fourth member, `{ _tag: "Errored", rule, message, defect }`), every other rule still runs and is reported in the suite's order, and `Report.writes` is still filled. Interruption is not turned into an outcome: it still stops the run.
A `Conformance` rule that dies no longer loses the whole report. In 0.16.3 a defect in any one rule (a transport that throws, or a bug in the kit) failed `Conformance.verify` / `verifyWith` outright, so every other rule's outcome — and, with this release's write fixture, the `Report.writes` ledger of what the kit created and whether it was removed — went unreported. The rule now gets a new `Errored` outcome (`Conformance.Outcome` gains a fourth member, `{ _tag: "Errored", rule, message, defect }`), every other rule still runs and is reported in the suite's order, and `Report.writes` is still filled. That holds whether the rule dies inside its Effect or throws before returning one. Interruption is not turned into an outcome: it still stops the run. A write fixture that throws is not a defect and never was: a `create` or `update` that throws skips the rules it would have driven, and a `cleanup` that fails or throws is recorded in `Report.writes` as `cleanup-failed`.

`format` prints such a rule first in its tier, marked `DIED` with the defect's message, and adds `· N died` to the tier and summary lines when one did (a run in which nothing died prints as before); `summarise` gains an `errored` count. `assert` dies on the first `Errored` outcome — with a `RuleDied` defect naming the rule and the defect's message, the original defect as its `cause` — before looking at failures, so the gate stays as strict as when the defect killed the run.
**Behaviour change:** before, a dying rule failed the whole run; now the run succeeds with an `Errored` outcome, so a caller who gates on `summarise(report).failed`, `findings(report)` or `_tag === "Failed"` passes silently. If you gate on `failed`/`findings` rather than `Conformance.assert`, also check `summarise(report).errored === 0`.

`format` prints such a rule first in its tier, marked `DIED` with the defect's message (an `Error` as `Name: message`, any other thrown value as itself), and adds `· N died` to the tier and summary lines when one did (a run in which nothing died prints as before); `summarise` gains an `errored` count. `assert` dies on the first `Errored` outcome — with a defect tagged `RuleDied` (match it with `Predicate.isTagged(defect, "RuleDied")`) carrying the rule's id, a message naming the rule and the defect, and the original defect as its `cause` — before looking at failures, so the gate stays as strict as when the defect killed the run.

A `switch` over `Outcome._tag` that relies on exhaustiveness needs an `Errored` case.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1924,9 +1924,9 @@ Two tiers, separately runnable. `spec` is JSON:API v1.1 alone; `profile` is this

**It says what it did not check.** Every rule that could not run reports why — no endpoint of that shape, no sample id, no write fixture, a mutating probe not opted into — and `Conformance.gaps` declares the areas the kit does not cover at all (filter _evaluation_ semantics, pagination-link and sort-ordering correctness, the write rules beyond the success responses, atomic processing), each with its reason and tracking issue. Both are printed in every report, and skips are counted separately from passes, so a run that proved little cannot read as a clean bill of health.

**A rule that dies does not cost you the report.** A defect in one rule — a fixture that throws, a transport that falls over — becomes that rule's `Errored` outcome (printed as `DIED`, with the defect's message, and counted as `errored` by `Conformance.summarise`); every other rule still runs and is reported, and so is `report.writes`. Interruption is not caught: it still stops the run, after the cleanup of whatever the interrupted rule created.
**A rule that dies does not cost you the report.** A defect in one rule — a transport that throws, or a bug in the kit — becomes that rule's `Errored` outcome (printed as `DIED`, with the defect's message, and counted as `errored` by `Conformance.summarise`); every other rule still runs and is reported, and so is `report.writes`. Interruption is not caught: it still stops the run, after the cleanup of whatever the interrupted rule created. A write fixture that throws is not a defect: a `create` or `update` that throws skips the rules it would have driven, and a `cleanup` that fails is recorded in `report.writes`.

Use `Conformance.assert(report)` as a gate: it fails with a `ContractViolation` carrying the rule, its requirement, its citation and the request that decided it. A rule that died is not a finding about your server, but the run could not decide it either, so `assert` dies on it — naming the rule and the defect — rather than passing.
Use `Conformance.assert(report)` as a gate: it fails with a `ContractViolation` carrying the rule, its requirement, its citation and the request that decided it. A rule that died is not a finding about your server, but the run could not decide it either, so `assert` dies on it — with a defect tagged `RuleDied` naming the rule and the defect, the original as its `cause` — rather than passing. If you gate on `summarise(report).failed` or `findings(report)` instead of `assert`, also check `summarise(report).errored === 0`.

Full design note, including the coverage ledger and what it would take to close each gap: [`docs/conformance.md`](./docs/conformance.md).

Expand Down
107 changes: 106 additions & 1 deletion src/Conformance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@
import { describe, expect, it } from "vite-plus/test";
import {
Cause,
Deferred,
Effect,
Exit,
Fiber,
Layer,
Match,
MutableHashMap,
Expand Down Expand Up @@ -439,13 +441,14 @@ describe("Conformance: the report", () => {
});

it("prints and counts a rule that died apart from failures, and assert dies on it", async () => {
const defect = { reason: "fell over" };
const report: Conformance.Report = {
target: "t",
version: "1.1",
transport: "in-process",
outcomes: [
{ _tag: "Passed", rule, probes: 2, note: undefined },
{ _tag: "Errored", rule, message: "the transport fell over", defect: "fell over" },
{ _tag: "Errored", rule, message: "the transport fell over", defect },
],
gaps: [],
};
Expand All @@ -469,6 +472,11 @@ describe("Conformance: the report", () => {
expect(Exit.isFailure(exit) && Cause.pretty(exit.cause)).toContain(
`${rule.id} died: the transport fell over`,
);
// A tagged defect carrying the rule's id and, as its `cause`, the very
// value the rule died with.
const died = Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined;
expect(died).toMatchObject({ _tag: "RuleDied", rule: rule.id });
expect(Predicate.hasProperty(died, "cause") && died.cause).toBe(defect);
};
await diesNaming(report);
await diesNaming({
Expand Down Expand Up @@ -1312,6 +1320,103 @@ describe("Conformance: the write fixture", () => {
expect(text).toContain("not decided — the rule died: TransportFellOver");
});

class FixturesUnreadable extends Schema.TaggedError<FixturesUnreadable>()(
"FixturesUnreadable",
{},
) {}

it("reports a rule that throws before its Effect starts as Errored, keeping the report", async () => {
// Reading `writes["articles"]` throws. The write rules read it while
// building their targets — before, not inside, the Effect their `run`
// returns — standing in for any kit code that throws synchronously.
const { report, store, writes } = await run(undefined, () => ({
writes: {
get articles(): Conformance.WriteFixture {
throw new FixturesUnreadable();
},
},
}));
expect(report.outcomes.map((outcome) => outcome.rule.id)).toEqual(
Conformance.rules.map((rule) => rule.id),
);
const errored = report.outcomes.filter((outcome) => Predicate.isTagged(outcome, "Errored"));
expect(errored.map((outcome) => outcome.rule.id)).toEqual(WRITE_RULES);
expect(errored.map((outcome) => outcome.message)).toEqual(
WRITE_RULES.map(() => "FixturesUnreadable"),
);
// Every other rule still ran.
expect(failed(report)).toEqual([]);
expect(Conformance.summarise(report).passed).toBeGreaterThan(0);
expect(writes).toEqual([]);
expect(MutableHashMap.size(store)).toBe(0);
});

class TransportRefused extends Schema.TaggedError<TransportRefused>()("TransportRefused", {
message: Schema.String,
}) {}

it.each([
["a string", "boom", "boom"],
["null", null, "null"],
["a number", 42, "42"],
["a plain object", { code: 7 }, `{"code":7}`],
[
"an error",
new TransportRefused({ message: "connection refused" }),
"TransportRefused: connection refused",
],
])("renders %s a rule dies with as itself", async (_, defect, message) => {
const { report } = await run(
(canned, request) => {
if (request.method === "PATCH") throw defect;
return canned;
},
() => ({ only: ["spec/status/update-response"] }),
);
expect(report.outcomes).toEqual([
expect.objectContaining({ _tag: "Errored", message, defect }),
]);
});

it("stops at an external interrupt, cleaning up what the interrupted rule created", async () => {
const store: Store = MutableHashMap.empty();
const cleaned: Array<string> = [];
const seen: Array<string> = [];
const serve = cannedClient(writeServer(store));
const exit = await Effect.runPromiseExit(
Effect.gen(function* () {
const patching = yield* Deferred.make<void>();
const fiber = yield* Effect.forkChild(
Conformance.verifyWith(writeApi, {
client: HttpClient.make((request, url) =>
Effect.andThen(
Effect.sync(() => seen.push(`${request.method} ${url.pathname}`)),
// The update rule's PATCH never answers; the run is
// interrupted from outside while it waits.
request.method === "PATCH"
? Effect.andThen(Deferred.succeed(patching, undefined), Effect.never)
: serve.execute(request),
),
),
baseUrl: "http://fixture.test",
ids: { articles: "1" },
mutating: true,
writes: { articles: fixture(store, cleaned) },
}),
);
yield* Deferred.await(patching);
yield* Fiber.interrupt(fiber);
return yield* Fiber.join(fiber);
}),
);
expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true);
// No rule started after the interrupted one: its PATCH was the last
// request, so the delete and atomic write rules never ran. And the
// resource it was patching — the one it created — was still removed.
expect(seen.at(-1)).toBe(`PATCH /articles/${cleaned.at(-1)}`);
expect(MutableHashMap.size(store)).toBe(0);
});

it("still propagates interruption, cleaning up what the interrupted rule created", async () => {
const store: Store = MutableHashMap.empty();
const cleaned: Array<string> = [];
Expand Down
19 changes: 12 additions & 7 deletions src/Conformance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,8 +226,8 @@ export interface Finding extends Core.Finding {}
/**
* What became of one rule in a run: `Passed` with the number of requests it
* made, `Failed` with its findings, `Skipped` with the reason it could not
* be decided against this target, or `Errored` when the rule died — a defect
* in the kit, a fixture or the transport, not a finding about the server —
* be decided against this target, or `Errored` when the rule died — a
* transport that throws, or a bug in the kit, not a finding about the server —
* with the defect's `message` and the `defect` itself.
*
* `Skipped` is load-bearing. A rule that needs a write endpoint against an api
Expand All @@ -238,7 +238,9 @@ export interface Finding extends Core.Finding {}
* rest of its report: every other rule still runs and is reported, and so is
* {@link Report.writes}. It is neither a pass nor a finding — {@link assert}
* dies on it. Interruption is not turned into an outcome: it still stops the
* run.
* run. A write fixture that throws is not a defect: a `create` or `update`
* that throws skips the rules it would have driven, naming the member, and a
* `cleanup` that fails or throws is recorded in {@link Report.writes}.
*
* @example
* ```ts
Expand Down Expand Up @@ -553,7 +555,8 @@ export class ContractViolation extends Data.TaggedError("ContractViolation")<{

/**
* The defect {@link assert} dies with on a rule that died: the rule's id, a
* message naming it and the defect, and the defect itself as `cause`.
* message naming it and the defect, and the defect itself as `cause`. Private
* on purpose — callers match it by its tag (`_tag: "RuleDied"`), not by class.
*/
class RuleDied extends Schema.TaggedError<RuleDied>()("RuleDied", {
rule: Schema.String,
Expand Down Expand Up @@ -1102,9 +1105,11 @@ export const findings = (report: Report): ReadonlyArray<Finding> =>
* A rule that died (`Errored`) is neither: the run could not decide it, so the
* gate cannot pass, and it is not a finding about the server, so it is not a
* `ContractViolation`. `assert` dies on the first one instead — before looking
* at failures — with a `RuleDied` defect whose message names the rule and the
* defect's, and whose `cause` is the original defect. That keeps the gate as strict as when a
* rule's defect killed the whole run, while the report itself stays readable.
* at failures — with a tagged defect, `_tag: "RuleDied"` (match it with
* `Predicate.isTagged(defect, "RuleDied")`), whose `rule` is the rule's id,
* whose message names the rule and the defect's, and whose `cause` is the
* original defect. That keeps the gate as strict as when a rule's defect
* killed the whole run, while the report itself stays readable.
*
* @example
* ```ts
Expand Down
40 changes: 26 additions & 14 deletions src/internal/conformance/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,15 @@
* @since 0.15.0
* @internal
*/
import { Array as Arr, Cause, Effect, MutableHashSet, Option, SchemaAST } from "effect";
import {
Array as Arr,
Effect,
Formatter,
MutableHashSet,
Option,
Predicate,
SchemaAST,
} from "effect";
import { HttpBody, HttpClient, HttpClientRequest } from "effect/http";
import type { HttpApi, HttpApiEndpoint } from "effect/http-api";
import { ATOMIC_EXTENSION_URI, MEDIA_TYPE } from "../media.js";
Expand Down Expand Up @@ -531,31 +539,35 @@ export const pass = (rule: Rule, probes: number, note?: string): Passed => ({
/** @internal */
export const skip = (rule: Rule, reason: string): Skipped => ({ _tag: "Skipped", rule, reason });

/**
* Renders the errors a defect pretty-prints as, `Name: message` each (or the
* name alone when it carries no message), so a thrown tagged error with no
* message still says what it was.
*/
const defectMessage = (errors: ReadonlyArray<Error>): string =>
errors
.map((error) => (error.message === "" ? error.name : `${error.name}: ${error.message}`))
.join("; ");
/** An `Error` as `Name: message`, or the name alone when it carries no message. */
const errorMessage = (error: Error): string =>
error.message === "" ? error.name : `${error.name}: ${error.message}`;

/**
* Runs one rule, turning a defect into its `Errored` outcome so that one rule
* that dies cannot cost the run every other rule's outcome and its writes
* ledger. Interruption is not caught: it is a request to stop the whole run,
* not something one rule did, so it still propagates.
* ledger. `run` is suspended, so a throw before it returns its Effect — kit
* code that works out a rule's targets up front — is caught the same way.
* Interruption is not caught: it is a request to stop the whole run, not
* something one rule did, so it still propagates.
*
* @internal
*/
export const runRule = (implementation: RuleImpl, ctx: Context): Effect.Effect<Outcome> =>
implementation.run(ctx).pipe(
Effect.suspend(() => implementation.run(ctx)).pipe(
// The defect's message for a report line: an `Error` by its name and
// message, so a thrown tagged error with no message still says what it
// was; anything else thrown — a string, `null`, a plain object — as
// itself, not dressed up as an `Error`.
Effect.catchDefect((defect) =>
Effect.succeed<Outcome>({
_tag: "Errored",
rule: implementation.rule,
message: defectMessage(Cause.prettyErrors(Cause.die(defect))),
message: Predicate.isError(defect)
? errorMessage(defect)
: Predicate.isString(defect)
? defect
: Formatter.format(defect),
defect,
}),
),
Expand Down
Loading