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
16 changes: 16 additions & 0 deletions .claude/skills/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Agent skills

Each directory holds a `SKILL.md`: YAML frontmatter (`name`, `description`) followed by step-by-step instructions, a worked example that references files in this repository, and a checklist. Invoke the matching skill before starting that kind of task (`CLAUDE.md`, "Skills"). Skills assume you have read `CLAUDE.md` and nothing else.

| Skill | Use it when |
|---|---|
| [`picking-up-an-issue`](picking-up-an-issue/SKILL.md) | Starting any unit of work: find an unblocked issue, claim it, worktree and branch, verify, commit, PR, merge policy, clean up. |
| [`updating-the-conformance-map`](updating-the-conformance-map/SKILL.md) | A PR touches a spec clause: find the row, cell formats, third-level splits, XML doc citations, the checker. |
| [`writing-a-corpus-file`](writing-a-corpus-file/SKILL.md) | A test needs a minimal PDF that `tests/Corpus/` does not have: `generate.py`, verification, README, `Corpus.cs`, snapshot. |
| [`adding-a-benchmark`](adding-a-benchmark/SKILL.md) | A PR touches a hot path: `[MemoryDiagnoser]` class, zero-allocation proof, dry/short/full runs, the regression gate. |
| [`adding-a-fuzz-target`](adding-a-fuzz-target/SKILL.md) | A PR adds or changes a parser or codec: register a SharpFuzz target, seeds, smoke mode. |
| [`adding-a-filter`](adding-a-filter/SKILL.md) | Implementing a stream filter or image codec behind the filter extension point (design brief until #38 lands). |
| [`adding-a-font-program-parser`](adding-a-font-program-parser/SKILL.md) | Implementing a TrueType, CFF, Type 1 or OpenType parser behind the font program extension point (design brief until #50 lands). |
| [`adding-a-rendering-backend`](adding-a-rendering-backend/SKILL.md) | Implementing a backend that consumes display lists (design brief until Phase 3A lands). |

Skills whose extension point does not exist in code yet say so at the top and must have their contract section replaced with the real signatures in the PR that defines the contract.
89 changes: 89 additions & 0 deletions .claude/skills/adding-a-benchmark/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
---
name: adding-a-benchmark
description: "Use when a PR touches a hot path (lexer, content interpreter, rasterizer, codecs) or adds any performance-sensitive code: add a BenchmarkDotNet class with MemoryDiagnoser, prove zero allocations, and run it in dry, short and full modes."
---

# Adding a benchmark

`CLAUDE.md` ("Code conventions") requires that hot paths allocate nothing per token, operator, glyph or scanline and that a BenchmarkDotNet benchmark with a `MemoryDiagnoser` assertion proves it. Benchmarks also become the baseline for the Phase 3I regression gate.

## Where benchmarks live

`bench/Broadside.Benchmarks/`, namespace `Broadside.Benchmarks`, one class per hot path (`LexerBenchmarks`, `FlateBenchmarks`, `RasterizerBenchmarks`). The project:

- references `src/Broadside/Broadside.csproj`; add a `ProjectReference` to `src/Broadside.Rendering/Broadside.Rendering.csproj` when you benchmark the rasterizer;
- links `tests/Broadside.TestSupport/CorpusLocator.cs` as source, so `CorpusLocator.CorpusDirectory` and `CorpusLocator.CorpusFiles()` are available, but nothing from `Broadside.TestSupport` itself (it would drag xunit and Verify in);
- sees `internal` members of every `src/` package (`InternalsVisibleTo` in `src/Directory.Build.props`), so you can benchmark the internal implementation directly;
- builds optimized; BenchmarkDotNet refuses a Debug assembly.

`Program.cs` runs `BenchmarkSwitcher` with `BenchmarkConfig`, and exits 1 when any benchmark fails validation or execution; that exit code is the CI smoke signal.

## Conventions

- `[MemoryDiagnoser]` on every class. It adds the `Allocated` column.
- No job attributes (`[ShortRunJob]`, `[SimpleJob]`, `[DryJob]`) on the class. `BenchmarkConfig` supplies the job from `--job short` / `--job dry`; without `--job` it is `Job.Default`. A class-level job attribute would add a second job to every run.
- `[GlobalSetup]` loads the inputs once (corpus bytes via `CorpusLocator`), outside the measured body.
- The benchmark body is the hot path and nothing else, and returns a value derived from the work so the JIT cannot discard it.
- `[Params]` over corpus file names when the input matters; keep the values stable, they are part of the result key.
- Method names are stable identifiers; renaming one breaks its history in the regression gate.
- Per-item costs: set `[Benchmark(OperationsPerInvoke = n)]` when one call processes `n` tokens or scanlines, so the mean is per item.

## Asserting zero allocations

Two layers:

1. The benchmark. With `[MemoryDiagnoser]` the `Allocated` column must read `-` (0 B) for a hot path. Any number there is a regression, whatever the baseline says. Read it from the console table or from `BenchmarkDotNet.Artifacts/results/<Class>-report-github.md`.
2. A unit test next to the feature that fails the build on regressions, because BenchmarkDotNet only reports. After one warm-up call:

```csharp
[Fact]
public void Tokenizing_allocates_nothing()
{
byte[] bytes = Corpus.Bytes("text-standard14.pdf");
RunHotPath(bytes); // warm up: JIT, static init
long before = GC.GetAllocatedBytesForCurrentThread();
RunHotPath(bytes);
Assert.Equal(0, GC.GetAllocatedBytesForCurrentThread() - before);
}
```

Put only the per-item work inside `RunHotPath`; one-time buffers (`ArrayPool<T>` rentals, the output list) are allowed per call, so size the input to make per-token allocations visible.

## Running

```sh
dotnet run -c Release --project bench/Broadside.Benchmarks -- --list flat # names
dotnet run -c Release --project bench/Broadside.Benchmarks -- --filter '*CorpusBenchmarks*' --job dry # one in-process iteration, proves it runs (CI)
dotnet run -c Release --project bench/Broadside.Benchmarks -- --filter '*' --job short # 3 iterations, quick local signal
dotnet run -c Release --project bench/Broadside.Benchmarks -- --filter '*' # full Job.Default run for numbers you quote
dotnet run -c Release --project bench/Broadside.Benchmarks -- --filter '*' --job dry --exporters json # adds <Class>-report-full-compressed.json
```

Results land in `BenchmarkDotNet.Artifacts/results/` (gitignored). `--job dry` numbers are meaningless; use them only to prove the benchmark executes. Quote `--job short` or full-run numbers in the PR's Verification section, with `Mean` and `Allocated`.

## The Phase 3I regression gate

Track 3I (`docs/plan/README.md`) adds a CI job that runs the suite and compares each benchmark's mean and allocated bytes against a baseline recorded from `main`, using the JSON exporter output above. What that gate needs from you now:

- stable class, method and `[Params]` names, since the comparison is keyed by them;
- `Allocated` already at `-` on hot paths, so the gate can treat any allocation as a failure rather than a percentage;
- one benchmark per operation, not one per test case, so the baseline stays small enough to run on every PR.

## Worked example: `CorpusBenchmarks`

`bench/Broadside.Benchmarks/CorpusBenchmarks.cs` is the placeholder that proves the harness: `[MemoryDiagnoser]` on the class, `[GlobalSetup]` fills `_files` from `CorpusLocator.CorpusFiles()`, and `ReadAllCorpusFiles` reads every file and returns the byte total. A dry run prints:

```
| Method | Mean | Error | Allocated |
| ReadAllCorpusFiles | 7.612 ms | NA | 22.13 KB |
```

`Allocated` is non-zero because `File.ReadAllBytes` allocates; that is fine for a placeholder and would be a failure for a lexer. A lexer benchmark that replaces it keeps the same shape: `[Params("text-standard14.pdf", "xref-stream.pdf")] public string File`, `[GlobalSetup]` reads the bytes once, and `[Benchmark] public int Tokenize()` walks every token and returns the count, with `Allocated` expected to read `-`.

## Checklist

- [ ] Class in `bench/Broadside.Benchmarks/`, `[MemoryDiagnoser]`, no job attributes
- [ ] Inputs loaded in `[GlobalSetup]`; body is only the hot path; result returned
- [ ] `--job dry` exits 0; `--job short` numbers quoted in the PR
- [ ] `Allocated` reads `-` on hot paths; `GC.GetAllocatedBytesForCurrentThread` test added next to the feature
- [ ] Names stable; any rename called out in the PR body
58 changes: 58 additions & 0 deletions .claude/skills/adding-a-filter/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
---
name: adding-a-filter
description: "Use when implementing a stream filter or image codec (FlateDecode, LZWDecode, ASCII85Decode, RunLengthDecode, DCTDecode, CCITTFaxDecode, JBIG2Decode, JPXDecode, Crypt, predictors) behind the filter extension point in Broadside.Filters."
---

# Adding a filter

> **The filter contract is defined by issue #38 (Decode streams through filters). When it lands, replace the "Contract" section of this skill with the real signatures from `src/Broadside/Filters/` and `src/Broadside/PublicAPI.Unshipped.txt`.** Until then this is a design brief: it says what the contract must provide and what a filter PR must deliver. It does not spell the methods.

A filter is "a stream encoding named in a stream's `/Filter` entry, and the codec that decodes or encodes it. Image codecs are filters." (`CONTEXT.md`). Filters are an extension point: a public contract in the core with a fully managed default (`CLAUDE.md`, "Hard rules"; ADR 0001).

## Where it lives

- Contract and standard filters: namespace `Broadside.Filters` in `src/Broadside/`. Image codecs (DCT, CCITT, JBIG2, JPX; Phase 2B) implement the same contract, in the same namespace or a sub-namespace per codec.
- Tests: `tests/Broadside.Tests/Filters/`, namespace `Broadside.Tests.Filters`, one class per filter.
- Corpus: `tests/Corpus/<filter>-stream.pdf` (`flate-stream.pdf`, `lzw-stream.pdf`, `ascii85-stream.pdf`, `asciihex-stream.pdf`, `runlength-stream.pdf`, `filter-chain.pdf`, `png-predictor.pdf` exist); the encoder side of each lives in `tests/Corpus/generate.py` (`lzw_encode`, `ascii85_encode`, `png_up_predict`, ...).
- Benchmarks: `bench/Broadside.Benchmarks/<Filter>Benchmarks.cs`. Fuzz: `tests/Broadside.Fuzz/FuzzTargets.cs`, target `filter-<name>`.

## Contract (responsibilities, not signatures)

An implementation must be able to:

- name the filter as it appears in `/Filter` (§7.4 Table 6) and its inline-image abbreviation (§8.9.7 Table 92: `/Fl`, `/LZW`, `/A85`, `/AHx`, `/RL`, `/CCF`, `/DCT`);
- decode a stream body given its `/DecodeParms` dictionary (§7.4.1; predictor parameters in §7.4.4.4 Table 10, CCITT in Table 11, JBIG2 in Table 12, DCT in Table 13, JPX in §7.4.9, Crypt in §7.4.10) into a caller-provided or pooled buffer, without per-byte or per-row allocation (codecs are a hot path);
- participate in a chain: the `/Filter` array is applied in order on decode (`filter-chain.pdf` is `[/ASCII85Decode /FlateDecode]`), each stage consuming the previous stage's output;
- repair and record in lenient mode: truncated data, a missing EOD marker, a wrong predictor row length produce a `Diagnostic` and the bytes decoded so far; strict mode throws (ADR 0005);
- for image codecs, deliver samples as a planar or interleaved buffer with a declared colour space and bit depth (plan, Track 2B), including the DCT Adobe-marker CMYK/YCCK and JPX colour-space and SMask-in-data cases;
- encode, for the filters the writer uses (Flate, DCT baseline, PNG predictors; Phase 4A). Decode-only filters say so.

Registration goes through the options object: `PdfOptions.UseFilter(...)` (plan row 1.12; `Use*` selects an implementation, `CLAUDE.md` "Code conventions") replaces or adds a filter for one engine instance. There is no static registry: a consumer must be able to run two engines with different filter sets in one process, and tests must be able to inject a fake.

## Managed default

Every filter the PDF file format depends on ships in the core, written in C#. Allowed dependencies are `System.*` only: Flate uses `System.IO.Compression` (`ZLibStream` or `DeflateStream`); everything else (LZW, ASCII, RunLength, predictors, and in Phase 2B the DCT, CCITT, JBIG2 and JPX decoders) is implemented here. Do not add a NuGet package to save time; stub behind the extension point and open an issue (`CLAUDE.md`, "Do not").

## Deliverables of a filter PR

1. Implementation in `Broadside.Filters`, `sealed`, XML docs on every public member with `<remarks>ISO 32000-2 §7.4.x</remarks>` (plus the codec's own reference: ITU-T T.81 for DCT, T.4/T.6 for CCITT, T.88 for JBIG2, ISO/IEC 15444-1 for JPX, cited from `Specs/References/`).
2. `PublicAPI.Unshipped.txt` entries for the new public surface, explained in the PR body.
3. Conformance rows: split `7.4` in `docs/conformance/iso-32000-2.md` to third level (`7.4.2` ASCIIHexDecode ... `7.4.10` Crypt) and mark the ones you implemented (skill `updating-the-conformance-map`).
4. Corpus file(s): one `<filter>-stream.pdf` per filter and one per distinctive parameter set (`png-predictor.pdf` covers Predictor 12), generated by `generate.py` (skill `writing-a-corpus-file`). Truncated and EOD-less variants belong in the "Deliberately broken files" table.
5. Unit tests: known-answer vectors from the spec (the LZW example in §7.4.4.2, the ASCII85 `~>` and `z` cases), round trip against the generator's encoder, the broken variants in lenient and strict mode, and the chain.
6. Fuzz target `filter-<name>` over raw stream bodies (skill `adding-a-fuzz-target`).
7. Benchmark `<Filter>Benchmarks` with `[MemoryDiagnoser]`, `Allocated` at `-` for the decode loop (skill `adding-a-benchmark`).
8. Fuzz smoke and `dotnet test Broadside.Core.slnf` green.

## Worked example: LZWDecode

`tests/Corpus/lzw-stream.pdf` holds a content stream encoded by `lzw_encode` in `generate.py` (9–12-bit codes, clear code 256 first, EOD 257 last, `EarlyChange` 1). The decoder lives in `Broadside.Filters`, cites `<remarks>ISO 32000-2 §7.4.4.2.</remarks>`, handles `/EarlyChange 0` from `/DecodeParms` (Table 8), and then the TIFF and PNG predictors from §7.4.4.4 run as a second stage shared with Flate. Tests: the Table 7 sequence `45 45 45 45 45 65 45 45 45 66` decodes from `80 0B 60 50 22 0C 0C 85 01` (the known answer `self_test()` in `generate.py` already checks for the encoder); `lzw-stream.pdf` decodes to the bytes `pdftotext` shows (`LZWDecode`); a truncated body yields a diagnostic in lenient mode and throws in strict mode. Fuzz target `filter-lzw`, benchmark `LzwBenchmarks.Decode` over the corpus stream, row `7.4.4` done with those tests named.

## Checklist

- [ ] Contract section of this skill replaced with the real signatures once #38 has landed
- [ ] Implementation in `Broadside.Filters`, managed only, `sealed`, clause-cited XML docs
- [ ] Registered through `PdfOptions`, not a static registry
- [ ] Lenient repairs recorded as `Diagnostic`; strict mode throws
- [ ] `PublicAPI.Unshipped.txt`, conformance rows, corpus file(s), unit tests, fuzz target, benchmark
- [ ] No per-byte or per-row allocation (`Allocated` reads `-`)
Loading
Loading