From 2f08dad1d7e066d3ecf3fa268f3378cfd4b76f99 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sat, 17 Oct 2026 18:57:29 +0200 Subject: [PATCH] chore(chore): R4 plan rev 1 --- .../plans/2026-10-17-rust-r4-pdf-core.md | 365 ++++++++++++++++++ 1 file changed, 365 insertions(+) create mode 100644 .claude/tasks/plans/2026-10-17-rust-r4-pdf-core.md diff --git a/.claude/tasks/plans/2026-10-17-rust-r4-pdf-core.md b/.claude/tasks/plans/2026-10-17-rust-r4-pdf-core.md new file mode 100644 index 00000000..6f6f1914 --- /dev/null +++ b/.claude/tasks/plans/2026-10-17-rust-r4-pdf-core.md @@ -0,0 +1,365 @@ +# PLAN: Rust R4, PDF core (reader in a disposable worker, writer, report-compare), `packages/pdf` deleted + +- date: 2026-10-17 | rev 1 | branch: `chore/rust-r4-plan` (plan only); code later on `feature/rust-r4-pdf-core`, one merge +- spec: owner briefs 2026-10-17 "Préparation de R4" and "Autorisation de préparation R4.0" (13 arbitrations, A1 to A13 below); `docs/development/RUST_ARCHITECTURE_REVIEW.md` I.2, II.2 rows "pdf reader", "pdf writer", "report-compare", III.3, VI.1 to VI.4, D-R2, D-R3, D-R12, D-R13, D-R14; `RUST.md` §8.7, §8.8, §9.4, §9.7; `PDF_IMPORT_HARDENING.md` §5; CLAUDE.md "PDF", "Schemas", workflow gates +- status: R4.0 only. No code and no fixture generated; R4.1 starts on the owner's explicit go. +- not in scope: TTF fonts, `scope_disclaimer`, collection caps on read, opening the import to external users (BDR-040 gate stays open), R5 (pipeline, `packages/anatomy`, `packages/domain`, `documentSha256`), the Safari download fix (separate bugfix), release 0.2.0, any deployment, any visible change + +## 0. Facts this plan rests on (develop ae845c6, inventory 2026-10-17) + +Engine, consumers, tests +- `packages/pdf/src` 3,122 lines: reader (`attachment/scan.ts` 549, `inflate.ts` 83, `read.ts`), writer (`export.ts` 228, `render/*` about 1,250 incl. `observationPage.ts` 634), `branding.ts` 291 (PNG gate), `svg/*` (TS sanitiser and view composition), `text.ts`, `render/dates.ts`, `i18n` (25 labels). Tests: 11 files, 140 cases (scan 39, inflate 9, read 13, security 55, text 5, size 2, goldens 11, raster 2, reexport 1, R3 oracle generators 3). +- App consumers: `src/pdf/{import,export,browserRasterizer}.ts`, `EditorRoute` (type only), `scripts/compare-reports.ts` + `compare/*` (589 lines, 11 cases). PDF-related app suites: pdf.goldens 13, pdf.roundtrip 16, pdf.import 5, archive.envelopes 3, n-1.reader 6, pdf.export.app 2, migration.leaves 2, pdf.browserRasterizer 2, scripts.compare 11, plus route and store suites that mock `@/pdf/*`. Only pdf.goldens, pdf.import and pdf.roundtrip load `pdf-lib`; `apps/app/src` never does. +- `release/0.2.0` and develop carry the same `packages/pdf/src`, and the same archive, report and sheet schemas as the N-1 Zod copy (`git diff release/0.2.0 1a7ee7d` on those directories: empty). One frozen TS scanner plus the N-1 copy therefore stand for the R3 build and for 0.2.0. +- Import today: whole file read on the main thread, TS byte scan, `JSON.parse(new TextDecoder().decode(data))` (scan.ts:498, non-fatal, one BOM stripped), candidate kept if it is an object with a numeric `version` or `envelopeVersion`, then `JSON.stringify` of that object into the core's `archive.import` (sheetOps.ts:33). A trap there poisons the main instance and spends one of its 3 recoveries. +- Rescue copy today: routed on the first KiB (`%PDF-` goes the PDF path), ≤ 16 MiB, `TextDecoder('utf-8', { fatal: true })`, core `draft.restore` on the main instance. + +Writer (pdf-lib 1.17.1 as used) +- Fonts Helvetica, Helvetica-Bold, Times-Roman, WinAnsi, not embedded. Width = Σ(AFM width, 250 when absent, + KPX kerning) × size / 1000; glyphs drawn unkerned. +- Operators: text `q BT rg Tf TL Tm ( Tj T*)+ ET Q` (TL 24, one `Tj T*` per line); image `q cm cm cm cm Do Q`; line `q RG w d m m l S Q`; rectangle `q rg w d cm cm cm m l l l h f Q` (no `re`). Operands printed by `numberToString` (JS shortest round trip with exponent expansion). No opacity, no ExtGState. Resource names `Tag-<10 digits>` from a seeded RNG (deterministic). Streams Flate (pako level 6). Classic xref (`useObjectStreams: false`), no `/ID`. +- Images: PNG fully decoded (UPNG, RGBA8), RGB plane plus a DeviceGray SMask only when an alpha < 255, re-deflated; no dedup. +- Info: Title, Author, Subject, Keywords (`faunosteo-archive/1`), Producer and Creator (`pdf-lib (https://github.com/Hopding/pdf-lib)`) as UTF-16BE hex with BOM; CreationDate and ModDate = `exportedAt` as literal `D:YYYYMMDDHHMMSSZ`. +- Attachment: `JSON.stringify(envelope, null, 2)` in UTF-8, ≤ 16 MiB; EmbeddedFile `/Subtype /application#2Fjson`, Params Size, CreationDate, ModDate; Filespec `/F (osteo-report.json)`, `/UF` and `/Desc` hex UTF-16BE, `/AFRelationship /Data`; catalog `Names/EmbeddedFiles` (key hex UTF-16BE) and `/AF`. +- Links: low-level dict, `Border [0 0 0]`, URI action holding the hex of the ASCII bytes. +- Dates: `Intl.DateTimeFormat` fr-FR and en-US, long month, UTC; input must match `^\d{4}-\d{2}-\d{2}$`, else printed unchanged; `Date.UTC` maps years 0 to 99 to 1900 to 1999 (`0050-03-04` → "4 mars 1950"); a rolled-over date is printed unchanged. +- Text: `safeText` removes `[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]` and replaces non-WinAnsi code points with `?`; `wrapLines` splits on JS `/\s+/`; `toUpperCase` on severity, view and zone names. +- Caps: 500 observations × 8 distinct views (`PAGE_CAPS`); rasters 1200 px wide, aspect clamped to 0.2 to 2.0; the views of one observation rasterised in parallel (`Promise.all`), embedded in order. + +Measurements (Node 24, TS engine, resvg test rasteriser, fr) + +| Report | Views rasterised | PNG in | PDF | Stored attachment | +|---|---|---|---|---| +| v2full nologos | 3 | 1.63 MB | 1.17 MB | 54 KB | +| demo nologos | 7 | 3.75 MB | 2.64 MB | 55 KB | +| demo logos | 8 | 3.79 MB | 2.82 MB | not measured | +| v2unresolved logos | 1 (SVG logo) | 0.03 MB | 0.26 MB | not measured | + +Per view: PNG 526 to 553 KB, decoded RGBA 4.4 to 4.5 MB, about 0.37 MB of image stream in the PDF. Browser canvas PNG sizes: not measured yet (R4.1 baseline). + +Reader experiments (scratch, 2026-10-17) +- `String::from_utf8_lossy` after stripping one leading BOM equals `new TextDecoder().decode` on 200,015 random and edge byte strings (overlongs, UTF-8-encoded surrogates, truncated sequences, double BOM): 0 differences. +- serde_json refuses `1e400` ("number out of range") where `JSON.parse` gives `Infinity`, which `JSON.stringify` then writes `null`. `1e-400`, `-0`, integers beyond u64, long decimals and duplicate keys come out as in the JS path once printed by `js_number`. A lone surrogate escape fails in serde_json (classified `lone_surrogate` since R2). + +Browsers and tooling +- Module workers: Chrome 80, Firefox 114, Safari 15. Documented floor for `'wasm-unsafe-eval'`: Chrome 97, Firefox 102, Safari 16 (DEPLOY.md, which calls it "the Vite 7 baseline"); the Vite 7.3.6 default build target is chrome107, firefox104, safari16. +- Vite 7.3.6: production workers are `iife` by default, asset URLs resolved against `self.location.href`; in dev a classic worker gets `importScripts` while its code keeps ESM imports, so dev needs a module worker. +- CSP (DEPLOY.md, sent `always` by the proxy; `docker/nginx.conf` sends none): `script-src 'self' 'wasm-unsafe-eval'`, no `worker-src`, which falls back to `script-src`: same-origin worker files allowed, `blob:` workers refused. +- Playwright (playwright-core 1.64.0, outside the repository as for the CSP proofs): Chromium present; Firefox 157 installed 2026-10-17 and proven headless (classic and module workers instantiate wasm); WebKit 27.2 downloaded, starts only once `libevent-2.1-7t64` and `libmanette-0.2-0` are installed (sudo, owner). +- WASM: 395.6 KB gzip of the 600 KB budget; linear memory after the editor path 4.1 MiB; sheet bundle text about 522 KB, handle 8 to 10 ms. +- R2 and R3 kept no per-test traceability table (prose census only). + +## 1. Outcome + +The application reads and writes archives with Rust only. An import, PDF or rescue copy, runs in a Web Worker created for it, with its own wasm instance, terminated after the answer, a timeout or a crash: the main instance never sees the file's bytes. The export composes the views in Rust, rasterises them with the existing canvas adapter and writes the PDF in Rust through an incremental session, placed in the main instance or in a disposable worker by the measured rule of §6. Old PDFs read exactly as before. New PDFs render pixel-identically to R3 for the same inputs; the one decided metadata change is Producer and Creator `Faunosteo`. `pnpm report:compare` keeps its name on a Rust binary. `packages/pdf` and `pdf-lib` leave the repository, and every TS test case is traced in a ledger. + +## 2. Owner arbitrations and plan decisions + +Owner, 2026-10-17 +- A1 one feature branch, one final merge, J1 stop once the import is wired. +- A2 old PDFs behave as before; UTF-8 differences documented; any break presented before it is applied. +- A3 years 0 to 99 unchanged (printed 19xx). +- A4 Producer and Creator `Faunosteo`. +- A5 new tracing goldens in `goldens/r4/`; frozen goldens untouched. +- A6 zero render difference; any difference explained, measured, submitted. +- A7 existing user message for import failures; timeout, worker crash and read error told apart technically; 20 s is a hypothesis to measure. +- A8 rescue copies restored through the import worker, same isolation and limits. +- A9 Firefox and WebKit for Playwright; real Safari still required; module workers vs the Firefox 102 floor handled by options (§11), policy unchanged unless the owner decides. +- A10 `pnpm report:compare` kept. +- A11 out of R4: TTF, `scope_disclaimer`, collection caps; the import stays closed to external users. +- A12 WASM budget exceeded: stop and options. +- A13 real anonymised PDFs join the corpus when provided (§7.2). + +Plan decisions (internal; trade-offs stated) +- P1 Replicate the reader, never tighten it. Lossy UTF-8 identical to TextDecoder (measured), one BOM stripped, and the two side effects of the JS path reproduced: a number overflowing f64 becomes `null` before the core reads the text (what `JSON.stringify` did with ±Infinity); a candidate holding a lone surrogate escape is still probed for its numeric version (JSON.parse accepted it) and is then refused by `import_archive` as `lone_surrogate`, as today. `session::import_archive` and the layered readers are not modified (D-R12): R4 adds the byte layer in front of them. Any other difference found by the differential corpus is a stop (A2). +- P2 Content streams come from our own emitter, which reproduces pdf-lib's operator sequences and `numberToString`; `pdf-writer` writes objects, dictionaries, strings, xref and trailer (D-R2). Same operators and operands make the render identical by construction, and give a complete oracle (normalised stream equality) on top of the draw log. +- P3 The writer is an incremental session: begin, raster requests per observation, add rasters, finish. The review's two-call shape holds every PNG in linear memory at once (§6); the session holds one decode at a time and keeps the TS engine's per-observation loop, concurrency and warnings. Image objects are written into the output buffer as soon as their PNG is decoded, so nothing is held twice. Placement by §6.4. +- P4 One worker script for core tasks, one task per worker instance (`import.pdf`, `import.copy`, and `export.pdf` if §6.4 selects it), terminated in a `finally`. +- P5 The default PDF labels (25 keys, two locales) move verbatim from `packages/pdf/src/i18n` to `apps/app/src/pdf/labels.ts` and stay an explicit, archived input (dictionaries stay TypeScript; same key order, so the attachment bytes do not move). +- P6 AFM tables for the three fonts are generated once from the frozen pdf-lib metrics (Adobe Core 14 AFM, APAFML notice committed) and checked against that oracle. +- P7 Cargo tests feed frozen PNGs to the writer; no rasteriser in the workspace (D-R3). +- P8 `exportFromEnvelope` is ported (a bilan reproduced from its own snapshot, branding and labels); no UI (BDR-040). +- P9 New crates: `pdf-writer` (MIT or Apache-2.0), `miniz_oxide` (inflate and deflate, already locked through `image`; one version for the core), `png` (0.18.1, already locked) under decoding limits; `lopdf` as a dev-dependency only. No new npm dependency. + +## 3. Architecture and contracts + +### 3.1 Modules (`crates/core`, features `pdf-read`, `pdf-write`, `cli`; the wasm facade enables both pdf features, the worker crate neither) + +``` +src/pdf/ + read/{header,scan,strings,inflate,probe,stamp}.rs bytes → Attachment | ReadKind + json_js.rs lossy decode, overflow → null, lone-surrogate-tolerant probe (one linear pass with the depth pre-scan) + import.rs import_pdf(sheet, bytes) = read → JS-faithful text → session::import_archive (unchanged) + write/ + input.rs ExportInput + checks (branding and labels schemas, assert_snapshot, read_svg per asset, + sheet ref match, caps), envelope written as JSON.stringify(_, null, 2) with js_number + session.rs ExportSession state machine + views.rs raster requests: compose_highlight (R3) per (observation, view), raster_size_of + layout/{observation,conclusion,header,footer}.rs → DrawLog + text.rs, afm/, dates.rs, png.rs (gate, decode, alpha split), content.rs (emitter, number_to_string), + serialize.rs (pdf-writer) +src/bin/report_compare.rs feature cli, the only file allowed std::fs +``` + +### 3.2 Reader contract (identical to scan.ts, pinned by O8 to O10) + +File ≤ 50 MiB and `%PDF-` within the first 1,024 bytes, else `invalid_pdf`. At most 32 `/Type /EmbeddedFile` dictionaries, each bounded to 4,096 bytes; object header from a 48-byte window; `stream` then `\r\n` or `\n`; a direct `/Length` when it lands on `endstream`, else the length measured up to the first `endstream` within 16 MiB + 16 bytes (one trailing `\n`, then one `\r`, dropped); `/FlateDecode` alone or first in an array, else raw bytes. Names from Filespec dictionaries in clear (`/F`, else `/UF`); `osteo-report*` first (stable), then data offset. One 16 MiB budget shared by the candidates; a cancelled inflation is not charged. A candidate opens on `{` after an optional BOM and JSON whitespace, nests at most 64 levels (raw bytes, strings skipped, a backslash skips one byte), then lossy decode, JS-faithful probe, and the chosen text goes to `import_archive`. No candidate: `attachment_stripped` when a `/Keywords` string (≤ 32 occurrences, 4,096-byte window, hex or literal with the same limited unescape, UTF-16BE with BOM else Latin-1) contains `faunosteo-archive`, else `no_attachment`. Inflation: zlib framing, accepted and refused like `DecompressionStream('deflate')` on O10 (truncated, bad Adler-32, trailing bytes, preset dictionary), output capped by the remaining budget, cancelled beyond it. + +### 3.3 Writer contract + +Input `ExportInput { report, sheetSnapshot, branding, labels, locale, exportedAt }` (ts-rs; `exportedAt` an ISO string from the caller). Errors before any page, with today's kinds: `branding_invalid`, `snapshot_invalid`, `snapshot_too_large`, `sheet_mismatch`, `too_many_pages`. Warnings unchanged: `view_raster_failed { observationId, viewId }`, `logo_failed { slot }`. Output: PDF bytes and warnings. The layout produces a `DrawLog` (per page, in call order: text, image, line, rectangle, link, every argument at full precision); `content.rs` emits pdf-lib's operator sequences; `serialize.rs` writes the catalog (Pages, Names/EmbeddedFiles, AF), A4 pages (595.28 × 841.89), three Type1 fonts with WinAnsiEncoding, image XObjects (DeviceRGB 8 bits, DeviceGray SMask with `Decode [0 1]` when needed), Link annotations, Info (Producer and Creator `Faunosteo`, the rest as today in the same string forms), the attachment objects of §0, a classic xref, no object stream, no `/ID`. + +### 3.4 Facade (`crates/wasm`), JSON strings as before, bytes as `Uint8Array` + +- `SheetHandle.importPdf(bytes) → string`: `{ ok: true, value: ArchiveImport } | { ok: false, kind, detail }`, kinds `invalid_pdf`, `no_attachment`, `attachment_stripped`, `incompatible_version`, `lone_surrogate`, `invalid`, `internal`. The rescue copy keeps `SheetHandle.call('draft.restore', …)`. +- `ExportSession` (wasm-bindgen struct): `new(inputJson)` (throws `": "` like `SheetHandle`), `next() → { kind: 'rasters', requests: [{ key, svg, widthPx, heightPx }] } | { kind: 'done' }`, `addRaster(key, png)`, `rasterFailed(key)`, `finish() → Uint8Array`, `warnings() → string`; `ExportSession.fromEnvelope(envelopeJson, locale, exportedAt)` for P8. +- Linear memory is read from the instance's exported `memory` for diagnostics; no new export. +- ts-rs types committed under `packages/core-wasm/types`: `ExportInput`, `RasterRequest`, `ExportStep`, `ExportWarning`, `PdfImportKind`. + +### 3.5 Core worker protocol (`apps/app/src/core/worker/`, messages tagged `v: 1`) + +1. The main thread creates the worker from a same-origin file (classic in the production build, module in dev: OD-1) and arms the task timer. +2. The worker fetches the shipped module (the main runtime's Vite asset URL), compiles (`compileStreaming`, fallback `compile`), instantiates, posts `{ type: 'ready' }`. A failure before `ready` is `worker_unavailable`. +3. The main thread posts `{ v: 1, task, file, sheet, limits }`: the `File` itself (structured clone of a Blob, nothing read on the main thread) and the bundle text the main runtime already builds (about 522 KB). +4. The worker re-checks `file.size` (50 MiB PDF, 16 MiB copy), reads `file.arrayBuffer()` once, builds a `SheetHandle`, runs `importPdf`, or the strict decode then `draft.restore`, and posts `{ type: 'result', out, diag: { ms, linearBytes } }`. A `WebAssembly.RuntimeError` is caught and posted as `{ type: 'crashed', detail }`. +5. The main thread: `result` → parse → the existing hydrate path; `crashed`, `error` or `messageerror` after `ready` → `crashed`; timer → `timeout`. `terminate()` in every case, timer cleared, references dropped. One task at a time (the Home busy flag already serialises imports). `diag` is printed in DEV only and never sent anywhere. +6. The main runtime is untouched by worker failures (no recovery spent, no poisoning). When it is `stopped`, the import is refused up front with today's stopped text, because the editor could not open the result. +7. Tests: vitest (happy-dom has no `Worker`) runs the worker entry in-process through the client's spawn seam; the real worker runs in the browser harness. + +### 3.6 Export driver + +The main thread computes `archive.snapshot` (needs the sheet, as today), builds `ExportInput` (branding from `loadBranding()`, labels from P5, `new Date()`), then loops: `next()`, rasterise the batch with `browserRasterizer` (`Promise.all`, as today), `addRaster` or `rasterFailed` per request, until `done`; `finish()`, download, warnings alert unchanged. In the worker placement the same loop runs over messages: SVG strings to the main thread, PNGs transferred to the worker, the PDF transferred back. A trap during an export in the main instance spends a recovery as any core call today; in the worker it does not. + +### 3.7 `report-compare` + +A `crates/core` binary behind `cli`, same arguments, output lines and exit codes as the TS CLI (O11, LRN-044 escaping). Root script `report:compare` → `cargo run --release --locked -q -p faunosteo-core --features cli --bin report-compare --` (the development machine's toolchain; the first run compiles). + +### 3.8 Import outcomes and messages (existing keys only) + +| Outcome | Raised by | Message | +|---|---|---| +| file > 50 MiB, no `%PDF-` | main pre-check, worker | `home.import.error_invalid_pdf` | +| `no_attachment` | reader | `error_no_attachment` | +| `attachment_stripped` | reader | `error_attachment_stripped` | +| `incompatible_version` | core | `error_incompatible_version` (version shown) | +| `lone_surrogate` | core | `error_lone_surrogate` | +| `invalid` (rebase refused) | core | `error_generic` (as today) | +| copy > 16 MiB, invalid UTF-8, refused by `draft.restore` | main pre-check, worker | `error_invalid_copy` | +| no bundled sheet; worker cannot start (CSP, script, module, no `Worker`) | main | `error_core_unavailable` (as a failed engine load today) | +| `timeout` or `crashed`, PDF | main | `error_generic` « Erreur de lecture du PDF. » (A7; today a trap showed `error_core_unavailable`) | +| `timeout` or `crashed`, copy | main | OD-3 | +| main runtime stopped | main | `core.stopped` or `core.stopped_unsaved` (unchanged) | +| held session | store | `session.held_blocked*` (unchanged) | + +The technical kind stays in the outcome and in the DEV console. + +## 4. PDF compatibility + +### 4.1 Historical behaviours preserved (each pinned by O8 or O9 rows) + +- H1 bare v2 MVP PDFs with object streams (`report-v2.full.pdf`, `report-v2.minimal.pdf`): migrated through the map. +- H2 bare v3 from Step 5 (`report-v3.bare.pdf`): read as is, rebased when the sheet differs. +- H3 envelopes v1 from Step 6 (pre-R2 key order, O3) and from R2 and R3 (O2): layered reading, report kept when the snapshot is rejected. +- H4 stamped PDFs with object streams: a stripped attachment still reads `no_attachment` (known trade-off). +- H5 several embedded files: `osteo-report*` first, then data order; decoys skipped. +- H6 indirect, wrong or missing `/Length`; `\r\n` after `stream`; `/Type/EmbeddedFile` without a space; hex and literal names; unfiltered streams. +- H7 caps: 50 MiB file, 32 candidates, 4 KiB dictionaries, 16 MiB shared budget, depth 64; bombs refused without memory growth. +- H8 invalid UTF-8 becomes U+FFFD, one BOM stripped (same decoder, measured). +- H9 JSON: a duplicate key keeps the last value at the first position; an overflowing number becomes `null`; a lone surrogate is refused (`lone_surrogate`, R2); numbers are f64. +- H10 encrypted PDF: `no_attachment`. +- H11 every §3.8 message for the same file. +- H12 rescue copy: BOM accepted, strict UTF-8, ≤ 16 MiB, `draft.restore`, `editor.draft_rebased` when rebased. +- Declared, decided at R3 (RUST.md §9.4) and now applied to the PDF path: `exportFromEnvelope` on a foreign archive whose snapshot SVG the R3 reader refuses answers `snapshot_invalid` where the TS sanitised and drew; no product drawing is affected (R3 proof), no interface reaches it. + +### 4.2 Readers that must read R4 PDFs (N-1, review VI.3) + +The frozen TS scanner (O12) and the N-1 Zod copy, standing for the R3 build and 0.2.0 (§0), read every R4 fixture PDF and app-path export; the R3 build, run side by side, reads them at the final acceptance. The live site (pre-Step 6) reads no envelope today; R4 changes nothing there. The DEPLOY.md rollback note says that R3 and 0.2.0 read R4 PDFs. + +### 4.3 Difference classes (R3 build vs R4 build, same inputs) + +Acceptable, no validation needed, each checked by a test: +- B1 Flate bytes of every stream (miniz_oxide vs pako): the decompressed bytes are compared. +- B2 object numbers, order and offsets, header binary comment, xref and trailer layout (both classic xref, no object stream). +- B3 resource names (`/Helvetica-7036340225` → `/F1`, `/Image-…` → `/Im1`): streams compared after normalising names. +- B4 string forms with the same decoded value (literal vs hex) where pdf-writer chooses, such as the link URI. Info, `/UF`, `/Desc` and the names-tree key keep pdf-lib's UTF-16BE hex form, checked by the frozen TS scanner. +- B5 numbers in dictionaries no content depends on, at pdf-writer's `f32` precision (link `/Rect`, under 0.0001 pt), if pdf-writer has no exact primitive; MediaBox expected to print the same (checked). +- B6 dictionary key order, whitespace, structural keys without effect (each listed when found). + +Decided (A4): Producer and Creator `Faunosteo`. Every other Info value identical: Title, Author, Subject, Keywords, CreationDate, ModDate, no `/ID`. + +Not acceptable without the owner (stop, measure, explain, submit): +- a pixel difference in the poppler render (150 dpi on every page; 300 dpi on the real-raster reference); +- a content-stream difference after B3 normalisation; +- a decoded image difference (RGB, alpha, size, bit depth, colour space, SMask presence); +- a draw-log difference (text, font, size, colour, position, line, rectangle); +- the set of links, a URI, or a rect beyond 0.01 pt; page count, size or order; +- the attachment: filename, subtype, Params, Desc, AFRelationship, names tree, `/AF`, or the decompressed JSON bytes (target: byte-identical to the R3 output for the same input; a key-order or formatting change is a contract change, presented with its N-1 proof); +- an import outcome difference on any file of O2, O3, O8, O9, the hostile set or the owner's real PDFs. + +## 5. Import and memory + +- 5.1 Isolation. Untrusted bytes (PDF or copy) are read only inside the worker created for that import. The main instance receives the core's canonical output (validated report and envelope), as it does today after `archive.import`. This closes the R3 residual (16 MiB parsed in the long-lived instance, RUST.md §8.8) and two BLK-012 residuals (a trapping copy spends a main recovery; memory exhaustion near 16 MiB in the main instance). +- 5.2 Transfer. The `File` is posted, never read on the main thread; the worker checks the size, reads once into an ArrayBuffer, copies once into linear memory. The sheet travels per import as the bundle text, the worker builds its own `SheetHandle`; nothing is cached across imports. The result comes back as one JSON string (report and envelope); its cost is measured. +- 5.3 Time. One constant `IMPORT_TIMEOUT_MS` (20 s hypothesis) from creation to answer. R4.3 measures per browser the worker start (cached fetch, compile, instantiate, handle), the largest legitimate archive (demo with logos) and the slowest hostile case; J1 repeats on the owner's devices, the low-end phone included. Rule proposed: timeout ≥ 10 × the slowest legitimate import on the slowest device, and ≥ 2 × the slowest hostile case that completes. The owner sets the value at J1 if the rule moves it away from 20 s. +- 5.4 Destruction. `terminate()` after a result, a crash or a timeout. The harness checks that the content process comes back within 10 MiB of its pre-import level after a forced GC (Chromium CDP `HeapProfiler.collectGarbage`; Firefox `about:memory` minimise at J1). +- 5.5 Errors and recovery. The §3.8 table; no automatic retry (the practitioner picks the file again); the file and the session are never modified; held sessions and the replace dialog behave as today. +- 5.6 Out of memory. A worker bounds the blast radius, not the peak: it shares the tab's content process on every engine, and iOS kills the whole tab beyond its limit. The harness measures the worker peak on the classes that grow memory most: a 16 MiB token-dense JSON attachment (serde_json `Value` expansion, estimated 8 to 30 × in linear memory), the 50 MiB file, the 16 MiB inflation, 32 candidates. Budget W4 below. Options when a class breaks it, each a behaviour change on hostile files only, presented at J1, none applied by default: (a) link the module with `--max-memory` so growth fails as a trap before the OS limit (it also caps the main instance, so it sits above the largest export need of §6); (b) a value-count budget in the existing linear pre-scan; (c) an attachment cap below 16 MiB (real archives are under 0.4 MB); (d) typed deserialisation without the intermediate `Value` (changes the R2 reader, gated). +- 5.7 Browsers: §11. +- 5.8 Rescue copy. Same worker, timeout and termination; the strict UTF-8 decode stays in TypeScript inside the worker (same decoder), `draft.restore` runs in the worker's instance; the routing on the first KiB stays on the main thread (five bytes and the first non-blank byte). + +## 6. Export memory: PNG accumulation in linear memory + +### 6.1 Where the bytes live + +From the measured sizes, a report with V rasterised views takes about 0.54 V MB of PNG input (resvg; browser PNGs measured at R4.1), 4.5 MB of decoded RGBA per view at a time, and yields about 0.08 + 0.37 V MB of PDF. The image streams are our own deflate of the RGB plane, so their size does not depend on the browser. + +| Design | Peak linear memory | Kept by a long-lived instance afterwards | +|---|---|---| +| Two calls (review sketch): every PNG in, then write | ΣPNG + PDF + one decode ≈ 0.91 V + 4.5 MB | the same high-water (linear memory never shrinks) | +| Session in the main instance | PDF + one decode ≈ 0.37 V + 4.5 MB | the same | +| Session in a disposable worker | as above, inside the worker | nothing (worker terminated) | +| TypeScript today (pdf-lib, JS heap) | ≈ PDF + up to 8 PNGs and their decodes | nothing (garbage-collected) | + +Examples, two calls / session: V = 7 (demo) 11 / 7 MB; V = 120 (60 observations, 2 views each) 114 / 49 MB; V = 500: 460 / 190 MB. The cap (500 × 8 = 4,000 views, about 1.5 GB of PDF) is not exportable today either; R4 must not fail earlier than the TS engine does (baseline O13). + +### 6.2 Strategies + +- S1 incremental session (P3), chosen by construction: it takes ΣPNG out of linear memory at no cost on the JS side, which already rasterises per observation. +- S2 disposable export worker: frees the high-water after each export. +- S3 chunked output: image streams handed to JS as Blob parts as they are written, the PDF assembled as a `Blob`; only if S2 still fails on a device. +- S4 visible or behavioural measures (lower raster resolution, a smaller cap): never without the owner. + +### 6.3 Measurement + +Harness in Chromium and Firefox (WebKit once it starts): linear memory after each session step, content-process RSS sampled every 50 ms from `/proc`, JS heap from CDP; reports demo, L (V = 120) and XL (V = 500) built from the demo's observations (O14), and a doubling probe up to failure, for the TS baseline (R4.1) and for R4 (R4.6). Phones: L at the final acceptance. + +### 6.4 Decision rule, fixed now + +Keep the session in the main instance if, for L, the main instance keeps at most 32 MiB more linear memory than before the export and L completes on every test device; otherwise run it in the disposable worker (S2). The sizes above predict S2 (about 49 MB kept for L): the plan budgets it, the measurement confirms or refutes it before R4.6 wires the application. If S2 fails L on a test device: stop and present S3 and S4. + +## 7. Fixtures and oracles + +### 7.1 Frozen with the TS code at R4.1, before any Rust (generators committed behind `MAKE_R4_ORACLES=1`; never regenerated without the owner) + +| Id | Content | Location (planned) | Used by | +|---|---|---|---| +| O1 | draw log, 3 reports × fr/en × logos/nologos = 12 files: every drawText, drawImage, drawLine, drawRectangle and link call in order with all arguments at full precision (the step6 fixed rasterisers and FIXED_EXPORTED_AT) | `apps/app/tests/fixtures/goldens/r4/draw.*.json` | R4.4 | +| O2 | the 12 matching R3-build PDFs, plus one real-raster PDF (v2full fr logos) with its 3 resvg view PNGs and its SVG-logo PNG | `apps/app/tests/fixtures/pdf/r3/` (about 5 MB) | R4.2, R4.5 (normalised streams, image planes, links, Info, attachment), N-1 | +| O3 | pre-R2 envelope PDFs: the three frozen `goldens/r2/envelope.*.json` attached byte for byte by pdf-lib 1.17.1 (Step 6 layout) | `apps/app/tests/fixtures/pdf/step6/` | reader (H3), N-1 | +| O4 | text: widths (strings × sizes × 3 fonts), `wrapLines`, `safeText` over every code point class, JS `toUpperCase` over all code points (differences only), JS `\s`, `Math.round`, `numberToString` (random and edge values) | `crates/core/tests/oracles/r4/text.json` | R4.4 | +| O5 | pdf-lib metrics of the 3 fonts (widths, KPX, WinAnsi map) | `oracles/r4/afm.json` | P6 | +| O6 | `formatDate` fr and en over years 0000, 0001, 0050, 0099, 0100, 0999, 1000, 1900, 1904, 1999, 2000, 2024, 2026, 9999 × months 00 to 13 × days 00 to 32, plus non-matching strings | `oracles/r4/dates.json` | R4.4 | +| O7 | PNG: `pngIssue` verdict for every security-suite PNG, the brand logos and a variant set (palette, palette + tRNS, grey, grey + alpha, 16-bit, RGB, RGBA); for accepted ones, sha256 of pdf-lib's RGB and alpha planes | `oracles/r4/png.json` + small PNGs | R4.5 | +| O8 | reader outcomes for every input of scan, inflate, read and the reader part of security (inputs ≤ 64 KiB committed; bombs as deterministic generators ported to Rust and checked by the sha256 of the generated bytes): kind, chosen candidate, attachment and object digests | `oracles/r4/read.json`, `fixtures/pdf/r4/read/` | R4.2 | +| O9 | differential corpus: UTF-8 classes, BOM, double BOM, overflowing numbers (in `version` and in content), lone surrogate (probe and content), duplicate keys (incl. `version`), integers beyond 2^53 and u64, `-0`, `__proto__`, depth 64 and 65, a first candidate only JSON.parse accepts; outcome of the full R3 path (TS scanner, JSON.parse and stringify, core `archive.import` in wasm) | `fixtures/pdf/r4/tolerance/`, `oracles/r4/tolerance.json` | R4.2 (a difference is a stop, A2) | +| O10 | inflate: valid, empty, truncated, bad Adler-32, trailing bytes, raw deflate without zlib header, preset dictionary, exact cap, cap + 1: `DecompressionStream` verdict and output digest | `oracles/r4/inflate.json` | R4.2 | +| O11 | `report:compare` stdout and exit code on every fixture PDF and the 11 scenarios | `oracles/r4/compare/` | R4.7 | +| O12 | frozen TS scanner: verbatim copy of R3's `attachment/{scan,inflate,read}.ts` and their error module, never edited: the permanent N-1 PDF reader | `packages/core-wasm/tests/n-1/scanner/` | N-1 tests | +| O13 | TS baseline in Chromium and Firefox with the real `browserRasterizer`: PNG bytes per view, export time, RSS peak and after, JS heap, PDF size (demo, L, XL, doubling probe); TS import time and memory on O2 and the hostile set | table in RUST.md §10 (draft) | §5, §6, §10 | +| O14 | synthetic reports L (60 observations × 2 views) and XL (250 × 2) built from the demo | `apps/app/tests/fixtures/r4/reports/` | O13, R4.6 | + +The step6, r2 and r3 goldens and the R3 oracles stay untouched: `git diff --stat` on them is empty at every slice. + +### 7.2 Real PDFs (A13) + +Kept out of git on the development machine (`$FAUNOSTEO_FIELD_CORPUS`), read by an opt-in test; only a table without personal data is committed (sha256, producing build when known, expected outcome, observation count). A file enters git only after the owner reviews its anonymised form (attachment strings and page text replaced by same-length placeholders, structure kept), never automatically. + +## 8. Test traceability + +`crates/core/tests/pdf/LEDGER.tsv`: one row per TS case at the freeze commit, with the TS file, the full case title (describe path, each-row label), a disposition (`ported`, `replaced`, `kept`, `deleted`), the target (cargo `file::test` or vitest `file > title`), the oracle id and a note. Built at R4.1 from vitest's JSON reporter: the 140 engine cases, the PDF-related app cases of §0 and the 11 CLI cases. A census check fails when a frozen case has no row, when a `ported` target is missing from `cargo test -- --list` or the vitest list, or when the counts do not reconcile; the verifier runs it at R4.9. Rust test files keep a header naming their TS source, as at R2 and R3. + +## 9. Slices + +One branch, `feature/rust-r4-pdf-core`, cut from develop once this plan is merged. Every slice ends green on `pnpm rust:check`, `pnpm wasm:build` and `pnpm check`, its proof recorded in the TODO and in RUST.md §10. + +| Slice | Deliverable | Proof | +|---|---|---| +| R4.1 Freeze | O1 to O14, ledger, browser harness (`scripts/browser/`, Playwright kept outside the repository) | generators committed, frozen goldens untouched, suites green, baseline table; no Rust | +| R4.2 Reader | `pdf::read`, `json_js`, `pdf::import`, `SheetHandle.importPdf`; scan, inflate, read and reader-security suites in cargo on O8 and O10; O9 differential; hostile corpus through the wasm build (Node, fresh instance per case, time and linear memory) | 0 oracle difference, 0 differential difference (else stop, A2), no trap outside declared memory cases, W1 | +| R4.3 Import worker and rescue copy | §3.5 client and entry; HomeRoute on the worker (routing and pre-checks unchanged); OD-1 applied; client tests (ready, timeout, crash, messageerror, unavailable, terminate always, main runtime untouched); a message-table test over O2, O3, O9 and the hostile set; 612 leaves through the worker (export still TS); CSP proof on the app image with and without `'wasm-unsafe-eval'` in Chromium and Firefox (WebKit when it starts); time and memory measured | same messages as R3 on every file, tab responsive during hostile imports (W5), memory back to baseline (W4), P-W1 | +| J1 Owner checkpoint, no merge | production build (`SHEET_BUNDLE=draft`) behind the DEPLOY CSP on the DEV origin (port agreed with the owner, ENVIRONMENTS.md); a French checklist; old PDFs (v2 MVP, v3 Step 5, Step 6 and R3 envelopes), O2, a hostile folder with the expected message per file, rescue copies (valid, BOM, invalid UTF-8, oversized, refused), engine unavailable during an import; memory and time per device | owner OK; timeout value; OD-1 confirmed on real browsers; 5.6 options decided if needed; results in PDF_IMPORT_HARDENING §5 (gate still open) | +| R4.4 Layout | text, AFM, dates, upper-casing, `safeText`, `wrapLines`, the four layouts → DrawLog | O1 (12) exact at full precision, step6 text and images (24) exact, O4 to O6 exact | +| R4.5 Serialiser | emitter, pdf-writer, PNG gate and decode, links, Info, attachment, `exportFromEnvelope`; export-side security, size, reexport and text suites in cargo | against O2: normalised streams equal, image planes equal, links (lopdf) and step6 links (12) equal, Info equal except Producer and Creator, attachment bytes equal (else declared, A6); `qpdf --check` clean; `pdfdetach -list` shows `osteo-report.json`; poppler diff 0 px; O12 and the N-1 copy read every R4 PDF; E2; digests of the R4 outputs in `goldens/r4/pdf.*.sha256` (wasm output = native output) | +| R4.6 App export | session driver, placement by §6.4 measured first, `labels.ts` (P5), `export.ts` on the session; alerts unchanged | app suites; app-path bytes = native digests; step6 views via the app path; browser rasters of the Rust- and TS-composed views pixel-identical (Chromium, Firefox, WebKit when it starts; the TS composition still exists here); E3, E4; 612 leaves exported and re-imported on Rust | +| R4.7 report-compare | Rust binary, `pnpm report:compare` unchanged | O11 and the 11 cases in cargo | +| R4.8 Deletions and docs | `packages/pdf` (with the R3 oracle generators; the frozen oracle files stay), `@faunosteo/pdf` and `pdf-lib` in apps/app, the TS CLI, the pdf-lib-based tests rewritten per the ledger; N-1 test on O12; RUST.md §10, PDF-FORMAT, PDF_IMPORT_HARDENING §5, DEPLOY (rollback note, worker CSP note, floor line), CHANGELOG, CLAUDE.md, TEST_STRATEGY, WORKSPACE, packages/README, fixtures README (R4 freeze section) | `pnpm check:all` green, ledger census green, D1 | +| R4.9 Gates and acceptance | verify contract, fresh verifier, fresh security audit; owner acceptance (§12), after the separate Safari download fix has merged | verifier CONFORME, security PASS, owner's explicit merge signal | + +## 10. Budgets (measured, recorded in RUST.md §10) + +| Id | Budget | Measured by | +|---|---|---| +| W1 | served module ≤ 600 KB gzip -9; reported at 550 KB; above 600: stop (A12) | `size.test.ts`, every slice | +| W2 | worker start + largest legitimate import ≤ 1 s on the development machine (Chromium, CPU × 4); recorded per J1 device | harness, J1 | +| W3 | timeout value per the 5.3 rule | harness, J1 | +| W4 | worker linear memory ≤ 256 MiB on every hostile class; the tab survives on every device; the content process back within 10 MiB after GC | harness, J1 | +| W5 | main-thread long tasks during an import ≤ 50 ms, hydrate and navigation excluded | Chromium trace | +| E1 | render difference 0 px (poppler 150 dpi; 300 dpi on the real raster) | cargo + poppler | +| E2 | PDF size ≤ R3 + 5 %; stored attachment < 250 KB (demo with logos) | cargo | +| E3 | export time ≤ 1.2 × the TS baseline (demo, L) in Chromium | harness | +| E4 | §6.4 rule for L; XL completes on the development machine; the doubling probe fails no earlier than the TS baseline | harness | +| T1 | every frozen case dispositioned in the ledger | census | +| D1 | no `pdf-lib` or `@pdf-lib/*` in the lockfile; no `@xmldom/xmldom` in apps/app's closure (kept by `packages/anatomy` until R5) | lockfile, `pnpm why` | + +## 11. Browser compatibility + +- Floor as documented: Chrome 97, Firefox 102, Safari 16 for the keyword. The bundle's syntax target is already Firefox 104 (Vite 7 default): a doc inaccuracy that R4.8 corrects in DEPLOY.md whatever OD-1 decides. +- Firefox 102 to 113 lacks module workers. OD-1 options: + - A, recommended: a classic worker in the production build (Vite's default `iife` format, constructor without `type: 'module'` in the build), a module worker in dev only. Keeps the floor and one production path. Proof P-W1 at R4.3: the built worker runs under the production CSP in Chromium, Firefox 157, WebKit (once it starts), and Firefox ESR 102 and 115 binaries downloaded to a scratch directory (Playwright cannot drive a stock Firefox: a test page posts its result to the harness). Cost: worker type differs between dev and production, so J1 runs on the production build. + - B: raise the documented floor to Firefox 115 ESR (module workers everywhere, one worker type in dev and build). A policy change, the owner's decision; DEPLOY.md updated. + - C: feature detection with a main-thread fallback: two import paths, isolation lost where it applies. Not recommended. + - D: refuse the import without module workers: a regression on old Firefox. Not recommended. +- CSP: the worker is a same-origin hashed file under `/assets/`, allowed by `script-src 'self'`; its response carries the proxy's CSP, `'wasm-unsafe-eval'` included; no `blob:` or inline worker. No CSP change is needed; DEPLOY.md gains a note. Without the keyword the import answers `error_core_unavailable`, with no fallback. +- Safari: automated only once WebKit starts (OD-7); real Safari (macOS when available, iOS) at J1 and at the final acceptance. The PDF download revokes its URL at once (`EditorRoute.tsx:245`), which WebKit may cancel: separate bugfix before the final iPhone acceptance, outside R4. +- APIs in the worker: `Blob.arrayBuffer` (Firefox 69, Safari 14), `WebAssembly.compileStreaming` with the main runtime's fallback, `TextDecoder`, `postMessage` with transfer: all under the floor. + +## 12. Checkpoints, stop rules, exit criteria + +- Checkpoints: (1) this plan, validated by the owner, then merged (OD-2); (2) J1 after R4.3; (3) the final acceptance after R4.9. +- Stop rules (stop, measure, present): W1 above 600 KB; a reader or differential difference (A2); a §4.3 "not acceptable" difference; a visible change found necessary; S2 failing §6.4; a W4 class breaking its budget; a failed proof (P-W1, CSP); any change needed inside the gated readers (`import_archive`, `read_archive_document`, `rebase_report_on_sheet`; D-R12). +- J1 exit: the import runs on Rust in the worker; the §3.8 messages match R3 on every file; measurements recorded in PDF_IMPORT_HARDENING.md §5; OD-1, the timeout and any 5.6 option decided. +- Final acceptance (owner, LAN, production build behind the DEPLOY CSP): FR and EN exports of the three reference reports and of a new bilan, on computer and phone; viewers (Chrome, Firefox, Acrobat, Preview or Files, Android): pages, attachment listed, properties (Producer Faunosteo), footer links; a side-by-side R3 vs R4 page with per-page differences, preceded by an R3 vs R3 run that measures the browser's own noise; 400 % zoom; print preview and a paper print; accents in pages and properties; R4 PDFs imported into the R3 build run side by side; R4 PDFs re-imported (same bilan); engine unavailable during an import and an export. +- R4 exit (merge): the review's VI.2 R4 criteria as amended here, the §4.3 proofs, the ledger census, the budgets, J1 and the final acceptance, verifier CONFORME, security PASS, `pnpm check:all` green, the owner's explicit merge signal. + +## 13. Risks + +| Risk | Mitigation | Detection | +|---|---|---| +| Writer exactness: float order, `Math.round`, kerning, upper-casing, the Cf table, dates | port expression by expression; full-precision O1; O4 to O6 | O1, normalised streams | +| pdf-writer's `f32` or string forms break a form the N-1 scanner needs (Keywords, Filespec) | UTF-16BE hex written as pdf-lib does; B5 only for numbers nothing reads | O12 read-back, byte test | +| Reader divergence on foreign or old PDFs | O8, O9, the owner's real PDFs | stop rule A2 | +| miniz_oxide and DecompressionStream accept different streams | O10 | cargo | +| Worker type, CSP or wasm in workers on Firefox and Safari | OD-1 and P-W1, CSP proof on three engines, J1 on real devices | R4.3, J1 | +| Memory exhaustion despite the worker (iOS kills the tab) | W4 classes measured, 5.6 options | harness, J1 | +| Export memory | session by construction, §6.4 rule | harness | +| WASM size (+100 to 150 KB estimated) | three fonts only, features, measured per slice | W1 | +| A test lost in the migration | ledger census | R4.8, verifier | +| Browser canvas noise hides or invents differences in the final comparison | R3 vs R3 noise run first; automated proofs use frozen PNGs | final acceptance | +| Largest phase of the roadmap | J1 split, per-slice proofs, stop rules | slice reports | +| Two PDF stacks coexist until R4.8 | the TS stays frozen (no new logic), deleted in one slice | grep census | + +## 14. Kept and deleted (consumers named) + +- Deleted at R4.8: `packages/pdf/**` (last consumers: app import at R4.3, app export at R4.6, CLI at R4.7, tests per the ledger), `apps/app/scripts/compare-reports.ts` and `compare/*`, `@faunosteo/pdf` and `pdf-lib` in apps/app, `@resvg/resvg-js` and `@pdf-lib/*` with packages/pdf. +- Kept: `browserRasterizer.ts` (DOM adapter), `loadBranding` and `src/assets/brand`, `packages/anatomy/render` and `packages/domain` (pipeline, R5), the frozen R3 oracle files (their generators go with packages/pdf; never regenerated), the N-1 Zod copy, O12. + +## 15. Open decisions for the owner + +| # | Question | Recommendation | +|---|---|---| +| OD-1 | Module workers vs the Firefox 102 floor | A, classic worker in production, proven by P-W1; if P-W1 fails, B (floor Firefox 115 ESR) for your decision | +| OD-2 | Branches: this plan on `chore/rust-r4-plan`, merged at validation; then the Safari fix off develop; then `feature/rust-r4-pdf-core` cut from develop (one feature branch, one feature merge, no sync of develop into it) | yes | +| OD-3 | Message when a rescue copy times out or crashes the worker | `error_invalid_copy` (accurate: refused, file untouched); alternative `error_generic` | +| OD-4 | A PDF that crashes the reader moves from « Le moteur de lecture n'a pas pu être chargé. Réessayez l'import. » (today's trap mapping) to « Erreur de lecture du PDF. » (A7) | confirm | +| OD-5 | A worker that cannot start keeps « Le moteur de lecture n'a pas pu être chargé. Réessayez l'import. » | yes | +| OD-6 | J1 devices and browsers (computer, iPhone, low-end Android) and the LAN port of the J1 build | your list | +| OD-7 | WebKit system packages: `sudo apt-get install libevent-2.1-7t64 libmanette-0.2-0` | install before R4.3 | +| OD-8 | Slot of the Safari download fix | right after this plan's validation, before the feature branch | +| OD-9 | Repository weight of O2 (about 5 MB of PDFs and PNGs) | accept | + +Scheduled later: the timeout value and the 5.6 options (J1), the §6.4 outcome (reported at R4.6), any §4.3 "not acceptable" difference (stop rule). + +## 16. Tracked outside R4 + +- Safari PDF download fix (separate bugfix, before the final iPhone acceptance). +- The worker container ignores SIGTERM: Docker kills it after 10 s, the job resumes after its lease expires (chore, for example `init: true` in compose). +- README test counter stale (367; 1,015 at the R3 merge).