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
2 changes: 1 addition & 1 deletion .changeset/conformance-rule-defect-outcome.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"@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 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 a value the kit can render is not a defect: a `create` or `update` that throws one skips the rules it would have driven, and a `cleanup` that fails with or throws one is recorded in `Report.writes` as `cleanup-failed`. One that throws a value the kit can't render (a revoked `Proxy`, say) is still reported as `Errored` until #271.
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 member that throws is not a defect, whatever it throws — even a value that throws when inspected, such as a revoked `Proxy`: 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`. The skip reason and the `cleanup-failed` detail render the value as an `Errored` message does (below).

**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`.

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1928,7 +1928,7 @@ 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 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 a value the kit can render is not a defect: a `create` or `update` that throws one skips the rules it would have driven, and a `cleanup` that fails with one is recorded in `report.writes`. One that throws a value the kit can't render (a revoked `Proxy`, say) is still reported as `Errored` until [#271](https://github.com/thomasfosterau/effect-jsonapi/issues/271).
**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 member that throws is not a defect, whatever it throws: 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`.

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`.

Expand Down
2 changes: 1 addition & 1 deletion docs/conformance.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ Conformance.verify(api, {
What the kit promises in return:

- **It refuses an id it evidently did not create.** Every write rule creates its own disposable target from `create` — the update rule PATCHes it, the delete rule DELETEs it — and acts on the id the server's create response named only after checking it: the response must name a resource of the type `create` returned (`data.type`, or `atomic:results[0].data.type` for an `add`), under an id that is a URL path segment of its own (not `""`, `.` or `..`, which `encodeURIComponent` leaves alone and URL normalisation turns into the collection or `/`, nor a lone surrogate, which no URL can carry), that is not an `ids` sample, that no successful `GET` earlier in the run returned (as primary data, in `included`, or as a relationship's linkage) unless the kit had already taken it from a create of its own, and that the run does not already hold a resource for that has not been removed (two live resources cannot share an id, so one of the two answers is wrong). Any other id is recorded as `left`, with `detail` naming what was named — "named `people:1`, which the kit did not create … — not touched" — and is never PATCHed, DELETEd or handed to `cleanup`; the rules that would have acted on it skip, saying so. An id the server hands out again once the kit has removed its first holder — a `size + 1` store, a SQLite rowid — is accepted, because refusing it would leave every later resource behind. (Before the fixture, `mutating: true` made the delete rule delete the `ids` sample.) Every rule that creates nothing (the profile tier's included) runs before the first rule that creates, so a create is checked against everything the run reads; the report keeps the suite's order. The read check can refuse falsely: linkage can name a resource since deleted, and a server that reuses ids may hand that id to the kit's create. That fails safe — the resource is recorded as `left` with a `detail` saying why, and the rules that would have acted on it skip.
- **Cleanup runs however the rule ends.** Each target is created inside `Effect.acquireUseRelease`, so `cleanup` runs after the rule that made it whether that rule passed, failed or died. A cleanup that fails with a value the kit can render is recorded, not propagated, so one bad cleanup cannot cost the run its report; one that fails with a value the kit can't render (a revoked `Proxy`, say) is still reported as its rule's `Errored` outcome until [#271](https://github.com/thomasfosterau/effect-jsonapi/issues/271).
- **Cleanup runs however the rule ends.** Each target is created inside `Effect.acquireUseRelease`, so `cleanup` runs after the rule that made it whether that rule passed, failed or died. A cleanup that fails or throws is recorded as `cleanup-failed`, not propagated, so one bad cleanup cannot cost the run its report — whatever it fails with: `detail` renders the value as a rule's defect message is, and a value that throws when inspected (a revoked `Proxy`, say) as `[unrenderable defect]`.
- **The run is auditable.** `Report.writes` lists every resource the kit created, the rule that created it and what became of it — `deleted` by the kit's own DELETE, `cleaned-up`, `cleanup-failed` with the cause, or `left`. `format` prints them under `WRITES`, with the count still in place.
- **Each sub-key gates only its own rules.** A type with no `create` skips every write rule naming `writes["<type>"].create`, exactly as a missing `ids` entry does; a create-only type omits `update` and skips only the update rule. Never a vacuous pass.
- **A rejected payload is not a verdict.** If the server does not accept `create` (a 4xx, say), the rules it was for report `Skipped` with the status and body — the fixture is wrong or the server is, and the kit cannot tell which.
Expand Down
128 changes: 102 additions & 26 deletions src/Conformance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1592,21 +1592,71 @@ describe("Conformance: the write fixture", () => {
message: Schema.String,
}) {}

// A fixture that throws a value the kit can render is not a defect: no rule
// dies of it. One it can't render still does, until #271.
it.each([
/** An error whose `message` getter throws: reading it, as `String` does, throws. */
const messageThrows = Object.defineProperty(new FixtureBroke({ message: "" }), "message", {
get: (): string => {
throw new FixtureBroke({ message: "no message" });
},
});

/** What each value a fixture member throws or fails with renders as in the report. */
const fixtureValues = [
{
value: "a tagged error",
thrown: new FixtureBroke({ message: "fixture broke" }),
rendered: "FixtureBroke: fixture broke",
},
// `__proto__` in a literal sets the prototype: `String` finds no `toString` on it.
{ value: "a null-prototype object", thrown: { __proto__: null }, rendered: "{}" },
{ value: "a revoked Proxy", thrown: revoked, rendered: "[unrenderable defect]" },
{
value: "an error whose message getter throws",
thrown: messageThrows,
rendered: "[unrenderable defect]",
},
{
value: "an error named by a Symbol",
thrown: Object.assign(new FixtureBroke({ message: "broke" }), { name: Symbol("odd") }),
rendered: "[unrenderable defect]",
},
];

type Thrown = (typeof fixtureValues)[number]["thrown"];

const throwing = (thrown: Thrown) => (): never => {
throw thrown;
};

/** The fixture member that misbehaves, how, and what the run must make of it. */
const fixtureMembers = [
{
member: "create",
expected: (report: Conformance.Report, writes: ReadonlyArray<Conformance.Write>) => {
everyWriteRule(report, `writes["articles"].create threw: FixtureBroke: create broke`);
how: "throws",
override: (thrown: Thrown): Partial<Conformance.WriteFixture> => ({
create: throwing(thrown),
}),
expected: (
report: Conformance.Report,
writes: ReadonlyArray<Conformance.Write>,
rendered: string,
) => {
everyWriteRule(report, `writes["articles"].create threw: ${rendered}`);
expect(writes).toEqual([]);
},
},
{
member: "update",
expected: (report: Conformance.Report, writes: ReadonlyArray<Conformance.Write>) => {
how: "throws",
override: (thrown: Thrown): Partial<Conformance.WriteFixture> => ({
update: throwing(thrown),
}),
expected: (
report: Conformance.Report,
writes: ReadonlyArray<Conformance.Write>,
rendered: string,
) => {
expect(outcomeFor(report, "spec/status/update-response")).toEqual(
skippedFor(`writes["articles"].update threw: FixtureBroke: update broke`),
skippedFor(`writes["articles"].update threw: ${rendered}`),
);
const others = WRITE_RULES.filter((id) => id !== "spec/status/update-response");
expect(others.map((id) => outcomeFor(report, id)._tag)).toEqual(others.map(() => "Passed"));
Expand All @@ -1615,32 +1665,58 @@ describe("Conformance: the write fixture", () => {
},
{
member: "cleanup",
expected: (report: Conformance.Report, writes: ReadonlyArray<Conformance.Write>) => {
everyWriteRule(report);
const stuck = writes.filter((write) => write.disposal === "cleanup-failed");
// Every creation but the one the kit's own DELETE removed.
expect(stuck.length).toBe(WRITE_RULES.length - 1);
expect(stuck[0]?.detail).toContain("cleanup broke");
},
how: "throws",
override: (thrown: Thrown): Partial<Conformance.WriteFixture> => ({
cleanup: throwing(thrown),
}),
expected: (
report: Conformance.Report,
writes: ReadonlyArray<Conformance.Write>,
rendered: string,
) => cleanupFailed(report, writes, rendered),
},
] as const)(
"skips or records — never dies — when the fixture's $member throws",
async ({ member, expected }) => {
{
member: "cleanup",
how: "fails with",
override: (thrown: Thrown): Partial<Conformance.WriteFixture> => ({
cleanup: () => Effect.fail(thrown),
}),
expected: (
report: Conformance.Report,
writes: ReadonlyArray<Conformance.Write>,
rendered: string,
) => cleanupFailed(report, writes, rendered),
},
];

/** Every write rule passed, and every creation but the one the kit's own DELETE removed is `cleanup-failed`, saying why. */
const cleanupFailed = (
report: Conformance.Report,
writes: ReadonlyArray<Conformance.Write>,
rendered: string,
) => {
everyWriteRule(report);
const stuck = writes.filter((write) => write.disposal === "cleanup-failed");
expect(stuck.length).toBe(WRITE_RULES.length - 1);
expect(stuck.map((write) => write.detail)).toEqual(stuck.map(() => rendered));
};

// A write fixture member that throws, or a `cleanup` that fails, is not a
// defect — whatever the value, even one no rendering can read: no rule dies
// of it.
it.each(
fixtureMembers.flatMap((member) => fixtureValues.map((value) => ({ ...member, ...value }))),
)(
"skips or records — never dies — when the fixture's $member $how $value",
async ({ override, thrown, rendered, expected }) => {
const { report, writes } = await run(undefined, (store, cleaned) => ({
writes: {
articles: {
...fixture(store, cleaned),
[member]: () => {
throw new FixtureBroke({ message: `${member} broke` });
},
},
},
writes: { articles: { ...fixture(store, cleaned), ...override(thrown) } },
}));
expect(report.outcomes.filter((outcome) => Predicate.isTagged(outcome, "Errored"))).toEqual(
[],
);
expect(failed(report)).toEqual([]);
expected(report, writes);
expected(report, writes, rendered);
},
);

Expand Down
11 changes: 5 additions & 6 deletions src/Conformance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,12 +240,11 @@ 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. A write fixture that throws a value the kit can render is not a
* defect: a `create` or `update` that throws one skips the rules it would have
* driven, naming the member, and a `cleanup` that fails with or throws one is
* recorded in {@link Report.writes}. One that throws a value the kit can't
* render (a revoked `Proxy`, say) is still reported as `Errored` until
* {@link https://github.com/thomasfosterau/effect-jsonapi/issues/271 #271}.
* run. A write fixture member that throws is not a defect, whatever it
* throws: 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}. The value is rendered as `message` is, so one that
* throws when inspected reads `[unrenderable defect]` there too.
*
* @example
* ```ts
Expand Down
51 changes: 31 additions & 20 deletions src/internal/conformance/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -570,6 +570,36 @@ const capped = (message: string): string => {
/** `Errored.message` for a defect that throws when it is inspected. */
const UNRENDERABLE = "[unrenderable defect]";

/**
* A thrown or failed value as one report line: an `Error` by its name and
* message, so a thrown tagged error with no message still says what it was;
* anything else — a string, `null`, a plain object — as itself, not dressed up
* as an `Error`; capped at {@link MESSAGE_LIMIT}. Total: a value that throws
* when inspected (a revoked `Proxy`, a getter that throws, an `Error` whose
* `name` is a Symbol) renders as {@link UNRENDERABLE} rather than throwing in
* turn, so the report the caller is building survives it.
*
* Shared by a rule's `Errored.message` and the write fixture's skip reasons and
* `cleanup-failed` details, so a value renders the same wherever it surfaces.
*
* @internal
*/
// oxlint-disable-next-line effect/no-unknown-parameters -- renders whatever a rule or fixture threw or failed with; a thrown value has no schema to parse it by
export const renderThrown = (thrown: unknown): string =>
Result.merge(
Result.try({
try: () =>
capped(
Predicate.isError(thrown)
? errorMessage(thrown)
: Predicate.isString(thrown)
? thrown
: Formatter.format(thrown),
),
catch: () => UNRENDERABLE,
}),
);

/**
* 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
Expand All @@ -586,26 +616,7 @@ export const runRule = (implementation: RuleImpl, ctx: Context): Effect.Effect<O
Effect.succeed<Outcome>({
_tag: "Errored",
rule: implementation.rule,
// 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`. Rendering is total: a
// defect that throws when inspected (a revoked `Proxy`, a getter that
// throws) gets a fixed marker rather than killing the run the
// `Errored` outcome exists to keep.
message: Result.merge(
Result.try({
try: () =>
capped(
Predicate.isError(defect)
? errorMessage(defect)
: Predicate.isString(defect)
? defect
: Formatter.format(defect),
),
catch: () => UNRENDERABLE,
}),
),
message: renderThrown(defect),
defect,
}),
),
Expand Down
Loading
Loading