Skip to content

Phase 1: edge cache for zarr data plane - #1199

Merged
neuromechanist merged 4 commits into
feature/issue-1181-epic-zarr-servingfrom
feature/issue-1178-phase1-edge-cache
Sep 2, 2026
Merged

neuromechanist merged 4 commits into
feature/issue-1181-epic-zarr-servingfrom
feature/issue-1178-phase1-edge-cache

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

Summary

  • Range-keyed edge cache entries: a single accepted bytes= range gets its
    own cache key (canonicalCacheUrl + __cr=<normalised range>); the
    Workers Cache API refuses to store a 206, so an accepted range is written
    as a synthetic 200 (X-Nemar-Content-Range carrying the real
    Content-Range) and rebuilt into a real 206 on the way back out. Multi-
    range, malformed, and non-bytes Range headers pass through uncached exactly
    as before. 416 and any other non-206 answer to an accepted range is never
    cached.
  • Canonical cache key: origin + path + at most the v query parameter,
    dropping every other query parameter (including a client-supplied __cr,
    which would otherwise let a request poison the range cache).
  • cacheControlFor grows a tokened argument: a ?v= tokened request for
    zarr.json/index.json gets max-age=86400; untokened zarr.json is
    unchanged at max-age=60, and untokened index.json rises from 60s to
    3600s (safe because the zarr-ready callback already purges it on rebuild).
    Chunks are unchanged.
  • Every 404 the route produces now carries Cache-Control: public, max-age=60; the missing-object 404 (upstream 403/404 on a public dataset)
    is additionally cached at the edge under the canonical key so a probe
    storm for a missing object stops there. Bad-path and private-dataset 404s
    are not cached.
  • A createZarrDataRoutes(deps) factory with a ZarrDataDeps seam
    (cache, fetch, s3Base) so tests can supply a real in-memory cache and
    a real local upstream; zarrDataRoutes = createZarrDataRoutes() keeps
    index.ts untouched.

Measured on live zarr.nemar.org (#1178): every level-0 read is a Range
request that skipped the edge cache entirely, costing ~439 KB of per-user S3
round trips per 10s window; index.json alone is 95% of Worker egress (#1035)
at a 60s TTL despite being purged on every re-conversion.

Test plan

  • backend/test/zarr-data-cache.test.ts (29 tests): real Bun.serve()
    upstream with genuine single-range semantics (206/416/200/HEAD/ETag/404),
    a real in-memory CacheLike, and D1 via freshDb()/realD1() with one
    public and one private dataset, driven through the real Hono app via
    app.request(). Covers: ranged miss-then-hit, distinct ranges as separate
    entries, full GET after a ranged GET, a client-supplied __cr being
    ignored for keying, multi-range never cached, 416 never cached, tokened vs
    untokened Cache-Control for zarr.json/index.json, HEAD never
    touching the cache, CORS reapplied per requesting origin on a hit
    (including a range hit), missing-object 404 caching vs private-dataset
    404s never being cached, and canonicalCacheUrl/parseCacheableRange
    unit tests.
  • cd backend && bun test — full backend suite: 1357 pass, 0 fail.
  • bun run lint (Biome, root src/) and bunx biome check on the two
    changed backend files: clean.
  • bun run typecheck (root tsc --noEmit + tsc --noEmit -p backend):
    clean.
  • Mutation-tested the changed logic by hand: disabling range-keying,
    disabling 404 edge-caching, disabling CORS reapplication on a hit,
    forcing tokened to always false, and skipping the synthetic-200->206
    restore each independently broke the corresponding test(s); reverted
    after each check (git status --porcelain clean).

Part of epic #1181
Addresses #1178 (items 3, 4) and #1035

Range-keyed cache entries (single bytes-range, synthetic 200 storage
for the 206 the Cache API refuses), a canonical origin+path+v cache
key, tokened Cache-Control (zarr.json/index.json get a day when
?v= is present, index.json's untokened TTL rises 60s -> 3600s),
edge-cached missing-object 404s, and a deps seam (cache/fetch/s3Base)
so backend/test/zarr-data-cache.test.ts can drive the real route
against a real Bun.serve() upstream and an in-memory cache.

Addresses #1178 (items 3, 4) and #1035. Part of epic #1181.
@github-actions

github-actions Bot commented Sep 2, 2026 •

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR1199

Version: 0.9.12-PR1199.382e28d
Commit: 382e28d


🤖 Updated on each push.

Correctness: gate isPublicDataset() before every cache lookup, not
only on miss, so a dataset flipped private stops serving immediately
instead of up to a day later; a ranged 404 lookup now falls back to
the canonical negative-cache entry so a ranged probe storm converges;
a 206 with no Content-Range fails closed (stream through, warn, don't
guess); cached entries get a size cap (8 MiB range / 32 MiB full),
checked from Content-Length before any clone/put; 416 now passes
through as 416 with Content-Range instead of collapsing into 502;
cache.put failures are caught and logged instead of risking an
unhandled rejection under waitUntil; app.onError logs and still
applies CORS instead of a bare 500.

Cache key and TTLs: canonicalCacheUrl now derives the key from the
normalised S3 key (each segment encodeURIComponent'd) instead of the
raw request pathname, so differently percent-encoded spellings of the
same object collapse onto one entry; untokened index.json drops to
300s/3600s (was 3600s/86400s) with a corrected comment on why (the
zone id is unset in prod today, so the purge is a no-op and the TTL
is the only bound); the chunk-purge comment now says zarrPurgeTargets
never targets a chunk URL.

Types: NormalizedRange/CanonicalCacheUrl are branded strings;
cacheControlFor takes an options object; the test InMemoryCache
throws on a 206 (mirroring the real Cache API) with a comment on why
only 206.

Tests: 45 (was 29) in zarr-data-cache.test.ts, covering every item
above plus a v-token round trip, telemetry via a real binding-shaped
collector, four concurrent identical range requests, HEAD with a
Range header, and an upstream that ignores a well-formed single range.

Part of epic #1181
Addresses #1178 (items 3, 4) and #1035
@neuromechanist

Copy link
Copy Markdown
Contributor Author

Addressed all 18 items from the five-reviewer follow-up round (correctness 1-7, cache key/TTL 8-10, types/structure 11-13, new tests 14-18, plus the docstring wording fixes) in commit e83deb3.

Correctness

  1. isPublicDataset() now gates every non-OPTIONS request before any cache lookup (was: gated only on miss). A dataset flipped private now stops being served immediately instead of up to a day later.
  2. A ranged request whose range-keyed cache lookup misses now also checks the canonical (no-range) key for a cached 404, so a ranged probe storm against a missing object converges at the edge.
  3. A 206 with no Content-Range fails closed: streamed through uncached with a single console.warn naming the key, instead of guessing.
  4. Cached entries are capped (RANGE_CACHE_MAX_BYTES = 8 MiB, FULL_OBJECT_CACHE_MAX_BYTES = 32 MiB, both exported), checked against Content-Length before any clone()/put(). No Content-Length -> never cached either.
  5. Upstream 416 now passes through as 416 with Content-Range preserved and CORS applied, never cached (was collapsed into the generic 502 mapping).
  6. Every cache.put() is wrapped so a rejection is caught and logged (console.error("[zarr-data] cache.put failed", ...)) rather than risking an unhandled rejection under waitUntil.
  7. app.onError now logs "[zarr-data] unhandled" with the path and returns 500 with CORS applied, instead of a bare Workers 500.

Cache key and TTLs

  1. canonicalCacheUrl now derives the key from the normalised S3 key (origin + "/" + key, each segment encodeURIComponent'd) instead of the raw request pathname, so two differently percent-encoded spellings of the same object collapse onto one cache entry.
  2. Untokened index.json TTL corrected to max-age=300, stale-while-revalidate=3600 (was 3600/86400); the comment now explains CLOUDFLARE_ZONE_ID is unset in production today (so the zarr-ready purge is currently a no-op and the TTL is the only staleness bound), that Cloudflare purge-by-URL can't reach a Cache API entry under a custom key (applies to __cr range entries, not to index.json), and that raising it further needs the purge verified in staging once the zone id is provisioned. Tokened 86400 unchanged.
  3. cacheControlFor's docstring now correctly says zarrPurgeTargets() never targets a chunk URL (only index.json and each changed store's zarr.json).

Types and structure

  1. NormalizedRange and CanonicalCacheUrl branded string types; NEMAR_CONTENT_RANGE_HEADER constant used at both the write and read site.
  2. cacheControlFor(key, { tokened }) takes an options object instead of a positional boolean.
  3. The test InMemoryCache.put throws on a 206 (mirroring the real Workers Cache API), with a comment explaining it's 206 specifically -- a real 404 negative entry and the synthetic-200 range entry are both accepted, same as production.

New tests (backend/test/zarr-data-cache.test.ts, 45 tests total, up from 29)

  1. ?v= round trip: same tokened URL is a hit, different v values are separate entries, untokened is a third.
  2. Telemetry via a real binding-shaped ANALYTICS.writeDataPoint collector: range miss/hit and a full-object hit all report the correct byte counts.
  3. Four concurrent identical range requests: all 206 with identical bytes, at most 4 upstream hits, then a hit.
  4. HEAD with a Range header: never cached, never puts, forwards the Range upstream.
  5. A fake-upstream mode where the upstream ignores a well-formed single range and answers 200: passed through, never cached under the range key.

Also added a per-key upstream quirk switch to the fake Bun.serve() (no-content-range, no-content-length, ignored-range) to exercise items 3/4/18 against real (if deliberately misbehaving) HTTP responses, and a shared oversized fixture buffer for the two size-cap tests.

Gates

  • cd backend && bun test: 1373 pass, 0 fail (full suite).
  • bun run lint (Biome) and bunx biome check on both changed files: clean.
  • bun run typecheck (root tsc --noEmit + tsc --noEmit -p backend): clean.
  • Mutation-tested the five correctness fixes (1, 2, 4, 5, and the original phase-1 logic) by hand: each independently broke exactly the test(s) targeting it; reverted to a byte-identical file after each (diff confirmed) before moving to the next.

One implementation note, not a deviation: item 13's instruction text second-guessed itself mid-sentence (starts with "throw on response.status !== 200", then re-derives to "throw on 206 specifically"). I implemented the final, explicit instruction (206 only) and documented why in the comment.

@neuromechanist
neuromechanist merged commit c9949c0 into feature/issue-1181-epic-zarr-serving Sep 2, 2026
12 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-1178-phase1-edge-cache branch September 2, 2026 17:02

This branch was previously deployed

1 inactive deployment
npm — 382e28de Deployed Sep 2, 2026 by neuromechanist via publish #2169
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.

1 participant