contacts: stream vCard imports with duplicate suggestions #800

Closed
kayg wants to merge 1 commit from feat/contacts-import into dev
Owner

Plan (foundational; read this first)

Contacts D12: vCard import plan

Goal

Add an authenticated, streaming .vcf upload to the existing contacts import
job. Return durable per-card outcomes, preserve the existing all-at-once notes
job and crash recovery, and suggest possible duplicates without merging them.
The current limits remain 20,000 cards and 100 MiB.

Scope and decisions

  • Add POST /api/v1/contacts/import, authenticated through the existing
    Signed extractor. It accepts raw text/vcard and legacy text/x-vcard
    request bodies, not JSON or multipart. The file name is not trusted or used.
  • Read Body frames directly. Reject a declared or observed body over 100 MiB;
    count BEGIN:VCARD records as bytes arrive and reject record 20,001 before
    collecting the complete request. Split cards while retaining the physical
    line containing each BEGIN:VCARD.
  • Reject an empty or non-vCard document before creating a job. Invalid UTF-8
    and malformed cards become failed per-card results when card boundaries are
    recoverable; valid neighboring cards still import.
  • Follow ADRs 0063 and 0064: accept vCard 3.0 and 4.0. Report vCard 2.1 as a
    per-card failure with an explicit unsupported-version reason. The contacts
    converter deliberately excludes 2.1, whose quoted-printable and charset
    rules differ from 3.0. Do not relabel 2.1 as 3.0 or risk corrupting bytes.
  • Derive the route's action idempotency key from BLAKE3 of the exact uploaded
    bytes. A retry or upload of the same file replays the original durable job.
    The existing UID and byte identity checks continue to suppress repeated
    cards when callers use a different key.
  • Extend the import result to count imported, updated, skipped, and
    failed. Every card result has its 1-based source line, status, and contact
    ID or reason. Same UID with changed card data updates that contact using the
    contacts merge rules inside the import bulk job; an unchanged card is
    skipped. A different UID with matching contact facts remains a separate
    imported contact and gets a suggestion.
  • Suggestions use exact normalized email, explicitly international E.164 phone,
    or full name after case and punctuation normalization. Local phone numbers
    never gain a guessed country code. Fuzzy name matching is deferred.
  • Retain at most 9 representatives per exact key, 8 suggestions per incoming
    card and 10,000 suggestions per import. Keys over 1 KiB are not indexed.
    duplicate_suggestions_limited reports that an output budget was reached;
    results are samples, not a complete enumeration. Suggestions never merge.
  • One shared ImportLimits checker runs before streaming card buffers grow and
    before direct action callers reach identity extraction or either parser.
    Caps: 2 MiB/unfolded line, 4,096 physical lines including blanks/folds (also
    bounds properties), 8 MiB/card, 4 MiB/total encoded PHOTO content-line bytes.
    A discarded card has a durable skipped result with a too large reason.
    Its neighbors continue; accepted original bytes remain unchanged.
  • Store the complete result and suggestions with the import job so retries and
    crash recovery return the same summary. Keep original vCard bytes, including
    inline photos, in the existing contact history companion.
  • Add fixtures using only fictional names, example.test addresses, and
    reserved 555-01xx numbers.

Size and complexity

Estimated size: 5 to 7 small Rust files changed or added, about 450 to 700
implementation lines and 300 to 500 test lines. No new parser or phone-number
dependency is planned.

Let B be uploaded bytes, I incoming cards, K the total bytes in existing
and incoming matching keys, and S retained suggestions. Framing, budget checks
and conversion scan O(B) bytes. Exact hash indexing and lookup take expected
O(K + I + S) work: each key retains at most 9 IDs and each incoming card
returns at most 8 matches. S <= 10,000; identical-name/email groups never
materialize pairs. There are no deletion signatures or edit-distance checks.
The checker uses constant space and each streaming card buffer is bounded by
8 MiB, then freed immediately on overflow. Accepted upload bytes total at most
100 MiB. Index space is linear in key bytes and contact IDs; large existing
name fields never expand into per-character allocations. Existing path selection
remains O(I log I) and is independent of suggestion matching.

Failure table

Case Effect and detection Recovery Test
Huge file Content-Length or streamed byte count exceeds 100 MiB; return 413 before accepting more bytes; no job starts Retry with a smaller .vcf Body above limit, including absent or false Content-Length
More than 20,000 cards The 20,001st BEGIN:VCARD is seen while streaming; return 413 before full buffering; no job starts Split the export into smaller files Chunked input crossing the card limit
Malformed card Import result marks only that card failed with source line and parser reason Correct and retry the card/file Malformed card between two valid synthetic cards
Mixed encodings vCard 3.0/4.0 are UTF-8; invalid UTF-8 fails only its card when framing is recoverable Re-export as UTF-8 or fix that card Valid UTF-8 and one invalid byte sequence in one upload
vCard 2.1, 3.0, 4.0 2.1 is a per-card unsupported-version failure per ADR 0063; 3.0 and 4.0 import Re-export 2.1 as 3.0 or 4.0 Synthetic fixture for each version and a mixed-version file
Per-card limits Stop retaining overlong unfolded lines, excessive physical lines/properties, card bytes or total encoded PHOTO bytes before parsing; skipped: too large Continue at END/next BEGIN; retry smaller card Each cap, ordinary/folded FN, blank/property floods, bounded buffer and work
Inline photos Keep accepted original bytes unchanged; never fetch photo URLs Retry with a smaller card if over limit Folded/grouped photo and original-byte round trips
Crash mid-import Existing durable bulk plan resumes on restart; no partially duplicated import Retry same bytes; BLAKE3 action key replays the job Create, update-only and mixed create/update kill/recovery and durable-summary replay
Same file twice Exact upload replays by BLAKE3; changed request keys still use stored UID/byte identities Return the original summary or skipped card outcomes without another contact Upload identical bytes twice; assert note and card counts
Possible duplicate Matching facts produce reasoned suggestions only; no contact is modified by suggestion matching User decides later in UI Email, E.164 phone, exact name, no-match, and no-auto-merge cases

Gates

Run on cua@calternal-dev-02-std inside the Nix dev shell and through
~/bin/slot:

  • cargo fmt --all -- --check
  • cargo clippy -j4 -p calternal-contacts -p calternal-contacts-actions -p calternal-server --all-targets -- -D warnings
  • cargo test -j4 -p calternal-contacts
  • cargo test -j4 -p calternal-contacts-actions
  • cargo test -j4 -p calternal-server

Sources and format notes

  • RFC 2426: vCard 3.0 removed
    vCard 2.1 quoted-printable and in-card CHARSET; 3.0 requires TYPE= on
    parameters and supports folded inline binary values.
  • RFC 6350: vCard 4.0 uses
    UTF-8, CRLF lines, and continuation folding that must not split a UTF-8
    character.
  • Apple Contacts vCard settings
    say 3.0 is the default and 2.1 has a separate encoding choice.
  • Apple's vCard compatibility help
    confirms exports default to 3.0 and can be re-exported as 2.1 with encoding
    adjusted.
  • Google Contacts export help
    offers CSV or vCard but does not promise a vCard version.
  • Microsoft Outlook vCard help
    documents .vcf sharing, while its duplicate prompt
    lets a person choose update or create-new. Microsoft's pages do not promise a
    vCard version, so this plan follows the Calternal converter's 3.0/4.0
    contract instead of guessing.

Implementation tasks

Task 1: Durable import summary, updates, and duplicate suggestions

Interfaces: extend contacts.import without breaking existing {cards} callers;
the server route will pass source line numbers and recoverable parser failures.
Keep each result and every suggestion in the bulk job summary.

Steps:

  1. Add failing action tests for 1-based source lines, imported/updated/skipped/
    failed results, same-UID updates, exact-key replay, and duplicate suggestions
    by email, E.164 phone, and exact name.
  2. Run the contacts-actions tests on dev-02 and confirm the new expectations fail
    because the result contract and suggestion matching are missing.
  3. Implement the result contract and matching in the contacts action, storing it
    in the existing resumable bulk job. Preserve same-UID update merge semantics
    and never merge suggested contacts.
  4. Run the contacts-actions tests on dev-02.

Expected: new tests fail before implementation, then pass; prior contacts-actions
tests remain green.

Task 2: Authenticated streaming vCard upload route

Interfaces: POST /api/v1/contacts/import accepts text/vcard and
text/x-vcard; it authenticates before reading and invokes contacts.import
with a BLAKE3 key over exact request bytes.

Steps:

  1. Add failing server tests for authentication, media-type and non-vCard
    rejection, declared and streamed size limits, the 20,001st card, physical
    source lines, and exact-file replay.
  2. Run the server tests on dev-02 and confirm the new route is absent.
  3. Implement frame-by-frame parsing that enforces byte and card limits before
    collecting the full request, and forwards card lines and parse failures to
    the durable import action.
  4. Run the server tests on dev-02.

Expected: route tests fail before implementation, then pass; request bodies over
either limit never dispatch an import action.

Task 3: Full gates and branch review

Interfaces: the route, action result, and converter must agree on 3.0/4.0 input,
per-card failures, and line numbers. No UI changes.

Steps:

  1. Run formatting, clippy with warnings denied, and the contacts,
    contacts-actions, and server test suites on dev-02 through ~/bin/slot.
  2. Review the full branch against this plan, fix any important defect with a
    failing test first, and update the PR with exact gate results.

Expected: every listed gate passes; the branch remains unmerged and the PR
continues to target dev.

Round 1 implementation status

Head: ae2cbf27fa31e43a3ce6dfd2b90bf439427c94cf. All steps committed and pushed; no merge. Ready for the next independent review (round 1 fixes, maximum 3 review rounds).

Finding / gap Status Result
P1: quadratic duplicate suggestions Fixed Exact normalized email, E.164 phone and full-name hash maps; at most 9 representative IDs/key, 8 suggestions/card and 10,000/import. No exhaustive candidate/pair collection. duplicate_suggestions_limited reports omitted possibilities.
P1: unbounded name signatures Fixed Removed fuzzy rolling/deletion signatures entirely. Matching keys above 1 KiB are omitted while original fields remain intact. Exact-name index storage/work is linear in indexed facts. Fuzzy matching is a follow-up.
P1: unbounded parser line/property allocations Fixed Shared constant-space ImportLimits/ImportBudget, enforced before streaming buffers grow and before direct-action identity/parsing: 2 MiB unfolded line, 4,096 physical lines including blanks/folds (also bounds properties), 8 MiB card, 4 MiB total encoded PHOTO content lines. Oversized cards are discarded and durably reported as skipped with too large; neighbors continue.
Hostile input regressions Passed Ordinary/folded huge FN, blank/property floods, each structural/byte/PHOTO cap, embedded CR vs CRLF, split frames, bounded retained buffer; 20,000 identical-name/email matching facts assert bounded index/output and time.
Missing END recovery Passed Next BEGIN fails only the unfinished card and preserves the next card's physical line.
Mixed 2.1 / 3.0 / 4.0 upload Passed 2.1 fails explicitly; 3.0 and 4.0 survive in one request.
Update-only / mixed create+update crash and replay Passed Seven new kill/recovery cases at prepared/planned/committed and mixed mid-job; note/card consistency, separate creates, original update ID and durable summary replay.

Final gates on cua@calternal-dev-02-std, in the Nix dev shell, under ~/bin/slot:

Exact command Status
cargo fmt --all -- --check Passed
cargo clippy -j4 -p calternal-contacts -p calternal-contacts-actions -p calternal-server --all-targets --locked -- -D warnings Passed
cargo test -j4 -p calternal-contacts --locked Passed, 132 tests
cargo test -j4 -p calternal-contacts-actions --locked Passed, 145 tests
cargo test -j4 -p calternal-server --locked Passed, 35 tests

Resource checks ran the compiled regression test executables under the same Nix/slot wrapper, using Python os.wait4 peak RSS and wall-clock measurements with hard assertions of <128 MiB / <10 s for the 20,000-fact matcher and <256 MiB / <10 s for the hostile streaming-card test. These measure those isolated components, not peak RSS for a full disk import. Regression tests also assert the scanner's constant state, bounded per-card buffer, fixed bucket sizes and at most 10,000 serialized suggestions (<2 MiB).

Decisions/limits: suggestions are bounded samples and fuzzy matching is deferred; very large cards/photos or unusually folded/property-heavy cards are skipped by the explicit limits above. Accepted original vCard bytes, unknown fields and photos remain intact. No independent re-review has been performed by this implementation agent.

Final-head resource measurements: matcher peak RSS 28,668 KiB, 0.184 s; hostile-card stream peak RSS 28,896 KiB, 0.109 s. Both hard memory/time assertions passed. Final gate log: ~/pr800-r1-locked.log on dev-02; it records the head SHA and ends with RESOURCE_GATES_PASSED and ALL_GATES_PASSED.

## Plan (foundational; read this first) # Contacts D12: vCard import plan ## Goal Add an authenticated, streaming `.vcf` upload to the existing contacts import job. Return durable per-card outcomes, preserve the existing all-at-once notes job and crash recovery, and suggest possible duplicates without merging them. The current limits remain 20,000 cards and 100 MiB. ## Scope and decisions - Add `POST /api/v1/contacts/import`, authenticated through the existing `Signed` extractor. It accepts raw `text/vcard` and legacy `text/x-vcard` request bodies, not JSON or multipart. The file name is not trusted or used. - Read `Body` frames directly. Reject a declared or observed body over 100 MiB; count `BEGIN:VCARD` records as bytes arrive and reject record 20,001 before collecting the complete request. Split cards while retaining the physical line containing each `BEGIN:VCARD`. - Reject an empty or non-vCard document before creating a job. Invalid UTF-8 and malformed cards become failed per-card results when card boundaries are recoverable; valid neighboring cards still import. - Follow ADRs 0063 and 0064: accept vCard 3.0 and 4.0. Report vCard 2.1 as a per-card failure with an explicit unsupported-version reason. The contacts converter deliberately excludes 2.1, whose quoted-printable and charset rules differ from 3.0. Do not relabel 2.1 as 3.0 or risk corrupting bytes. - Derive the route's action idempotency key from BLAKE3 of the exact uploaded bytes. A retry or upload of the same file replays the original durable job. The existing UID and byte identity checks continue to suppress repeated cards when callers use a different key. - Extend the import result to count `imported`, `updated`, `skipped`, and `failed`. Every card result has its 1-based source line, status, and contact ID or reason. Same UID with changed card data updates that contact using the contacts merge rules inside the import bulk job; an unchanged card is skipped. A different UID with matching contact facts remains a separate imported contact and gets a suggestion. - Suggestions use exact normalized email, explicitly international E.164 phone, or full name after case and punctuation normalization. Local phone numbers never gain a guessed country code. Fuzzy name matching is deferred. - Retain at most 9 representatives per exact key, 8 suggestions per incoming card and 10,000 suggestions per import. Keys over 1 KiB are not indexed. `duplicate_suggestions_limited` reports that an output budget was reached; results are samples, not a complete enumeration. Suggestions never merge. - One shared `ImportLimits` checker runs before streaming card buffers grow and before direct action callers reach identity extraction or either parser. Caps: 2 MiB/unfolded line, 4,096 physical lines including blanks/folds (also bounds properties), 8 MiB/card, 4 MiB/total encoded PHOTO content-line bytes. A discarded card has a durable `skipped` result with a `too large` reason. Its neighbors continue; accepted original bytes remain unchanged. - Store the complete result and suggestions with the import job so retries and crash recovery return the same summary. Keep original vCard bytes, including inline photos, in the existing contact history companion. - Add fixtures using only fictional names, `example.test` addresses, and reserved `555-01xx` numbers. ## Size and complexity Estimated size: 5 to 7 small Rust files changed or added, about 450 to 700 implementation lines and 300 to 500 test lines. No new parser or phone-number dependency is planned. Let `B` be uploaded bytes, `I` incoming cards, `K` the total bytes in existing and incoming matching keys, and `S` retained suggestions. Framing, budget checks and conversion scan `O(B)` bytes. Exact hash indexing and lookup take expected `O(K + I + S)` work: each key retains at most 9 IDs and each incoming card returns at most 8 matches. `S <= 10,000`; identical-name/email groups never materialize pairs. There are no deletion signatures or edit-distance checks. The checker uses constant space and each streaming card buffer is bounded by 8 MiB, then freed immediately on overflow. Accepted upload bytes total at most 100 MiB. Index space is linear in key bytes and contact IDs; large existing name fields never expand into per-character allocations. Existing path selection remains `O(I log I)` and is independent of suggestion matching. ## Failure table | Case | Effect and detection | Recovery | Test | |---|---|---|---| | Huge file | `Content-Length` or streamed byte count exceeds 100 MiB; return 413 before accepting more bytes; no job starts | Retry with a smaller `.vcf` | Body above limit, including absent or false `Content-Length` | | More than 20,000 cards | The 20,001st `BEGIN:VCARD` is seen while streaming; return 413 before full buffering; no job starts | Split the export into smaller files | Chunked input crossing the card limit | | Malformed card | Import result marks only that card failed with source line and parser reason | Correct and retry the card/file | Malformed card between two valid synthetic cards | | Mixed encodings | vCard 3.0/4.0 are UTF-8; invalid UTF-8 fails only its card when framing is recoverable | Re-export as UTF-8 or fix that card | Valid UTF-8 and one invalid byte sequence in one upload | | vCard 2.1, 3.0, 4.0 | 2.1 is a per-card unsupported-version failure per ADR 0063; 3.0 and 4.0 import | Re-export 2.1 as 3.0 or 4.0 | Synthetic fixture for each version and a mixed-version file | | Per-card limits | Stop retaining overlong unfolded lines, excessive physical lines/properties, card bytes or total encoded PHOTO bytes before parsing; skipped: too large | Continue at END/next BEGIN; retry smaller card | Each cap, ordinary/folded FN, blank/property floods, bounded buffer and work | | Inline photos | Keep accepted original bytes unchanged; never fetch photo URLs | Retry with a smaller card if over limit | Folded/grouped photo and original-byte round trips | | Crash mid-import | Existing durable bulk plan resumes on restart; no partially duplicated import | Retry same bytes; BLAKE3 action key replays the job | Create, update-only and mixed create/update kill/recovery and durable-summary replay | | Same file twice | Exact upload replays by BLAKE3; changed request keys still use stored UID/byte identities | Return the original summary or skipped card outcomes without another contact | Upload identical bytes twice; assert note and card counts | | Possible duplicate | Matching facts produce reasoned suggestions only; no contact is modified by suggestion matching | User decides later in UI | Email, E.164 phone, exact name, no-match, and no-auto-merge cases | ## Gates Run on `cua@calternal-dev-02-std` inside the Nix dev shell and through `~/bin/slot`: - `cargo fmt --all -- --check` - `cargo clippy -j4 -p calternal-contacts -p calternal-contacts-actions -p calternal-server --all-targets -- -D warnings` - `cargo test -j4 -p calternal-contacts` - `cargo test -j4 -p calternal-contacts-actions` - `cargo test -j4 -p calternal-server` ## Sources and format notes - [RFC 2426](https://www.rfc-editor.org/rfc/rfc2426.html): vCard 3.0 removed vCard 2.1 quoted-printable and in-card `CHARSET`; 3.0 requires `TYPE=` on parameters and supports folded inline binary values. - [RFC 6350](https://www.rfc-editor.org/rfc/rfc6350.html): vCard 4.0 uses UTF-8, CRLF lines, and continuation folding that must not split a UTF-8 character. - [Apple Contacts vCard settings](https://support.apple.com/en-euro/guide/contacts/adrbk1512/mac) say 3.0 is the default and 2.1 has a separate encoding choice. - [Apple's vCard compatibility help](https://support.apple.com/en-vn/guide/contacts/adrbk1526/mac) confirms exports default to 3.0 and can be re-exported as 2.1 with encoding adjusted. - [Google Contacts export help](https://support.google.com/contacts/answer/7199294?co=GENIE.Platform&hl=en) offers CSV or vCard but does not promise a vCard version. - [Microsoft Outlook vCard help](https://support.microsoft.com/en-us/outlook/send-and-save-contacts-as-vcards-vcf-files) documents `.vcf` sharing, while [its duplicate prompt](https://support.microsoft.com/en-us/outlook/create-and-share-contacts-as-electronic-business-cards) lets a person choose update or create-new. Microsoft's pages do not promise a vCard version, so this plan follows the Calternal converter's 3.0/4.0 contract instead of guessing. ## Implementation tasks ### Task 1: Durable import summary, updates, and duplicate suggestions Interfaces: extend `contacts.import` without breaking existing `{cards}` callers; the server route will pass source line numbers and recoverable parser failures. Keep each result and every suggestion in the bulk job summary. Steps: 1. Add failing action tests for 1-based source lines, imported/updated/skipped/ failed results, same-UID updates, exact-key replay, and duplicate suggestions by email, E.164 phone, and exact name. 2. Run the contacts-actions tests on dev-02 and confirm the new expectations fail because the result contract and suggestion matching are missing. 3. Implement the result contract and matching in the contacts action, storing it in the existing resumable bulk job. Preserve same-UID update merge semantics and never merge suggested contacts. 4. Run the contacts-actions tests on dev-02. Expected: new tests fail before implementation, then pass; prior contacts-actions tests remain green. ### Task 2: Authenticated streaming vCard upload route Interfaces: `POST /api/v1/contacts/import` accepts `text/vcard` and `text/x-vcard`; it authenticates before reading and invokes `contacts.import` with a BLAKE3 key over exact request bytes. Steps: 1. Add failing server tests for authentication, media-type and non-vCard rejection, declared and streamed size limits, the 20,001st card, physical source lines, and exact-file replay. 2. Run the server tests on dev-02 and confirm the new route is absent. 3. Implement frame-by-frame parsing that enforces byte and card limits before collecting the full request, and forwards card lines and parse failures to the durable import action. 4. Run the server tests on dev-02. Expected: route tests fail before implementation, then pass; request bodies over either limit never dispatch an import action. ### Task 3: Full gates and branch review Interfaces: the route, action result, and converter must agree on 3.0/4.0 input, per-card failures, and line numbers. No UI changes. Steps: 1. Run formatting, clippy with warnings denied, and the contacts, contacts-actions, and server test suites on dev-02 through `~/bin/slot`. 2. Review the full branch against this plan, fix any important defect with a failing test first, and update the PR with exact gate results. Expected: every listed gate passes; the branch remains unmerged and the PR continues to target `dev`. ## Round 1 implementation status Head: `ae2cbf27fa31e43a3ce6dfd2b90bf439427c94cf`. All steps committed and pushed; no merge. Ready for the next independent review (round 1 fixes, maximum 3 review rounds). | Finding / gap | Status | Result | |---|---|---| | P1: quadratic duplicate suggestions | Fixed | Exact normalized email, E.164 phone and full-name hash maps; at most 9 representative IDs/key, 8 suggestions/card and 10,000/import. No exhaustive candidate/pair collection. `duplicate_suggestions_limited` reports omitted possibilities. | | P1: unbounded name signatures | Fixed | Removed fuzzy rolling/deletion signatures entirely. Matching keys above 1 KiB are omitted while original fields remain intact. Exact-name index storage/work is linear in indexed facts. Fuzzy matching is a follow-up. | | P1: unbounded parser line/property allocations | Fixed | Shared constant-space `ImportLimits`/`ImportBudget`, enforced before streaming buffers grow and before direct-action identity/parsing: 2 MiB unfolded line, 4,096 physical lines including blanks/folds (also bounds properties), 8 MiB card, 4 MiB total encoded PHOTO content lines. Oversized cards are discarded and durably reported as `skipped` with `too large`; neighbors continue. | | Hostile input regressions | Passed | Ordinary/folded huge FN, blank/property floods, each structural/byte/PHOTO cap, embedded CR vs CRLF, split frames, bounded retained buffer; 20,000 identical-name/email matching facts assert bounded index/output and time. | | Missing END recovery | Passed | Next BEGIN fails only the unfinished card and preserves the next card's physical line. | | Mixed 2.1 / 3.0 / 4.0 upload | Passed | 2.1 fails explicitly; 3.0 and 4.0 survive in one request. | | Update-only / mixed create+update crash and replay | Passed | Seven new kill/recovery cases at prepared/planned/committed and mixed mid-job; note/card consistency, separate creates, original update ID and durable summary replay. | Final gates on `cua@calternal-dev-02-std`, in the Nix dev shell, under `~/bin/slot`: | Exact command | Status | |---|---| | `cargo fmt --all -- --check` | Passed | | `cargo clippy -j4 -p calternal-contacts -p calternal-contacts-actions -p calternal-server --all-targets --locked -- -D warnings` | Passed | | `cargo test -j4 -p calternal-contacts --locked` | Passed, 132 tests | | `cargo test -j4 -p calternal-contacts-actions --locked` | Passed, 145 tests | | `cargo test -j4 -p calternal-server --locked` | Passed, 35 tests | Resource checks ran the compiled regression test executables under the same Nix/slot wrapper, using Python `os.wait4` peak RSS and wall-clock measurements with hard assertions of <128 MiB / <10 s for the 20,000-fact matcher and <256 MiB / <10 s for the hostile streaming-card test. These measure those isolated components, not peak RSS for a full disk import. Regression tests also assert the scanner's constant state, bounded per-card buffer, fixed bucket sizes and at most 10,000 serialized suggestions (<2 MiB). Decisions/limits: suggestions are bounded samples and fuzzy matching is deferred; very large cards/photos or unusually folded/property-heavy cards are skipped by the explicit limits above. Accepted original vCard bytes, unknown fields and photos remain intact. No independent re-review has been performed by this implementation agent. Final-head resource measurements: matcher peak RSS **28,668 KiB**, **0.184 s**; hostile-card stream peak RSS **28,896 KiB**, **0.109 s**. Both hard memory/time assertions passed. Final gate log: `~/pr800-r1-locked.log` on dev-02; it records the head SHA and ends with `RESOURCE_GATES_PASSED` and `ALL_GATES_PASSED`.
docs: plan contacts vCard import
Some checks failed
CI / server (pull_request) Has been cancelled
CI / rust (pull_request) Has been cancelled
CI / web (pull_request) Has been cancelled
8d947953ea
Author
Owner

Independent review, round 1

Reviewed 60d990ddf452a933f4f009fff409b4a29233d8fc, the PR plan/failure table, ADRs 0063/0064, and the contacts decisions memory.

Verdict: fix first.

P1: bound duplicate work and output before materializing matches

crates/contacts-actions/src/import.rs:883–951 collects every candidate, returns every matching pair, and appends every suggestion without a per-card or per-job budget. An empty address book plus 20,000 cards with distinct UIDs and the same email produces 20,000 * 19,999 / 2 = 199,990,000 suggestion rows. This requires only a few MiB of upload and does not require hash collisions. Each row owns a contact ID and reason strings; the result is then sorted, converted to JSON, and persisted in the job summary. It can exhaust process memory before the durable job starts, and matching/sorting also consumes quadratic CPU. An existing book can amplify this further. Bound candidate visits and retained suggestions, or represent large groups compactly with an explicit truncation/continuation contract. Apply the budget inside matching, before collecting an exhaustive Vec. Regression: the maximum-card same-email file must finish within a documented memory/work budget and retain separate contacts.

P1: bound name indexing independently of upload bytes

crates/contacts-actions/src/import.rs:784–814, 833–840, 895–899 builds chars, prefixes, and a hash set sized to the full normalized FN, then creates a separate map entry and owned contact-ID set for each distinct deletion signature. FN has no maximum matching length. A single accepted card with a tens-of-MiB pseudorandom alphabetic FN therefore creates millions of map entries and small allocations, using many GiB despite remaining below 100 MiB and one card. The 4,096-character linear-storage test checks only signature values, not the much larger MatchIndex or a practical maximum. Skip fuzzy matching above a documented length/work budget (preserving the original field), or use another bounded representation; cover both incoming names and existing names when constructing the index. Regression: huge ordinary and folded FN values must not expand into an unbounded matching index.

P1: enforce structural parsing budgets before allocating per-line objects

crates/contacts-actions/src/import.rs:706–710 calls Card::parse to detect 2.1 and then parses again in Contact::from_vcard. The new streaming route caps only raw bytes and BEGIN records, so a single otherwise valid card can contain millions of tiny properties or empty physical lines. crates/contacts/src/card.rs:38–55 allocates a Vec and a Line for each non-folded physical line, plus property objects for parsed properties. For example, a card containing about 90 MiB of blank LF lines passes the upload limits but attempts about 94 million Line records during the preliminary version check alone. This can kill the server before any per-card failure or job is recorded. Add a physical/logical-line or property-count/allocation budget while streaming, or use a bounded parser representation; do not fully parse merely to inspect VERSION before enforcing that budget. Preserve accepted unknown fields and large-photo bytes. Regression: a one-card many-lines/many-properties upload must fail safely or parse within a documented bound, without exhausting the process.

P0: none found. P2/P3: no additional findings.

Auth is extracted before body polling; the observed-byte check precedes parser buffering for each frame, and BEGIN counting stops at 20,001. User-scoped engine runtimes/job IDs and the stored bulk plan support isolation and replay. The suggestion path itself only reads facts and builds results; it does not merge contacts. Original-card persistence retains unmodeled fields. Those observations do not remove the resource blockers above.

Validation: source review and exact pair-count analysis, not runtime/RSS measurements. No builds or tests were run on the read-only control host; the passing gates listed in the PR are author-reported. Existing kill/recovery tests cover create-only imports; add update/mixed create+update crash/replay coverage for the new import path. Also close the author-recorded missing-END recovery and mixed 2.1/3.0/4.0 route cases. No code changed or pushed.

## Independent review, round 1 Reviewed `60d990ddf452a933f4f009fff409b4a29233d8fc`, the PR plan/failure table, ADRs 0063/0064, and the contacts decisions memory. **Verdict: fix first.** ### P1: bound duplicate work and output before materializing matches `crates/contacts-actions/src/import.rs:883–951` collects every candidate, returns every matching pair, and appends every suggestion without a per-card or per-job budget. An empty address book plus 20,000 cards with distinct UIDs and the same email produces `20,000 * 19,999 / 2 = 199,990,000` suggestion rows. This requires only a few MiB of upload and does not require hash collisions. Each row owns a contact ID and reason strings; the result is then sorted, converted to JSON, and persisted in the job summary. It can exhaust process memory before the durable job starts, and matching/sorting also consumes quadratic CPU. An existing book can amplify this further. Bound candidate visits and retained suggestions, or represent large groups compactly with an explicit truncation/continuation contract. Apply the budget inside matching, before collecting an exhaustive Vec. Regression: the maximum-card same-email file must finish within a documented memory/work budget and retain separate contacts. ### P1: bound name indexing independently of upload bytes `crates/contacts-actions/src/import.rs:784–814, 833–840, 895–899` builds chars, prefixes, and a hash set sized to the full normalized FN, then creates a separate map entry and owned contact-ID set for each distinct deletion signature. FN has no maximum matching length. A single accepted card with a tens-of-MiB pseudorandom alphabetic FN therefore creates millions of map entries and small allocations, using many GiB despite remaining below 100 MiB and one card. The 4,096-character linear-storage test checks only signature values, not the much larger MatchIndex or a practical maximum. Skip fuzzy matching above a documented length/work budget (preserving the original field), or use another bounded representation; cover both incoming names and existing names when constructing the index. Regression: huge ordinary and folded FN values must not expand into an unbounded matching index. ### P1: enforce structural parsing budgets before allocating per-line objects `crates/contacts-actions/src/import.rs:706–710` calls `Card::parse` to detect 2.1 and then parses again in `Contact::from_vcard`. The new streaming route caps only raw bytes and BEGIN records, so a single otherwise valid card can contain millions of tiny properties or empty physical lines. `crates/contacts/src/card.rs:38–55` allocates a Vec and a Line for each non-folded physical line, plus property objects for parsed properties. For example, a card containing about 90 MiB of blank LF lines passes the upload limits but attempts about 94 million Line records during the preliminary version check alone. This can kill the server before any per-card failure or job is recorded. Add a physical/logical-line or property-count/allocation budget while streaming, or use a bounded parser representation; do not fully parse merely to inspect VERSION before enforcing that budget. Preserve accepted unknown fields and large-photo bytes. Regression: a one-card many-lines/many-properties upload must fail safely or parse within a documented bound, without exhausting the process. **P0:** none found. **P2/P3:** no additional findings. Auth is extracted before body polling; the observed-byte check precedes parser buffering for each frame, and BEGIN counting stops at 20,001. User-scoped engine runtimes/job IDs and the stored bulk plan support isolation and replay. The suggestion path itself only reads facts and builds results; it does not merge contacts. Original-card persistence retains unmodeled fields. Those observations do not remove the resource blockers above. Validation: source review and exact pair-count analysis, not runtime/RSS measurements. No builds or tests were run on the read-only control host; the passing gates listed in the PR are author-reported. Existing kill/recovery tests cover create-only imports; add update/mixed create+update crash/replay coverage for the new import path. Also close the author-recorded missing-END recovery and mixed 2.1/3.0/4.0 route cases. No code changed or pushed.
Author
Owner

Round 1 implementation plan

Replace fuzzy signatures with exact normalized email/E.164/full-name hash maps. Retain at most 9 representatives per key, visit at most 8 returned candidates per incoming card, and retain at most 10,000 suggestions per job. Matching keys above 1 KiB are ignored without changing stored fields. Fuzzy matching is a follow-up. Work is O(input/indexed key bytes + bounded suggestions), including identical-name/email groups; no exhaustive pair materialization.

Use one shared limits struct in the pure contacts crate and an allocation-free incremental budget checker used before buffering/parsing: 2 MiB unfolded line, 4,096 physical lines (also bounds properties), 8 MiB/card, 4 MiB total encoded PHOTO property bytes/card. Keep 100 MiB/upload and 20,000 cards. Oversized cards are discarded while streaming until the next boundary, then reported as skipped with too large and the source line; accepted neighboring cards and original bytes remain intact. Direct action callers receive the same checks before identity/parser allocations.

Failure Effect/detection Recovery Regression
Excess line, line/property count, card or PHOTO bytes Incremental checker stops retaining card; per-card skipped: too large Continue at END/next BEGIN; retry smaller card Each cap, folded lines, blank/property flood, frame splits, bounded retained buffer
Repeated exact facts Fixed representative/output budgets; report suggestion truncation Contacts remain separate 20,000 identical names/emails; index/work/output bounds
Huge existing/incoming name One exact key, omitted above 1 KiB; no signatures Original name retained Long ordinary/folded names
Missing END / mixed versions Per-card failure, neighboring valid versions continue Correct/re-export bad card Missing END; mixed 2.1/3.0/4.0 route tests

Commit/push after each meaningful implementation step. Run fmt, clippy -D warnings and contacts, contacts-actions, server tests on dev-02 via Nix and slot. Never merge.

## Round 1 implementation plan Replace fuzzy signatures with exact normalized email/E.164/full-name hash maps. Retain at most 9 representatives per key, visit at most 8 returned candidates per incoming card, and retain at most 10,000 suggestions per job. Matching keys above 1 KiB are ignored without changing stored fields. Fuzzy matching is a follow-up. Work is O(input/indexed key bytes + bounded suggestions), including identical-name/email groups; no exhaustive pair materialization. Use one shared limits struct in the pure contacts crate and an allocation-free incremental budget checker used before buffering/parsing: 2 MiB unfolded line, 4,096 physical lines (also bounds properties), 8 MiB/card, 4 MiB total encoded PHOTO property bytes/card. Keep 100 MiB/upload and 20,000 cards. Oversized cards are discarded while streaming until the next boundary, then reported as `skipped` with `too large` and the source line; accepted neighboring cards and original bytes remain intact. Direct action callers receive the same checks before identity/parser allocations. | Failure | Effect/detection | Recovery | Regression | |---|---|---|---| | Excess line, line/property count, card or PHOTO bytes | Incremental checker stops retaining card; per-card skipped: too large | Continue at END/next BEGIN; retry smaller card | Each cap, folded lines, blank/property flood, frame splits, bounded retained buffer | | Repeated exact facts | Fixed representative/output budgets; report suggestion truncation | Contacts remain separate | 20,000 identical names/emails; index/work/output bounds | | Huge existing/incoming name | One exact key, omitted above 1 KiB; no signatures | Original name retained | Long ordinary/folded names | | Missing END / mixed versions | Per-card failure, neighboring valid versions continue | Correct/re-export bad card | Missing END; mixed 2.1/3.0/4.0 route tests | Commit/push after each meaningful implementation step. Run fmt, clippy -D warnings and contacts, contacts-actions, server tests on dev-02 via Nix and slot. Never merge.
Author
Owner

Round 1 implementation status

Head: ae2cbf27fa31e43a3ce6dfd2b90bf439427c94cf. All steps committed and pushed; no merge. Ready for the next independent review (round 1 fixes, maximum 3 review rounds).

Finding / gap Status Result
P1: quadratic duplicate suggestions Fixed Exact normalized email, E.164 phone and full-name hash maps; at most 9 representative IDs/key, 8 suggestions/card and 10,000/import. No exhaustive candidate/pair collection. duplicate_suggestions_limited reports omitted possibilities.
P1: unbounded name signatures Fixed Removed fuzzy rolling/deletion signatures entirely. Matching keys above 1 KiB are omitted while original fields remain intact. Exact-name index storage/work is linear in indexed facts. Fuzzy matching is a follow-up.
P1: unbounded parser line/property allocations Fixed Shared constant-space ImportLimits/ImportBudget, enforced before streaming buffers grow and before direct-action identity/parsing: 2 MiB unfolded line, 4,096 physical lines including blanks/folds (also bounds properties), 8 MiB card, 4 MiB total encoded PHOTO content lines. Oversized cards are discarded and durably reported as skipped with too large; neighbors continue.
Hostile input regressions Passed Ordinary/folded huge FN, blank/property floods, each structural/byte/PHOTO cap, embedded CR vs CRLF, split frames, bounded retained buffer; 20,000 identical-name/email matching facts assert bounded index/output and time.
Missing END recovery Passed Next BEGIN fails only the unfinished card and preserves the next card's physical line.
Mixed 2.1 / 3.0 / 4.0 upload Passed 2.1 fails explicitly; 3.0 and 4.0 survive in one request.
Update-only / mixed create+update crash and replay Passed Seven new kill/recovery cases at prepared/planned/committed and mixed mid-job; note/card consistency, separate creates, original update ID and durable summary replay.

Final gates on cua@calternal-dev-02-std, in the Nix dev shell, under ~/bin/slot:

Exact command Status
cargo fmt --all -- --check Passed
cargo clippy -j4 -p calternal-contacts -p calternal-contacts-actions -p calternal-server --all-targets --locked -- -D warnings Passed
cargo test -j4 -p calternal-contacts --locked Passed, 132 tests
cargo test -j4 -p calternal-contacts-actions --locked Passed, 145 tests
cargo test -j4 -p calternal-server --locked Passed, 35 tests

Resource checks ran the compiled regression test executables under the same Nix/slot wrapper, using Python os.wait4 peak RSS and wall-clock measurements with hard assertions of <128 MiB / <10 s for the 20,000-fact matcher and <256 MiB / <10 s for the hostile streaming-card test. These measure those isolated components, not peak RSS for a full disk import. Regression tests also assert the scanner's constant state, bounded per-card buffer, fixed bucket sizes and at most 10,000 serialized suggestions (<2 MiB).

Decisions/limits: suggestions are bounded samples and fuzzy matching is deferred; very large cards/photos or unusually folded/property-heavy cards are skipped by the explicit limits above. Accepted original vCard bytes, unknown fields and photos remain intact. No independent re-review has been performed by this implementation agent.

Final-head resource measurements: matcher peak RSS 28,668 KiB, 0.184 s; hostile-card stream peak RSS 28,896 KiB, 0.109 s. Both hard memory/time assertions passed. Final gate log: ~/pr800-r1-locked.log on dev-02; it records the head SHA and ends with RESOURCE_GATES_PASSED and ALL_GATES_PASSED.

## Round 1 implementation status Head: `ae2cbf27fa31e43a3ce6dfd2b90bf439427c94cf`. All steps committed and pushed; no merge. Ready for the next independent review (round 1 fixes, maximum 3 review rounds). | Finding / gap | Status | Result | |---|---|---| | P1: quadratic duplicate suggestions | Fixed | Exact normalized email, E.164 phone and full-name hash maps; at most 9 representative IDs/key, 8 suggestions/card and 10,000/import. No exhaustive candidate/pair collection. `duplicate_suggestions_limited` reports omitted possibilities. | | P1: unbounded name signatures | Fixed | Removed fuzzy rolling/deletion signatures entirely. Matching keys above 1 KiB are omitted while original fields remain intact. Exact-name index storage/work is linear in indexed facts. Fuzzy matching is a follow-up. | | P1: unbounded parser line/property allocations | Fixed | Shared constant-space `ImportLimits`/`ImportBudget`, enforced before streaming buffers grow and before direct-action identity/parsing: 2 MiB unfolded line, 4,096 physical lines including blanks/folds (also bounds properties), 8 MiB card, 4 MiB total encoded PHOTO content lines. Oversized cards are discarded and durably reported as `skipped` with `too large`; neighbors continue. | | Hostile input regressions | Passed | Ordinary/folded huge FN, blank/property floods, each structural/byte/PHOTO cap, embedded CR vs CRLF, split frames, bounded retained buffer; 20,000 identical-name/email matching facts assert bounded index/output and time. | | Missing END recovery | Passed | Next BEGIN fails only the unfinished card and preserves the next card's physical line. | | Mixed 2.1 / 3.0 / 4.0 upload | Passed | 2.1 fails explicitly; 3.0 and 4.0 survive in one request. | | Update-only / mixed create+update crash and replay | Passed | Seven new kill/recovery cases at prepared/planned/committed and mixed mid-job; note/card consistency, separate creates, original update ID and durable summary replay. | Final gates on `cua@calternal-dev-02-std`, in the Nix dev shell, under `~/bin/slot`: | Exact command | Status | |---|---| | `cargo fmt --all -- --check` | Passed | | `cargo clippy -j4 -p calternal-contacts -p calternal-contacts-actions -p calternal-server --all-targets --locked -- -D warnings` | Passed | | `cargo test -j4 -p calternal-contacts --locked` | Passed, 132 tests | | `cargo test -j4 -p calternal-contacts-actions --locked` | Passed, 145 tests | | `cargo test -j4 -p calternal-server --locked` | Passed, 35 tests | Resource checks ran the compiled regression test executables under the same Nix/slot wrapper, using Python `os.wait4` peak RSS and wall-clock measurements with hard assertions of <128 MiB / <10 s for the 20,000-fact matcher and <256 MiB / <10 s for the hostile streaming-card test. These measure those isolated components, not peak RSS for a full disk import. Regression tests also assert the scanner's constant state, bounded per-card buffer, fixed bucket sizes and at most 10,000 serialized suggestions (<2 MiB). Decisions/limits: suggestions are bounded samples and fuzzy matching is deferred; very large cards/photos or unusually folded/property-heavy cards are skipped by the explicit limits above. Accepted original vCard bytes, unknown fields and photos remain intact. No independent re-review has been performed by this implementation agent. Final-head resource measurements: matcher peak RSS **28,668 KiB**, **0.184 s**; hostile-card stream peak RSS **28,896 KiB**, **0.109 s**. Both hard memory/time assertions passed. Final gate log: `~/pr800-r1-locked.log` on dev-02; it records the head SHA and ends with `RESOURCE_GATES_PASSED` and `ALL_GATES_PASSED`.
Author
Owner

Independent review, round 2

Reviewed ae2cbf27fa31e43a3ce6dfd2b90bf439427c94cf, round 1 (#issuecomment-71487), fixes (#issuecomment-71529), and the relevant plan/ADRs. Verdict: fix first.

Round 1 finding Status Does the test prove it?
P1 quadratic duplicate suggestions resolved Exact-key buckets retain 9 IDs, matching retains 8 candidates/card, and output stops at 10,000 suggestions before pair materialization. The 20,000-fact regression exercises identical email/name groups, checks bucket/output sizes and serialized suggestions below 2 MiB. The recorded 28,668 KiB peak RSS is at 20,000 facts, but is an isolated matcher measurement, not a 20,000-contact disk import.
P1 unrestricted name signatures resolved Deletion/fuzzy signatures are gone. Keys above 1 KiB are omitted from lookup maps. The 2 MiB name regression covers index insertion and lookup; ordinary/folded oversized FN tests cover streaming rejection. Full normalized strings are still allocated/retained, but linearly, without the former per-character map-entry explosion. No hostile existing-book/full-import RSS measurement is supplied by these tests.
P1 unrestricted parser line/property allocations not resolved Physical-line/property floods are stopped before buffering/parsing, but parameter/value object counts within one accepted line remain unrestricted. The hostile-stream test allocates attacks of roughly 0.1–9 MiB and measures the scanner, without running the allocating converter on a 100 MiB hostile upload. Its 28,896 KiB RSS result does not prove this allocation boundary. See P1 below.

Full supported-scale RSS gate: not demonstrated. The ~28 MiB results measure the 20,000-fact matcher and a smaller scanner-only input separately. Neither measures an end-to-end import combining 20,000 cards and 100 MiB. No round-1 item was found regressed.

P1: parameter-value floods bypass the new structural budget and still consume GiB

crates/contacts/src/import_limits.rs:65,114 counts physical lines and unfolded bytes, but never parameter/value objects. crates/contacts/src/card.rs:116–134 allocates a String entry for every comma-separated parameter value and a Parameter for every semicolon-separated parameter. crates/contacts/src/field.rs:67 then clones parameters into the converted field, while the original parsed card is retained (note.rs:72–91). These allocations occur after the budget accepts the card. A single line below 2 MiB can therefore allocate over two million value entries despite having only five ordinary physical lines plus a UID.

Independent reproduction on dev-02, using the final-head compiled contacts crate, Nix and ~/bin/slot:

let mut contacts = Vec::new();
for at in 0..49 {
    let text = format!(
        "BEGIN:VCARD\nVERSION:3.0\nUID:probe-{at}\nFN:Sample\nEMAIL;TYPE={}:a@example.test\nEND:VCARD\n",
        ",".repeat(2 * 1024 * 1024 - 64)
    );
    assert!(ImportBudget::new(ImportLimits::default()).push(text.as_bytes()));
    contacts.push(Contact::from_vcard(&format!("id-{at}"), text.as_bytes()).unwrap());
}
std::hint::black_box(&contacts);

All 49 distinct-UID contacts convert successfully; total wire size 102,761,418 bytes, below 100 MiB; 102,757,361 parameter-value objects in the fields alone, plus their original-card counterparts. Python resource.getrusage(RUSAGE_CHILDREN).ru_maxrss around this single executable measured 4,932,284 KiB peak RSS, 10.563 s. A parser-only probe at the same scale measured 2,515,608 KiB. These are component measurements, not a claim of measured full-route peak RSS. The import conversion path retains converted contacts across the upload and clones these same structures, so the new limits still admit a multi-GiB allocation before durable preparation. Unique UIDs prevent identity deduplication from eliminating the attack.

Bound parser substructure allocations before constructing vectors/strings, including parameter counts, comma-separated parameter values, and typed list/component entries. Enforce a practical aggregate object/work budget as well as byte/line limits, preserving accepted original bytes. Add an approximately 100 MiB, distinct-UID regression that runs the actual conversion path under a documented peak-RSS budget; scanner-only measurements cannot catch this.

Replay, recovery, summary, and route-gap checks

  • Streaming overflow frees the active buffer immediately; direct-action limits run before identity extraction/parsing. Oversized cards receive constant too large reasons and count toward the 20,000-card cap. Accepted neighboring cards retain physical source lines.
  • The oversized action regression verifies durable skipped outcomes and exact-key replay with one valid neighbor. Updates/mixed creates now have seven kill/recovery cases, which passed independently. Those kill cases do not include an oversized skipped card, and the oversized replay case does not restart the process; combined skipped-card/resume coverage remains a test gap. Source review found no separate replay/resume defect: skipped outcomes enter the same persisted summary before placement.
  • Route-produced summary rows are capped at 20,000 and use fixed failure messages; suggestions are capped at 10,000 with three fixed reasons. The suggestion serialization assertion covers suggestions only, not the whole summary. Direct action callers can supply arbitrary-length failures[].reason; that field is only checked for nonempty text and is excluded from MAX_BYTES, so there is no universal action-level summary-byte bound. No additional P0/P1 finding from that path in this review.
  • Missing-END recovery and mixed 2.1/3.0/4.0 route tests both exist and passed. They verify adapter dispatch through the recording action, rather than a full on-disk import.

P0: none. New P1: parameter/value allocation bypass above. Additional P2/P3 findings: none.

Independent validation on cua@calternal-dev-02-std, final head, Nix dev shell, through ~/bin/slot:

  • cargo test -j4 -p calternal-contacts-actions --locked import -- --nocapture: 44 passed, including the new seven update/mixed kill/recovery cases and oversized-summary replay.
  • cargo test -j4 -p calternal-server --locked contacts_import: 1 unit + 11 route tests passed.
  • Temporary standalone probes linked against the final-head contacts rlib; compiled with rustc --edition=2024 ... -L dependency=target/debug/deps --extern calternal_contacts=..., measured by Python resource.getrusage around each executable. Probe sources remain under /tmp/pr800-review2.* on dev-02 for reproduction.

No repository code changed or pushed; no builds/tests ran on the control host. This is round 2 of at most 3.
Recheck at the same head: confirmed the existing round-2 finding against the budget, parser, field conversion, matcher and streaming source, and confirmed the recorded author resource-gate log and retained probe artifacts on dev-02. This recheck did not rerun the earlier runtime probes or test suites. Updated this existing round-2 comment to avoid duplicating the review.

## Independent review, round 2 Reviewed `ae2cbf27fa31e43a3ce6dfd2b90bf439427c94cf`, round 1 (#issuecomment-71487), fixes (#issuecomment-71529), and the relevant plan/ADRs. **Verdict: fix first.** | Round 1 finding | Status | Does the test prove it? | |---|---|---| | P1 quadratic duplicate suggestions | **resolved** | Exact-key buckets retain 9 IDs, matching retains 8 candidates/card, and output stops at 10,000 suggestions before pair materialization. The 20,000-fact regression exercises identical email/name groups, checks bucket/output sizes and serialized suggestions below 2 MiB. The recorded 28,668 KiB peak RSS is at 20,000 facts, but is an isolated matcher measurement, not a 20,000-contact disk import. | | P1 unrestricted name signatures | **resolved** | Deletion/fuzzy signatures are gone. Keys above 1 KiB are omitted from lookup maps. The 2 MiB name regression covers index insertion and lookup; ordinary/folded oversized FN tests cover streaming rejection. Full normalized strings are still allocated/retained, but linearly, without the former per-character map-entry explosion. No hostile existing-book/full-import RSS measurement is supplied by these tests. | | P1 unrestricted parser line/property allocations | **not resolved** | Physical-line/property floods are stopped before buffering/parsing, but parameter/value object counts within one accepted line remain unrestricted. The hostile-stream test allocates attacks of roughly 0.1–9 MiB and measures the scanner, without running the allocating converter on a 100 MiB hostile upload. Its 28,896 KiB RSS result does not prove this allocation boundary. See P1 below. | **Full supported-scale RSS gate: not demonstrated.** The ~28 MiB results measure the 20,000-fact matcher and a smaller scanner-only input separately. Neither measures an end-to-end import combining 20,000 cards and 100 MiB. No round-1 item was found regressed. ### P1: parameter-value floods bypass the new structural budget and still consume GiB `crates/contacts/src/import_limits.rs:65,114` counts physical lines and unfolded bytes, but never parameter/value objects. `crates/contacts/src/card.rs:116–134` allocates a String entry for every comma-separated parameter value and a Parameter for every semicolon-separated parameter. `crates/contacts/src/field.rs:67` then clones parameters into the converted field, while the original parsed card is retained (`note.rs:72–91`). These allocations occur after the budget accepts the card. A single line below 2 MiB can therefore allocate over two million value entries despite having only five ordinary physical lines plus a UID. Independent reproduction on dev-02, using the final-head compiled contacts crate, Nix and `~/bin/slot`: ```rust let mut contacts = Vec::new(); for at in 0..49 { let text = format!( "BEGIN:VCARD\nVERSION:3.0\nUID:probe-{at}\nFN:Sample\nEMAIL;TYPE={}:a@example.test\nEND:VCARD\n", ",".repeat(2 * 1024 * 1024 - 64) ); assert!(ImportBudget::new(ImportLimits::default()).push(text.as_bytes())); contacts.push(Contact::from_vcard(&format!("id-{at}"), text.as_bytes()).unwrap()); } std::hint::black_box(&contacts); ``` All **49 distinct-UID contacts** convert successfully; total wire size **102,761,418 bytes**, below 100 MiB; **102,757,361 parameter-value objects in the fields alone**, plus their original-card counterparts. Python `resource.getrusage(RUSAGE_CHILDREN).ru_maxrss` around this single executable measured **4,932,284 KiB peak RSS**, **10.563 s**. A parser-only probe at the same scale measured **2,515,608 KiB**. These are component measurements, not a claim of measured full-route peak RSS. The import conversion path retains converted contacts across the upload and clones these same structures, so the new limits still admit a multi-GiB allocation before durable preparation. Unique UIDs prevent identity deduplication from eliminating the attack. Bound parser substructure allocations before constructing vectors/strings, including parameter counts, comma-separated parameter values, and typed list/component entries. Enforce a practical aggregate object/work budget as well as byte/line limits, preserving accepted original bytes. Add an approximately 100 MiB, distinct-UID regression that runs the actual conversion path under a documented peak-RSS budget; scanner-only measurements cannot catch this. ### Replay, recovery, summary, and route-gap checks - Streaming overflow frees the active buffer immediately; direct-action limits run before identity extraction/parsing. Oversized cards receive constant `too large` reasons and count toward the 20,000-card cap. Accepted neighboring cards retain physical source lines. - The oversized action regression verifies durable skipped outcomes and exact-key replay with one valid neighbor. Updates/mixed creates now have seven kill/recovery cases, which passed independently. Those kill cases do **not** include an oversized skipped card, and the oversized replay case does not restart the process; combined skipped-card/resume coverage remains a test gap. Source review found no separate replay/resume defect: skipped outcomes enter the same persisted summary before placement. - Route-produced summary rows are capped at 20,000 and use fixed failure messages; suggestions are capped at 10,000 with three fixed reasons. The suggestion serialization assertion covers suggestions only, not the whole summary. Direct action callers can supply arbitrary-length `failures[].reason`; that field is only checked for nonempty text and is excluded from `MAX_BYTES`, so there is no universal action-level summary-byte bound. No additional P0/P1 finding from that path in this review. - Missing-END recovery and mixed 2.1/3.0/4.0 route tests both exist and passed. They verify adapter dispatch through the recording action, rather than a full on-disk import. **P0:** none. **New P1:** parameter/value allocation bypass above. **Additional P2/P3 findings:** none. Independent validation on `cua@calternal-dev-02-std`, final head, Nix dev shell, through `~/bin/slot`: - `cargo test -j4 -p calternal-contacts-actions --locked import -- --nocapture`: **44 passed**, including the new seven update/mixed kill/recovery cases and oversized-summary replay. - `cargo test -j4 -p calternal-server --locked contacts_import`: **1 unit + 11 route tests passed**. - Temporary standalone probes linked against the final-head contacts rlib; compiled with `rustc --edition=2024 ... -L dependency=target/debug/deps --extern calternal_contacts=...`, measured by Python `resource.getrusage` around each executable. Probe sources remain under `/tmp/pr800-review2.*` on dev-02 for reproduction. No repository code changed or pushed; no builds/tests ran on the control host. This is round 2 of at most 3. Recheck at the same head: confirmed the existing round-2 finding against the budget, parser, field conversion, matcher and streaming source, and confirmed the recorded author resource-gate log and retained probe artifacts on dev-02. This recheck did not rerun the earlier runtime probes or test suites. Updated this existing round-2 comment to avoid duplicating the review.
Author
Owner

Round 2 implementation plan

Reserve one conservative per-card allocation envelope before the allocating parser or converter runs. Charge raw byte copies (names, parameter names/values, unfolded/unescaped text, rendering and decoded photos) and object/vector storage, including empty parameter values and typed list/component items. The reservation is bounded by 16 times raw card bytes plus a small fixed allowance, with an absolute ceiling. Counting every delimiter, even quoted/escaped ones, deliberately overestimates storage. Exceeded reservations produce durable skipped: too large outcomes. Keep original bytes of accepted cards unchanged.

Remove parallel batch conversion and consume each converted contact immediately. Retain only the bulk plan data and matching/naming facts needed for the existing atomic import; reparse related contacts individually when paths are known. Complexity remains O(input bytes + bounded matching output); allocation checking is constant-space O(card bytes).

Failure Effect/detection Recovery Test
Parameter/name/value/list/component allocation reservation exceeds card envelope Checked before parser allocation; skipped: too large Continue with neighboring cards; durable replay 49 distinct UID cards using round-2 probe; delimiter/name/fold/photo cases
Conversion accumulates typed contacts Sequential per-card consumption Existing bulk job semantics Real 20,000-card, approximately 100 MiB mixed-version disk import
Resource regression Isolated child-process peak RSS assertions Fail gate before final review Reviewer probe and full disk import measured on dev-02

Steps: (1) budget plus regressions, commit/push; (2) sequential conversion and full-scale memory gate, commit/push; (3) VM fmt, clippy -D warnings, contacts/contacts-actions/server suites and measured status table, commit/push documentation. Never merge.

## Round 2 implementation plan Reserve one conservative per-card allocation envelope before the allocating parser or converter runs. Charge raw byte copies (names, parameter names/values, unfolded/unescaped text, rendering and decoded photos) and object/vector storage, including empty parameter values and typed list/component items. The reservation is bounded by 16 times raw card bytes plus a small fixed allowance, with an absolute ceiling. Counting every delimiter, even quoted/escaped ones, deliberately overestimates storage. Exceeded reservations produce durable `skipped: too large` outcomes. Keep original bytes of accepted cards unchanged. Remove parallel batch conversion and consume each converted contact immediately. Retain only the bulk plan data and matching/naming facts needed for the existing atomic import; reparse related contacts individually when paths are known. Complexity remains O(input bytes + bounded matching output); allocation checking is constant-space O(card bytes). | Failure | Effect/detection | Recovery | Test | |---|---|---|---| | Parameter/name/value/list/component allocation reservation exceeds card envelope | Checked before parser allocation; skipped: too large | Continue with neighboring cards; durable replay | 49 distinct UID cards using round-2 probe; delimiter/name/fold/photo cases | | Conversion accumulates typed contacts | Sequential per-card consumption | Existing bulk job semantics | Real 20,000-card, approximately 100 MiB mixed-version disk import | | Resource regression | Isolated child-process peak RSS assertions | Fail gate before final review | Reviewer probe and full disk import measured on dev-02 | Steps: (1) budget plus regressions, commit/push; (2) sequential conversion and full-scale memory gate, commit/push; (3) VM fmt, clippy -D warnings, contacts/contacts-actions/server suites and measured status table, commit/push documentation. Never merge.
Author
Owner

round 2 implementation complete, ready for FINAL review. head 7b932eb9627b364ddc55bb370eb7f597e1762f2d. no merge performed.

item status evidence
parameter/value allocation limit fixed allocation-free per-card reservation before parser/converter allocation, including parameter names and values, empty entries, typed components, string/vector capacity, unfolding/unescaping, rendering and decoded photos; overflow produces durable skipped: too large
conversion and storage fixed one typed card at a time; original bytes spooled to an anonymous temporary file; quota/history read one card at a time; companion copying capped at 256 rows and 8 MiB plus one card
reviewer conversion probe passed 49 distinct UIDs, 102,761,418 wire bytes; peak 12,680 KiB, 0.697 s, asserted ceiling 131,072 KiB
reviewer probe through disk action passed same approximately 100 MiB fixture; peak 144,736 KiB, 5.030 s, asserted ceiling 196,608 KiB
full disk import passed 20,000 cards, 104,840,000 bytes, mixed 2.1/3.0/4.0; peak 225,532 KiB, 28.868 s, asserted ceiling 262,144 KiB
full HTTP import passed real router/executor/plugins, inline photos, visible notes and unknown wire data; peak 233,540 KiB (228.1 MiB), 18.118 s, asserted ceiling 262,144 KiB
fmt, clippy, contacts/actions/server suites passed dev-02, Nix, slot, commands below
notes history/bulk and engine suites passed targeted regression suites below
final independent review pending branch remains open and unmerged

capacity decision: for raw bytes B, LF count L and comma/semicolon count D, reserve 16B + 1024L + 256D + 1024, required to fit min(32B + 64 KiB, 64 MiB). separators inside quoted/escaped text also count. this conservative reservation includes object/capacity overhead before allocation; unusually dense otherwise valid cards can be skipped. the import-specific checked converter uses a single parse; general editing conversion retains its existing contract. accepted original wire bytes remain intact.

full-scale fixtures each contain 20,000 × 5,242-byte cards: 18,000 imported, 2,000 unsupported 2.1. both wait for companion copies, history copy marks and background index/journal publication. scripts/contacts-import-memory.py verifies named ignored tests exist, runs each in a fresh process, and asserts absolute Linux os.wait4 peak RSS, including fixture generation and completed publication. compilation is outside measurement.

exact gates, each through ~/bin/slot inside the dev-02 Nix shell:

cargo fmt --all -- --check
cargo clippy -j4 -p calternal-contacts -p calternal-contacts-actions -p calternal-server --all-targets --locked -- -D warnings
cargo test -j4 -p calternal-contacts -p calternal-contacts-actions -p calternal-server --locked
cargo test -j4 -p calternal-notes --locked history::
cargo test -j4 -p calternal-notes --locked bulk::
cargo test -j4 -p calternal-engine --locked

functional gates passed at adfd25df3249194605f91df6ab6647fceab41a44, log ~/pr800-r2-final-gates.log ends ALL_GATES_PASSED. the following commit ca779da171dadb6ef1935436f01f05b418a8edbf strengthened ignored resource tests to drain publication and updated documentation. fmt and the same clippy gate passed again there, followed by ~/bin/slot python3 scripts/contacts-import-memory.py. log ~/pr800-r2-complete.log ends IMPORT_MEMORY_GATES_PASSED and FINAL_RESOURCE_GATES_PASSED. final head adds only the recorded measurements.

allocation contract, methodology and results.

limits: measurements cover one import into an empty Home on dev-02, not a universal process-memory cap with existing book state, concurrent requests or live editor documents. anonymous spooling adds temporary disk I/O; preparation errors leave no job or roll back the transaction, and committed recovery remains in history. no builds/tests ran on the control host.

round 2 implementation complete, ready for FINAL review. head `7b932eb9627b364ddc55bb370eb7f597e1762f2d`. no merge performed. | item | status | evidence | |---|---|---| | parameter/value allocation limit | fixed | allocation-free per-card reservation before parser/converter allocation, including parameter names and values, empty entries, typed components, string/vector capacity, unfolding/unescaping, rendering and decoded photos; overflow produces durable `skipped: too large` | | conversion and storage | fixed | one typed card at a time; original bytes spooled to an anonymous temporary file; quota/history read one card at a time; companion copying capped at 256 rows and 8 MiB plus one card | | reviewer conversion probe | passed | 49 distinct UIDs, 102,761,418 wire bytes; peak **12,680 KiB**, 0.697 s, asserted ceiling 131,072 KiB | | reviewer probe through disk action | passed | same approximately 100 MiB fixture; peak **144,736 KiB**, 5.030 s, asserted ceiling 196,608 KiB | | full disk import | passed | 20,000 cards, 104,840,000 bytes, mixed 2.1/3.0/4.0; peak **225,532 KiB**, 28.868 s, asserted ceiling 262,144 KiB | | full HTTP import | passed | real router/executor/plugins, inline photos, visible notes and unknown wire data; peak **233,540 KiB (228.1 MiB)**, 18.118 s, asserted ceiling 262,144 KiB | | fmt, clippy, contacts/actions/server suites | passed | dev-02, Nix, slot, commands below | | notes history/bulk and engine suites | passed | targeted regression suites below | | final independent review | pending | branch remains open and unmerged | capacity decision: for raw bytes B, LF count L and comma/semicolon count D, reserve `16B + 1024L + 256D + 1024`, required to fit `min(32B + 64 KiB, 64 MiB)`. separators inside quoted/escaped text also count. this conservative reservation includes object/capacity overhead before allocation; unusually dense otherwise valid cards can be skipped. the import-specific checked converter uses a single parse; general editing conversion retains its existing contract. accepted original wire bytes remain intact. full-scale fixtures each contain 20,000 × 5,242-byte cards: 18,000 imported, 2,000 unsupported 2.1. both wait for companion copies, history copy marks and background index/journal publication. `scripts/contacts-import-memory.py` verifies named ignored tests exist, runs each in a fresh process, and asserts absolute Linux `os.wait4` peak RSS, including fixture generation and completed publication. compilation is outside measurement. exact gates, each through `~/bin/slot` inside the dev-02 Nix shell: ```sh cargo fmt --all -- --check cargo clippy -j4 -p calternal-contacts -p calternal-contacts-actions -p calternal-server --all-targets --locked -- -D warnings cargo test -j4 -p calternal-contacts -p calternal-contacts-actions -p calternal-server --locked cargo test -j4 -p calternal-notes --locked history:: cargo test -j4 -p calternal-notes --locked bulk:: cargo test -j4 -p calternal-engine --locked ``` functional gates passed at `adfd25df3249194605f91df6ab6647fceab41a44`, log `~/pr800-r2-final-gates.log` ends `ALL_GATES_PASSED`. the following commit `ca779da171dadb6ef1935436f01f05b418a8edbf` strengthened ignored resource tests to drain publication and updated documentation. fmt and the same clippy gate passed again there, followed by `~/bin/slot python3 scripts/contacts-import-memory.py`. log `~/pr800-r2-complete.log` ends `IMPORT_MEMORY_GATES_PASSED` and `FINAL_RESOURCE_GATES_PASSED`. final head adds only the recorded measurements. [allocation contract, methodology and results](https://git.kayg.org/kayg/calternal/src/commit/7b932eb9627b364ddc55bb370eb7f597e1762f2d/docs/plans/contacts-import.md#round-2-allocation-and-memory-contract). limits: measurements cover one import into an empty Home on dev-02, not a universal process-memory cap with existing book state, concurrent requests or live editor documents. anonymous spooling adds temporary disk I/O; preparation errors leave no job or roll back the transaction, and committed recovery remains in history. no builds/tests ran on the control host.
Author
Owner

Independent review, round 3 (final)

Reviewed 7b932eb9627b364ddc55bb370eb7f597e1762f2d, round 1, round 2, and fix status. Verdict: stop and simplify. A new P1 remains in round 3, triggering kayg's three-round rule. No code changed or pushed.

Round-2 item Status Independent evidence
Original comma-separated parameter-value probe Resolved All 49 cards / 102,761,418 wire bytes are rejected before parser allocation. Conversion probe: 12,680 KiB peak RSS; real disk-action probe: 139,548 KiB. Both existing ceilings pass.
Parameter, empty-value, typed component/list object allocations Covered by the new pre-parse check Every comma/semicolon is charged, including quoted/escaped delimiters; physical lines and raw bytes cover parser objects and payload copies. Direct action checks precede identity extraction, and checked conversion repeats the checks.
Every derived allocation path covered Not resolved Shared group labels expand multiplicatively during note rendering, outside the claimed reservation. New P1 below. One-card-at-a-time conversion does not bound one rendered card.
Sequential conversion / original-byte retention Implemented Raw bytes use anonymous-file ranges; history/quota read one card at a time; copy batches stop at 256 rows / 8 MiB plus one card. Bulk commit retains the existing transaction/recovery path.
Reported 228.1 MiB full HTTP peak Recorded result confirmed; not a ceiling Author log contains 233,540 KiB. Independent HTTP rerun: 280,796 KiB (274.2 MiB), 18.236 s. Independent disk fixture: 282,856 KiB (276.2 MiB), exceeding its 262,144 KiB gate.
Replay / recovery / route behavior Targeted tests pass 45 action import tests, including update/mixed crash recovery; 1 server unit + 11 route tests. Source review found no additional replay/recovery defect.

New P1: shared group labels bypass the allocation reservation during rendering

crates/contacts/src/import_limits.rs:40 charges wire bytes and delimiter/line counts. However, crates/contacts/src/note_io/fields.rs:118,222 associates one X-ABLabel with every property in its group. write_line at line 489 prints the entire label for each property, and crates/contacts/src/note_io.rs:144 accumulates the result in an unrestricted String. The import calls to_note() before quota admission and retains that result in Fresh; bulk-plan creation subsequently copies/serializes it. The reservation's claim to cover rendering output is therefore false.

Independent bounded reproduction on dev-02, linked to the branch's compiled contacts crate:

let label = "l".repeat(256 * 1024);
let mut card = format!(
    "BEGIN:VCARD\nVERSION:3.0\nUID:label-probe\nFN:Sample\nitem.X-ABLabel:{label}\n"
);
for _ in 0..1024 {
    card.push_str("item.EMAIL:a@example.test\n");
}
card.push_str("END:VCARD\n");
assert!(ImportBudget::new(ImportLimits::default()).push(card.as_bytes()));
assert!(import_allocation_fits(card.as_bytes()));
let contact = Contact::from_vcard_for_import("probe", card.as_bytes()).unwrap();
let note = contact.to_note().unwrap();

Measured: 288,844 wire bytes → 268,457,034 rendered-note bytes, capacity 268,515,328; 267,672 KiB peak RSS, 7.283 s. Both checks accept it. This is conversion/rendering only, not a claimed full-route RSS measurement. The calculated reservation is 5,677,248 bytes, already exceeded by the note alone.

A 1 MiB label with 4,000 same-group email properties still fits the 2 MiB line, 4,096 physical-line, card-byte and allocation checks, but requires about 3.9 GiB of note text from roughly 1.1 MiB of wire input. Subsequent note/plan copies can exceed a 7 GB-class host. This larger case was calculated, not run. The HTTP upload cap cannot prevent it, and quota admission occurs too late. The large existing-book caveat is not needed to reproduce this issue.

New P2: the documented full-scale RSS gate fails on an independent rerun

scripts/contacts-import-memory.py:64 failed at the disk fixture: 282,856 KiB versus its 262,144 KiB ceiling. Consequently, the script did not reach HTTP. I ran the unchanged HTTP test separately with a diagnostic 512 MiB measurement ceiling; it passed functionally at 280,796 KiB, which also exceeds the original 256 MiB ceiling. That diagnostic run is not a pass of the published resource gate.

The 228.1 MiB number comes from absolute child-process peak RSS (os.wait4) for a specific 20,000 × 5,242-byte fixture into an empty Home. Most wire content is X-PADDING, retained in the spool rather than the visible note. Ten percent of cards are unsupported 2.1; some accepted cards contain a 128-byte NOTE or a small photo. The peak includes retained upload strings, parser/converter scratch, naming/matching facts, bulk-plan/seed/serialized representations, SQLite, summary and completed background publication. There is no allocation profile attributing the exact peak among those components.

Thus this is a fixture measurement, not a proof that all accepted 100 MiB files stay under 256 MiB. More visible NOTE/field content can retain larger plans even without the P1. A single 228–276 MiB import is reasonable on a 4-core/7 GB-class host; multi-GiB rendered output is not. Existing book state and concurrent uploads add further memory. Stabilize the representative resource gate and add derived-output cases; merely raising the gate does not fix P1.

Cheap reductions after establishing the bound: move note into Step::Create instead of cloning it (import.rs:600, compute its length first); omit over-1-KiB matching keys from retained MatchFacts, not only the lookup maps. Neither substitutes for the rendering limit.

Concrete simpler design

Keep sequential conversion and raw spooling, but replace the inferred rendering allowance with explicit derived-byte limits:

  1. Keep the existing raw/line/object checks. Before constructing render views, account for shared-label length × reference count with checked arithmetic, including any cleaned copies.
  2. Give import rendering a bounded writer and an explicit per-note byte ceiling, for example 8 MiB. Stop before allocation growth and return durable skipped: too large; preserve accepted original bytes.
  3. Limit aggregate retained note/plan bytes independently of upload bytes, for example 128 MiB, and reserve room for serialization/copies. Reject or skip before retaining excess data. Document the chosen capacities rather than adding further cross-layer copy optimizations to infer a bound.
  4. Gate the shared-label fixture, a near-limit visible-note fixture, and a supported-version full HTTP import through completed publication. Verify skipped outcomes replay/recover through the existing bulk summary.

This gives direct input, object, rendered-card and aggregate-plan bounds without relying on a payload multiplier to model shared references.

Validation and limits

VM execution used cua@calternal-dev-02-std, Nix and ~/bin/slot. VM checkout was ca779da171dadb6ef1935436f01f05b418a8edbf; git diff ca779da1..7b932eb9 --stat confirms the requested head adds only the measurement documentation, with no code/test difference.

  • ~/bin/slot python3 scripts/contacts-import-memory.py: conversion + disk parameter probes passed; full disk fixture failed the RSS ceiling; HTTP was not reached.
  • ~/bin/slot cargo test -j4 -p calternal-contacts-actions --locked import: 45 passed, 2 ignored.
  • ~/bin/slot cargo test -j4 -p calternal-server --locked contacts_import: 1 unit + 11 route tests passed.
  • Separate fresh-process HTTP measurement reused the script's binaries() / measure() functions with a diagnostic 512 MiB ceiling: test passed, 280,796 KiB RSS.
  • Shared-label probe compiled with rustc --edition=2024 /tmp/pr800-review3-label.rs -o /tmp/pr800-review3-label -L dependency=target/debug/deps --extern calternal_contacts=<branch rlib>, under the same Nix/slot wrapper; Python os.wait4 measured the child. Artifacts: /tmp/pr800-review3-label.{rs,py}, ~/pr800-review3-label.log; gate logs: ~/pr800-review3-{gates,extra,http}.log.

No builds/tests ran on the control host. Author-reported fmt/clippy/full-suite results were inspected, not independently rerun. A supplemental visible-NOTE HTTP probe did not compile because its standalone linking selected incompatible duplicate dependency artifacts; no measurement from that attempt is used here.

New severity counts: P0 0, P1 1, P2 1, P3 0. Verdict: stop and simplify.

## Independent review, round 3 (final) Reviewed `7b932eb9627b364ddc55bb370eb7f597e1762f2d`, [round 1](#issuecomment-71487), [round 2](#issuecomment-71541), and [fix status](#issuecomment-71661). **Verdict: stop and simplify.** A new P1 remains in round 3, triggering kayg's three-round rule. No code changed or pushed. | Round-2 item | Status | Independent evidence | |---|---|---| | Original comma-separated parameter-value probe | Resolved | All 49 cards / 102,761,418 wire bytes are rejected before parser allocation. Conversion probe: 12,680 KiB peak RSS; real disk-action probe: 139,548 KiB. Both existing ceilings pass. | | Parameter, empty-value, typed component/list object allocations | Covered by the new pre-parse check | Every comma/semicolon is charged, including quoted/escaped delimiters; physical lines and raw bytes cover parser objects and payload copies. Direct action checks precede identity extraction, and checked conversion repeats the checks. | | Every derived allocation path covered | **Not resolved** | Shared group labels expand multiplicatively during note rendering, outside the claimed reservation. New P1 below. One-card-at-a-time conversion does not bound one rendered card. | | Sequential conversion / original-byte retention | Implemented | Raw bytes use anonymous-file ranges; history/quota read one card at a time; copy batches stop at 256 rows / 8 MiB plus one card. Bulk commit retains the existing transaction/recovery path. | | Reported 228.1 MiB full HTTP peak | Recorded result confirmed; not a ceiling | Author log contains 233,540 KiB. Independent HTTP rerun: **280,796 KiB (274.2 MiB)**, 18.236 s. Independent disk fixture: **282,856 KiB (276.2 MiB)**, exceeding its 262,144 KiB gate. | | Replay / recovery / route behavior | Targeted tests pass | 45 action import tests, including update/mixed crash recovery; 1 server unit + 11 route tests. Source review found no additional replay/recovery defect. | ### New P1: shared group labels bypass the allocation reservation during rendering `crates/contacts/src/import_limits.rs:40` charges wire bytes and delimiter/line counts. However, `crates/contacts/src/note_io/fields.rs:118,222` associates one `X-ABLabel` with every property in its group. `write_line` at line 489 prints the entire label for each property, and `crates/contacts/src/note_io.rs:144` accumulates the result in an unrestricted String. The import calls `to_note()` before quota admission and retains that result in `Fresh`; bulk-plan creation subsequently copies/serializes it. The reservation's claim to cover rendering output is therefore false. Independent bounded reproduction on dev-02, linked to the branch's compiled contacts crate: ```rust let label = "l".repeat(256 * 1024); let mut card = format!( "BEGIN:VCARD\nVERSION:3.0\nUID:label-probe\nFN:Sample\nitem.X-ABLabel:{label}\n" ); for _ in 0..1024 { card.push_str("item.EMAIL:a@example.test\n"); } card.push_str("END:VCARD\n"); assert!(ImportBudget::new(ImportLimits::default()).push(card.as_bytes())); assert!(import_allocation_fits(card.as_bytes())); let contact = Contact::from_vcard_for_import("probe", card.as_bytes()).unwrap(); let note = contact.to_note().unwrap(); ``` Measured: **288,844 wire bytes → 268,457,034 rendered-note bytes**, capacity 268,515,328; **267,672 KiB peak RSS**, 7.283 s. Both checks accept it. This is conversion/rendering only, not a claimed full-route RSS measurement. The calculated reservation is 5,677,248 bytes, already exceeded by the note alone. A 1 MiB label with 4,000 same-group email properties still fits the 2 MiB line, 4,096 physical-line, card-byte and allocation checks, but requires about **3.9 GiB of note text** from roughly 1.1 MiB of wire input. Subsequent note/plan copies can exceed a 7 GB-class host. This larger case was calculated, not run. The HTTP upload cap cannot prevent it, and quota admission occurs too late. The large existing-book caveat is not needed to reproduce this issue. ### New P2: the documented full-scale RSS gate fails on an independent rerun `scripts/contacts-import-memory.py:64` failed at the disk fixture: 282,856 KiB versus its 262,144 KiB ceiling. Consequently, the script did not reach HTTP. I ran the unchanged HTTP test separately with a diagnostic 512 MiB measurement ceiling; it passed functionally at 280,796 KiB, which also exceeds the original 256 MiB ceiling. That diagnostic run is **not** a pass of the published resource gate. The 228.1 MiB number comes from absolute child-process peak RSS (`os.wait4`) for a specific 20,000 × 5,242-byte fixture into an empty Home. Most wire content is `X-PADDING`, retained in the spool rather than the visible note. Ten percent of cards are unsupported 2.1; some accepted cards contain a 128-byte NOTE or a small photo. The peak includes retained upload strings, parser/converter scratch, naming/matching facts, bulk-plan/seed/serialized representations, SQLite, summary and completed background publication. There is no allocation profile attributing the exact peak among those components. Thus this is a fixture measurement, not a proof that all accepted 100 MiB files stay under 256 MiB. More visible NOTE/field content can retain larger plans even without the P1. A single 228–276 MiB import is reasonable on a 4-core/7 GB-class host; multi-GiB rendered output is not. Existing book state and concurrent uploads add further memory. Stabilize the representative resource gate and add derived-output cases; merely raising the gate does not fix P1. Cheap reductions after establishing the bound: move `note` into `Step::Create` instead of cloning it (`import.rs:600`, compute its length first); omit over-1-KiB matching keys from retained `MatchFacts`, not only the lookup maps. Neither substitutes for the rendering limit. ### Concrete simpler design Keep sequential conversion and raw spooling, but replace the inferred rendering allowance with explicit derived-byte limits: 1. Keep the existing raw/line/object checks. Before constructing render views, account for shared-label length × reference count with checked arithmetic, including any cleaned copies. 2. Give import rendering a bounded writer and an explicit per-note byte ceiling, for example 8 MiB. Stop before allocation growth and return durable `skipped: too large`; preserve accepted original bytes. 3. Limit aggregate retained note/plan bytes independently of upload bytes, for example 128 MiB, and reserve room for serialization/copies. Reject or skip before retaining excess data. Document the chosen capacities rather than adding further cross-layer copy optimizations to infer a bound. 4. Gate the shared-label fixture, a near-limit visible-note fixture, and a supported-version full HTTP import through completed publication. Verify skipped outcomes replay/recover through the existing bulk summary. This gives direct input, object, rendered-card and aggregate-plan bounds without relying on a payload multiplier to model shared references. ### Validation and limits VM execution used `cua@calternal-dev-02-std`, Nix and `~/bin/slot`. VM checkout was `ca779da171dadb6ef1935436f01f05b418a8edbf`; `git diff ca779da1..7b932eb9 --stat` confirms the requested head adds only the measurement documentation, with no code/test difference. - `~/bin/slot python3 scripts/contacts-import-memory.py`: conversion + disk parameter probes passed; full disk fixture **failed the RSS ceiling**; HTTP was not reached. - `~/bin/slot cargo test -j4 -p calternal-contacts-actions --locked import`: **45 passed, 2 ignored**. - `~/bin/slot cargo test -j4 -p calternal-server --locked contacts_import`: **1 unit + 11 route tests passed**. - Separate fresh-process HTTP measurement reused the script's `binaries()` / `measure()` functions with a diagnostic 512 MiB ceiling: test passed, 280,796 KiB RSS. - Shared-label probe compiled with `rustc --edition=2024 /tmp/pr800-review3-label.rs -o /tmp/pr800-review3-label -L dependency=target/debug/deps --extern calternal_contacts=<branch rlib>`, under the same Nix/slot wrapper; Python `os.wait4` measured the child. Artifacts: `/tmp/pr800-review3-label.{rs,py}`, `~/pr800-review3-label.log`; gate logs: `~/pr800-review3-{gates,extra,http}.log`. No builds/tests ran on the control host. Author-reported fmt/clippy/full-suite results were inspected, not independently rerun. A supplemental visible-NOTE HTTP probe did not compile because its standalone linking selected incompatible duplicate dependency artifacts; no measurement from that attempt is used here. **New severity counts: P0 0, P1 1, P2 1, P3 0. Verdict: stop and simplify.**
Author
Owner

On hold pending the contacts import v2 plan in #815 (docs/plans/0064-contacts-import-v2.md, head f97f322b). No further v1 fixes are proposed after the final review round.

The plan puts an incremental byte limit on every converted output, removes shared-label/parameter allocation fan-out, and streams one card through disk-backed preparation, history and publication. It retains exact raw sources and ADR 0063/0064 companions, keeps suggestions capped and exact-key only, and requires full 20,000-card / 100 MiB HTTP and disk measurements below 192 MiB absolute peak RSS. It includes the three review rounds, failure table, salvage list and reviewable slices. Docs only; no implementation or repository settings changed.

On hold pending the contacts import v2 plan in https://git.kayg.org/kayg/calternal/pulls/815 (`docs/plans/0064-contacts-import-v2.md`, head `f97f322b`). No further v1 fixes are proposed after the final review round. The plan puts an incremental byte limit on every converted output, removes shared-label/parameter allocation fan-out, and streams one card through disk-backed preparation, history and publication. It retains exact raw sources and ADR 0063/0064 companions, keeps suggestions capped and exact-key only, and requires full 20,000-card / 100 MiB HTTP and disk measurements below 192 MiB absolute peak RSS. It includes the three review rounds, failure table, salvage list and reviewable slices. Docs only; no implementation or repository settings changed.
Author
Owner

housekeeping #1009: needs-decision.

Explicit hold and replacement by bounded contacts import v2 plan #815 / WIP #817. Preserve duplicate/import vectors rather than replaying the older importer.

original head: 7b932eb9627b364ddc55bb370eb7f597e1762f2d. against dev cd7f84432febfc63b788fbb9b9f9950452982d74, git cherry reports 49 unmatched and 0 equivalent patches. the landing audit lists each candidate missing commit and stable patch match in pr-800.md; unmatched patches can include superseded behavior.

left open, source branch unchanged. no rebase or new test claim for this decision lane.

housekeeping #1009: needs-decision. Explicit hold and replacement by bounded contacts import v2 plan #815 / WIP #817. Preserve duplicate/import vectors rather than replaying the older importer. original head: `7b932eb9627b364ddc55bb370eb7f597e1762f2d`. against dev `cd7f84432febfc63b788fbb9b9f9950452982d74`, git cherry reports 49 unmatched and 0 equivalent patches. the [landing audit](https://git.kayg.org/attachments/fe3c09dc-dea3-47a0-92e2-b44a777083e5) lists each candidate missing commit and stable patch match in `pr-800.md`; unmatched patches can include superseded behavior. left open, source branch unchanged. no rebase or new test claim for this decision lane.
Author
Owner

Superseded by #815/#817 (contacts import v2). The branch and original tips are archived under archive/ (see #1009), so nothing is lost; useful regression vectors are noted there for the active lanes. Closing.

Superseded by #815/#817 (contacts import v2). The branch and original tips are archived under `archive/` (see #1009), so nothing is lost; useful regression vectors are noted there for the active lanes. Closing.
kayg closed this pull request 2026-11-07 21:21:06 +00:00
Some checks failed
CI / server (pull_request) Has been cancelled
CI / rust (pull_request) Has been cancelled
CI / web (pull_request) Has been cancelled

Pull request closed

Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
kayg/calternal!800
No description provided.