Skip to content

Phase: chunked annex keys count as present - #1674

Merged
neuromechanist merged 21 commits into
feature/issue-1671-epic-bru-upload-fixesfrom
feature/issue-1565-chunked-keys
Oct 8, 2026
Merged

neuromechanist merged 21 commits into
feature/issue-1671-epic-bru-upload-fixesfrom
feature/issue-1565-chunked-keys

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A git-annex special remote configured with chunk=1GiB stores <key>-S<chunksize>-C<n> objects and never the plain key.
isKeyPresentAtDeclaredSize looked up the plain key only, so verifyDatasetVersionS3 called every chunked file missing and data_complete stayed 0 for nm000276 although its chunks are in the bucket.
A key is now present when the plain object exists at its declared size, or when the plain object is absent and some chunking of the key is complete (issue #1565, first half).

The first commit is the contributor's original fix (PR #1651, bruAristimunha), preserved with authorship.
The commits on top are review refinements:

  • one definition: the key logic lives in shared/annex-key.ts, imported by the Worker (import-integrity.ts) and the CLI (s3-server-copy.ts), which re-export the old names so no importer changes; the grammar splits at the first -- like scripts/zarr/generate_zarr.py, and each function names its Python twin
  • bounded cost: a lazy per-listing index of C1 objects (whole-file key to the chunk sizes that key's own C1 objects carry), so a missing key is checked with one lookup; the first version tried every chunk size found anywhere in the listing, which an uploader with access to <id>/objects/* could inflate (50k distinct sizes against 2000 missing keys measured 16.8 s, enough for the Worker CPU limit to kill the integrity sweep); the cache is keyed by listing identity and revalidated by size, so staleness can only make a key read as missing, never present
  • keys with an -m<mtime> field work in the chunk path, and a plain -m key keeps its present-if-listed behavior
  • a plain object at the wrong size (truncated or oversized) is not rescued by chunks: the data plane serves the plain key, and a short plain object is served as a 200 with truncated bytes while an absent key fails loudly; the contributor's test that pinned the opposite is flipped deliberately
  • the geometry is stated exactly: n is the size divided by the chunk size, rounded up; every chunk is the chunk size except the last, which holds what is left (a full chunk when the size divides evenly); an empty file is one empty chunk
  • an amendment to ADR 0064 records that "present" now means recoverable, not servable, corrects the arithmetic (only the missing count shrinks; the denominator is unchanged and nothing needs a backfill), and names the side effects
  • descriptions of data_complete now say "whole or as a complete chunk set" (contract, API types, data router, metadata columns, the MCP search_datasets argument, and the regenerated shared/openapi.json)

Part of epic #1671. Supersedes #1651 (contributor PR retargeted to the epic branch). Issue #1565 stays open: the data plane and manifest.json still emit plain-key URLs for chunked keys.

For the owner to decide

  • data_complete = 1 is a public filter (catalog filter, MCP argument, API). It now means every data key is in the bucket, whole or as a complete chunk set, not that every key is servable. Whether it should be offered as a public claim before the data plane serves chunked keys, or whether this phase should wait for that half, is the owner's decision and is not made here.
  • Model-facing text: the MCP search_datasets data_complete argument now reads "...declared content, each file stored whole or as a complete chunk set." It does not say chunked files may not be downloadable yet. Add that caveat or not.
  • Deploy step: a stored data_complete = 0 stays 0 until something re-verifies the dataset (nemar admin data-integrity-sweep --reaudit, POST /admin/imports/:id/verify, a reindex, or the import retry engine). Nothing in this repository schedules the sweep, so the re-audit is a step for the release that carries this change.
  • nm000276: issue Data plane and manifest.json build plain annex object URLs, so chunked datasets 404 #1565 lists only C1..C94 of the 95-chunk key s100969566208, so the dataset flips to 1 only if the listing also holds C95 at the remainder size (37,834,752 bytes).

Behavior to know about

  • nemar admin fleet key-registration --apply uses the same presence test and will now record chunk-only keys in the location log as held by NEMAR's remote.
  • nemar dataset status prints its Data line only when data_complete is 0 and nemar dataset list leaves the column blank, so neither says anything about a chunk-only dataset until Data plane and manifest.json build plain annex object URLs, so chunked datasets 404 #1565 closes.
  • bytesPresent counts every stored byte, so a finished 1 GiB chunking beside an abandoned 512 MiB attempt both count; it is the physical bucket content, while declaredBytes is the logical size.
  • The import-failure surfaces (the publish gate in import-openneuro.ts, the issue accrual) keep their wording: imports copy plain keys server-side.
  • annexKeyDeclaredSize is unchanged and still scans the whole key, so a -sN-- in a free-text WORM or URL name can be read as a size; a test pins this as a documented exception.

Test plan

  • bun run typecheck (root and backend), biome check and bun run lint on the changed files
  • test/annex-key.unit.test.ts 34, test/chunked-key-availability.unit.test.ts 4, backend/test/import-integrity-chunked.test.ts 6, backend/test/import-integrity.test.ts 30, test/fleet-key-registration.test.ts 31 (a real git-annex repository), the ADR index test, and the MCP, OpenAPI and contract drift tests: all pass, 0 fail
  • bun build of the CLI entry and of the Worker module (--target browser, no node: imports); wrangler was not run
  • The CI-tier grep (testRequest|TEST_API_URL|runCli\() finds nothing in any touched test file or the new test/helpers/chunked-keys.ts
  • 25 mutations applied one at a time and restored byte-identical, each caught by at least one test (for example: empty-file chunk count fails 1, fall-through on any size mismatch fails 4, last chunk expected full fails 19, module-level size-keyed cache fails 12, no cache fails 2, bound removed fails 2, indexing C2 instead of C1 fails 7, the fleet registration scan counting only plain objects fails 1)
  • Live tier: backend changes reach the dev worker only when the epic merges to dev

Follow-ups (not in this PR)

  • data plane and manifest.json URLs for chunked keys (the second half of Data plane and manifest.json build plain annex object URLs, so chunked datasets 404 #1565)
  • a chunked_keys count in the availability report
  • the other hand-kept size regexes (manifest.ts, content-recovery.ts) and the archive and scrub tools that address objects/<key> by plain name
  • whether git annex get works for chunk-only keys
  • shared test vectors pinning the Python grammar to the TypeScript one
  • an ADR-level decision on annexKeyDeclaredSize reading a size from free text

bruAristimunha and others added 15 commits October 7, 2026 15:39
Datasets uploaded through a chunked special remote (nm000276, chunk=1GiB)
hold only '<key>-S<chunksize>-C<n>' objects in S3, never the plain key.
isKeyPresentAtDeclaredSize (backend import-integrity.ts and its CLI twin in
s3-server-copy.ts) looked up the plain key only, so verifyDatasetVersionS3
reported every such file missing, data_complete stayed 0 and 'nemar dataset
status' printed 'incomplete' although every byte was in the bucket; the CLI
fleet/recovery tools inherited the same false 'missing'.

A key is now also present when every chunk C1..Cn exists at the size
chunking gives it (chunk size for 1..n-1, the remainder for the last). A
missing or short chunk still counts as absent. The chunk index is built
once per listing. Serving chunked objects through the data plane (the 404
part of #1565) is not addressed here.
Move annexKeyDeclaredSize, isKeyPresentAtDeclaredSize, parseChunkKey and
the chunk index into shared/annex-key.ts, a pure module both
s3-server-copy.ts and import-integrity.ts import. The two hand-kept
copies are deleted; both files re-export the two functions their
importers already use. No behavior change; the tests import
parseChunkKey from the shared module.
annexKeyDeclaredSize reads -s<N>-- and returns null for a key with an
-m<mtime> field, so isChunkedKeyPresent returned false at that null and
chunked WORM-style keys were never present. Only parseChunkKey had been
tested with -m.

The chunk path now reads the size with annexKeyFieldSize, which looks at
the fields before the first -- and tolerates -m, as annex_key_size in
scripts/zarr/generate_zarr.py does. parseChunkKey anchors at the first
-- too, so chunk-shaped text inside the free-text name is not a chunk.
annexKeyDeclaredSize is unchanged: a plain -m key stays present-if-listed.

Tests cover presence for a chunked -m key, complete and incomplete.
isKeyPresentAtDeclaredSize fell through to the chunk check whenever
the plain object failed the size test, so a truncated plain object next
to a complete chunk set read as present. The data plane serves the plain
key, so that listing says complete over a served object that is short:
the #967 signature, and worse than absent.

Chunks are now consulted only when the plain object is absent. A plain
object that exists decides the answer by itself.

The contributor's test 'a truncated plain object is rescued by a
complete chunk set' pinned the opposite behavior. It is flipped on
purpose, in both test files, to assert the object is NOT rescued, and
the backend gains a compareManifestToListing case showing the key is
missing (and flagged zero-byte only when the plain object is 0 bytes).
isChunkedKeyPresent built a three-level Map (base key, chunk size,
chunk number) holding every chunk object in the listing, then walked
it per key. The listing now yields the distinct chunk sizes once, and a
key is checked by direct lookups of the exact chunk names, which
annexChunkKey writes the way annex_chunk_key does in
scripts/zarr/generate_zarr.py. The scan is lazy and cached per listing
as before, so a dataset with no missing plain keys never pays for it.

Presence answers are unchanged: any complete chunking of a key makes it
present, whatever order the sizes are tried in. Adds annexChunkKey
vectors and a round trip through parseChunkKey.
Strengthens the chunk presence tests so each rule fails when its line
is reverted:

- empty file: a -s0 key with only a C2 object, or a C1 that is not
  empty, is absent (reversing the 'declared === 0 ? 1' line made n=0
  and let any chunk size in the listing pass)
- two chunk sizes in one listing: a partial 512 MiB attempt beside a
  complete 1 GiB set is present in either insertion order, and two
  partial attempts are absent
- oversized middle or last chunk is absent
- a key with no declared size is never present through chunks
- another key's chunks do not count
- nm000276: s100969566208 at 1 GiB is 94 full chunks plus a 37,834,752
  byte C95, so the issue's C1..C94 listing reads as incomplete
- a chunk size first seen after the first lookup invalidates the cache
- the CLI and Worker modules re-export the one shared function

Mutation checks run on shared/annex-key.ts, one line at a time, each
killing at least one test: n=1 for empty, plain-size fall-through,
last chunk as a full chunk, first size only, oversized accepted, -m
size parse, cache never invalidated, unanchored chunk parse.
The availability numerator ADR 0064 defines, an object at its declared
size, now also counts a key whose complete chunk set exists, and
data_complete = 1 is a public filter. Records the change as a dated
amendment instead of a new ADR:

- present now means recoverable, not servable: the data plane and
  manifest.json still emit plain-key URLs for chunked keys, so the
  second half of #1565 stays open
- the withdrawal rule therefore never fires on account of a chunked key
  with a complete chunk set
- a chunked key with a missing, short or oversized chunk, and a
  truncated plain object, still count as missing

shared/annex-key.ts cites the amendment. The ADR index test passes.
A key absent as a plain object tried every distinct -S<size> found
anywhere in the listing, so the cost was missing keys times distinct
chunk sizes. Anyone who can write under <id>/objects/ can mint any
number of SHA256E-s1-S<n>-C1--x names, so the second factor was not
bounded by the dataset: 50,000 sizes against 2,000 missing keys took
16.8 s, enough for the Worker CPU limit to kill the integrity sweep.

The lazy per-listing scan now indexes only C1 objects, as whole-file key
to the chunk sizes that key's own C1 objects carry. A complete chunking
always contains C1, so a missing key is tried only at index.get(key).
The answer is the same; the work for a key is bounded by that one
file's chunkings, and memory is one entry per chunked file.

The cache stays keyed by the Map's identity and revalidated by its size.
Its comment now states the direction of error: a same-size edit leaves
a stale index, which can only make a key read as missing.

Also: drop the unreachable null-name branch (the chunk name is built
from an already-split key), rename annexChunkKey's parameter to
chunkNumber, and correct the header and docblock claims about which
functions read past -m and which scan the whole key.
The helper-level tests were repeated verbatim in the CLI and Worker test
files, with no extra kills. They now live once, in
test/annex-key.unit.test.ts, which covers the shared module directly.
The CLI file keeps the keysWithoutObjects, dataAvailability and
re-export checks; the Worker file keeps the compare and
computeVersionIntegrity checks, including the zero-byte versus missing
distinction. The two 'chunks added after the first lookup' copies are
gone: they passed with a cache that never invalidated. The one test that
kills that mutant stays.

New coverage:
- an oversized plain object (declared + 1) beside complete chunks is
  missing and not zero-byte
- the cache belongs to a listing, not a listing size (two equal-size
  Maps), and a listing is scanned at most once; a listing whose keys all
  exist as plain objects is never scanned
- 5,000 fake chunk sizes against 5,000 missing keys cost one plain probe
  per key, counted on a Map subclass, not timed
- a mixed listing with odd names and unsafe integers
- chunk geometry: an even split, C1 missing, a hole before the tail,
  8 bytes at chunk 4, the nm000276 interior gap, a stray C96
- keysWithoutObjects over a truncated plain object plus chunks;
  dataAvailability for a complete and a short chunked key
- computeVersionIntegrity on a chunked listing; bytesPresent counts
  every stored byte, so co-existing chunkings both count, on purpose
- the isSafeInteger guards, and annexKeyDeclaredSize reading a size out
  of a free-text name, pinned as a documented exception

Also drops the 'flipped from the contributor' comments, and corrects
two stale file headers.
scanDatasetKeyRegistration counts a key as held through
isKeyPresentAtDeclaredSize, so a key the bucket holds only as complete
chunks now appears in inBucket and toRegister, and a key with a missing
chunk stays missingContent. This follows from ADR 0063's presence test
and is the side effect of #1565 that reaches the location log: a repair
run with --apply will record such keys as held by NEMAR's remote.

The case runs against a real git-annex repository and its real keys,
with the listing laid out the way a chunked remote stores them.
A same-size edit to a listing leaves the cached chunk-size index stale.
The index only nominates sizes and every chunk is read from the live
Map, so the error can only make a key read as missing. The test swaps
C3 for an unrelated name at equal size and expects absent.
Corrects the first amendment against the code:

- the numerator is the missing count and only it shrinks; the
  denominator is the tree's distinct annexed keys and never reads S3, so
  no stored denominator changes. The Worker stores no ratio
  (data_complete is missingKeys.length === 0) and the 90% rule is
  evaluated only by the CLI's dataAvailability
- a stored data_complete = 0 stays 0 until something re-verifies it
  (data-integrity-sweep --reaudit, POST /admin/imports/:id/verify, a
  reindex, the import retry engine); nothing in the repository schedules
  the sweep, so the re-audit is named as a deploy step
- nm000276 is conditional: the issue lists only C1..C94 of a 95-chunk
  file, so the dataset flips only if its listing also holds C95
- the geometry sentence is stated once, in the wording the code uses
- the Zarr converter reassembles chunks; git annex get is unverified
- an unservable plain-key URL does not resolve (403 or 404); anonymous
  GET of an absent key on s3://nemar answers 403
- adds the side effects: key-registration --apply records chunk-only
  keys, dataset status and list stay silent, import-failure wording is
  unchanged
- whether data_complete = 1 stays a public claim is the owner's call

The ADR index test passes.
The title said the last chunk must be the remainder, which reads wrong
when the size divides evenly and the last chunk is a full one. It now
says every chunk is the chunk size except the last, which holds what is
left, matching the geometry comment in shared/annex-key.ts.
A key stored as a complete chunk set now counts as present, so the
descriptions of data_complete and of missing content that said 'present
at its declared size' or 'no object in the bucket' were no longer exact.
They now say whole or as a complete chunk set:

- shared/contract/dataset.ts, src/lib/api/datasets.ts and
  backend/src/services/data-router.ts (the data_complete field)
- backend/src/services/dataset-metadata-columns.ts and
  src/lib/api/admin.ts (the verify result and sweep response)
- src/lib/fleet-key-registration.ts: inBucket, missingContent,
  falselyClaimed, and the skipped-missing-content note
- scripts/generate-openapi.ts and the regenerated shared/openapi.json:
  the data_complete query parameter of the public API reference
- backend/src/mcp/schemas.ts: the data_complete argument of
  search_datasets, which the OSA assistant reads

No test pins these texts. The OpenAPI drift guard passes against the
regenerated document, and the schema parity, search_datasets, contract
and metadata-column tests still pass.
The note on what the C1 index holds, why it is bounded and which way a
stale cache errs described firstChunksIn but sat on the WeakMap. It now
sits on the function, with a one-line pointer on the cache.
@github-actions

github-actions Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR1674

Version: 0.10.15-PR1674.3efe89a
Commit: 3efe89a


🤖 Updated on each push.

Nothing imports ParsedChunkKey or isChunkedKeyPresent, so both lose
their export. annexChunkKey was imported only by a test while
production builds chunk names with chunkObjectName; it is deleted and
its round-trip test becomes a presence case through the same splitter
and builder: a key whose name holds '--' and chunk-shaped text is found
by its chunks. That case fails when the splitter reads the last '--'
and when the builder keeps only the last '--' segment.

KeyParts names the split key in place of three inline copies, and the
header says once that the module is shared and that generate_zarr.py
implements the same grammar. Behavior is unchanged.
firstChunksIn built Sets to dedupe each key's chunk sizes and then
copied them into arrays in a second loop. The cache now stores the Sets
as built: same dedup, same insertion order, same lookups, one loop less.
The shared-definition fact was restated in four places. The module header keeps it; import-integrity.ts and s3-server-copy.ts now say only that
they re-export it.
Wraps the over-long item in the module comment and replaces the
double-space JSDoc continuations on inBucket and missingContent with the
block form the neighboring members use. Comment text only.
The module test wrapped about 40 presence checks in
expect(isKeyPresentAtDeclaredSize(k, new Map([...]))).toBe(..). A
present(key, entries) helper replaces them, and the vectors every
chunked-key test file pasted (GiB, BASE_EEG, chunk, LAST, Entries,
complete1G) move to test/helpers/chunked-keys.ts, with chunk(n) defined
as chunkAt(2500000000, GiB, n) instead of a second template.

Redundant cases go, and no assertion that kills something is lost:
- 'an empty file stored as one empty chunk' repeated the last assertion
  of the empty-file test
- 'shrinking the listing rescans' passes with a cache that never
  invalidates, so it could not observe a rescan; the swap test and the
  appears-after-first-lookup test stay
- the two -m tests share a key and a name builder and are one test
- the nm000276 tests are one: it still asserts C1..C94 is incomplete,
  C95 at the 37,834,752 remainder is complete, C95 at a full chunk and
  C95 one byte short are absent, and the C1..C93 plus C95 gap is absent.
  The C96 test stays. The full-size and one-byte-short C95 assertions
  stay too: they are the deliberate check that a last chunk holds
  exactly what is left, which other geometry tests reach only by
  accident.
Both caller test files now take their vectors from
test/helpers/chunked-keys.ts and keep only what their caller adds.

Worker: the -m, two-chunkings and nm000276 cases used the same keys and
listings as test/annex-key.unit.test.ts and the Worker has no extra
branch for them; the complete-dataset and missing-chunk cases already
prove it reaches the rule. The truncated and oversized plain-object
cases are one loop over plain sizes 0, 7 and declared + 1, which keeps
the zero-byte distinction and the rule that the chunk check is not ORed
over the plain one.

CLI: the first two keysWithoutObjects cases are re-asserted by the
dataAvailability cases (same function, same outcome). The truncated
plain-object loop, both dataAvailability cases and the re-export check
stay.
@neuromechanist

Copy link
Copy Markdown
Contributor Author

Review record

One pass of the PR review toolkit (Sonnet agents): code review, test analysis, comment analysis, then a propose-only simplifier. No critical findings. Every finding below was fixed unless it is listed under "Not done". Tip at the time of writing: 3efe89a6.

Important

  • The chunk lookup cost was O(missing keys x distinct chunk sizes in the listing), and an uploader could inflate the second factor (code review; measured 16.8 s for 50k sizes x 2000 missing keys, enough for the Worker CPU limit to kill the integrity sweep on a poisoned dataset, which would then sort first on every run): the scan now indexes only C1 objects per whole-file key, a complete chunking always contains C1, so a missing key costs one lookup. Tests assert the bound structurally (exactly one scan for 200 absent keys; 5,000 fake chunk sizes against 5,000 missing keys cost exactly 5,000 get calls), not by wall clock.
  • The ADR 0064 amendment misstated the arithmetic (code review, comment analysis): the numerator is the missing count, the denominator is unchanged and never reads S3, and the Worker's data_complete is missingKeys.length === 0. Rewritten, with the re-audit named as a deploy step because a stored data_complete = 0 stays 0 until something re-verifies the dataset.
  • Claims about nm000276 and about recovery were not supported (code review, comment analysis): issue Data plane and manifest.json build plain annex object URLs, so chunked datasets 404 #1565 lists only C1..C94 of a 95-chunk key, so the statements are now conditional on C95; the git-annex recovery claim is removed (only the Zarr converter is verified); "gets a 404" is "does not resolve (403 or 404)".
  • "The last chunk holds the remainder" was wrong when the size divides evenly (comment analysis, test analysis): restated, and tested for 8 bytes at chunk size 4, and 2 GiB at 1 GiB.
  • Test gaps (test analysis, about 45 mutants run): an oversized plain object beside a complete chunk set, the load-bearing cache (without it 12k absent keys cost 15.9 s instead of 8 ms), the scan over plain and malformed names, chunk geometry holes (exact multiple, missing C1, gap, nm000276 interior gap), keysWithoutObjects and dataAvailability and computeVersionIntegrity with chunked data, and a registration-scan case on a real git-annex repository. All added.

Suggestions and nice-to-have (all applied)

  • Descriptions of data_complete corrected where this PR makes them inaccurate (contract, API types, data router, metadata columns, MCP, regenerated OpenAPI); header comments that overstated "everything is taken from the fields before the first --" (annexKeyDeclaredSize is the documented exception); review-history narration removed; number parameter renamed; stale file headers fixed.
  • Simplifier: annexChunkKey (test-only) deleted and its round-trip test replaced with a presence case, unneeded exports removed, the C1 index stores Sets directly, the duplicated test scaffolding moved to test/helpers/chunked-keys.ts, and wrapper tests that repeated shared tests deleted (net -111 lines). The three nm000276 edge assertions were kept after a proposed deletion would have left them asserted nowhere else.

Verification

  • 25 mutations applied one at a time, restored byte-identical, each caught by at least one test.
  • Typecheck, Biome, 256 tests across 8 files, MCP/OpenAPI/contract drift tests, Worker module builds for the browser target with no Node imports, tier grep clean.

Not done (tracked follow-ups)

  • data plane and manifest.json URLs for chunked keys
  • a chunked_keys count in the availability report
  • the other hand-kept size regexes and the archive and scrub tools addressing objects/<key> by plain name
  • whether git annex get works for chunk-only keys
  • shared test vectors pinning the Python grammar
  • an ADR-level decision on annexKeyDeclaredSize reading a size from free text
  • whether data_complete = 1 stays a public claim before the data plane serves chunked keys: the owner's decision

@neuromechanist
neuromechanist merged commit defad3e into feature/issue-1671-epic-bru-upload-fixes Oct 8, 2026
14 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-1565-chunked-keys branch October 8, 2026 00:46
@neuromechanist neuromechanist changed the title Phase: chunked annex keys count as present (#1565) Phase: chunked annex keys count as present Oct 8, 2026

This branch was previously deployed

1 inactive deployment
npm — 3efe89a6 Deployed Oct 8, 2026 by neuromechanist via publish #3234
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants