Skip to content

Stream s3_lock via continuation token, fix CF cap on small datasets - #386

Merged
neuromechanist merged 2 commits into
devfrom
feature/issue-385-s3-lock-continuation
Apr 28, 2026
Merged

neuromechanist merged 2 commits into
devfrom
feature/issue-385-s3-lock-continuation

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

Closes #385.

What broke

`nemar admin publish approve nm000130` (702 S3 objects) hit "Too many subrequests by single Worker invocation" inside the s3_lock step on the SCCN deployment, even after #383's cross-invocation retry. Every retry re-invoked correctly but hit the same cap — because each `applyObjectLock` call paginated the entire dataset's S3 prefix before locking 40 keys.

Root cause

Per-invocation cost was: ~7 D1 + ⌈N/1000⌉ LIST + 40 PUTs. For a 700-object dataset that's ~48 subrequests, at or over the cap on whatever plan the SCCN account is on (default subrequest budgets vary across plans, and the wrangler 3 → 4 bump in #1153e53 may also have affected accounting). User confirmed the same code worked pre-0.8.0 on the previous `neuromechanist` account.

Fix

Switch `applyObjectLock` (offset-paginated, full-list every call) to `applyObjectLockBatch` (continuation-token streamed). Each invocation issues:

  • 1 `ListObjectsV2` page with `max-keys=15`
  • ≤15 `PutObjectRetention` PUTs

Total: ~16 S3 subrequests + ~7 D1 = ~23 per invocation. Comfortable headroom on every plan tier, and constant regardless of dataset size.

Behavior

  • Backend route schema: new `s3_lock_continuation_token` field; legacy `s3_lock_offset` still parsed but ignored (so v0.8.4-and-earlier CLIs in admins' shells don't 422).
  • Backend response: returns `s3_lock_continuation_token` and `hasMore` instead of `s3_lock_offset`.
  • CLI `approvePublication` threads the token through its existing retry loop in place of the offset.
  • Standalone `POST /admin/datasets/:id/s3-lock` updated to match.
  • Idempotent on retry: 403 = already-locked = counted as success, so replaying the same continuation token after a transient failure is safe.

Out of scope

Test plan

The offset-based applyObjectLock paginated the entire dataset's S3
prefix on every invocation (full ListObjectsV2 plus a 40-PUT slice).
Per-invocation cost was ~7 D1 + ceil(N/1000) LIST + 40 PUTs which
tripped Cloudflare's per-invocation subrequest cap on the SCCN
deployment for datasets with even a few hundred objects. The CLI's
cross-invocation retry from #382 reinvoked correctly but every fresh
invocation hit the same cap.

Switch to S3 ListObjectsV2 continuation-token streaming:

- New applyObjectLockBatch issues exactly one LIST page (max-keys=15)
  plus up to 15 PutObjectRetention calls per invocation. Returns the
  next continuation token on hasMore. Subrequest cost is now bounded
  at ~22 regardless of dataset size.
- Backend route accepts s3_lock_continuation_token in the body and
  returns it in the hasMore response. Legacy s3_lock_offset still
  parsed but ignored, so v0.8.4-and-earlier CLIs don't reject the
  request.
- CLI approvePublication threads the continuation token through its
  existing retry loop in place of the offset.
- Standalone POST /admin/datasets/:id/s3-lock updated to match.

Idempotent on retry: 403 (already-locked) keeps counting as success,
so re-invoking with the same continuation token after a transient
failure replays the same batch safely.

Closes #385
@github-actions

github-actions Bot commented Apr 28, 2026 •

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR386

Version: 0.8.5-PR386.ddf2ff9
Commit: ddf2ff9


🤖 Updated on each push.

Both review agents converged on five real issues with the
continuation-token migration. All addressed:

1. CLI applyS3Lock (nemar admin s3 lock) was structurally broken: still
   sent body.offset (server ignores), read result.total/failed:string[]
   (server returns failed:{key,error}[]), and would infinite-loop
   re-locking page 1 of any dataset > 25 objects. Rewritten to thread
   continuation_token; S3LockResponse interface fixed; CLI command
   formats {key,error} pairs; defensive guard prevents loop on
   server-side missing-token bugs.

2. applyObjectLockBatch silently stopped streaming when S3 returned
   IsTruncated=true with no NextContinuationToken (contract violation
   or proxy bug). The dataset would be left partially locked - exactly
   the failure mode S3 Object Lock exists to prevent. Now throws so
   the orchestrator surfaces a 500 and the CLI retries.

3. Empty-page mid-stream early-returned hasMore=false and dropped the
   live continuation token. Subsequent pages of objects would never be
   locked. Now preserves the token on the empty-page path.

4. Schema accepted legacy s3_lock_offset for "back-compat" but this
   was a footgun: the new server doesn't return s3_lock_offset on the
   response, so an old CLI's pagination loop breaks out on the first
   hasMore=true and silently reports lock complete after only the
   first batch. Replaced silent-ignore with explicit 426 Upgrade
   Required so admins running old CLIs see a clear error instead of
   corrupt-by-omission success.

5. Partial-fail (failed.length > 0) returned 500 without echoing the
   continuation token. The CLI's retry would lose its place and
   re-stream from page 1. Now echoes the token so retry replays the
   exact failing batch (idempotent: 403=already-locked).

Also bumped batchSize 15 → 25: still well under any plan's
per-invocation cap, halves CLI round-trips for medium datasets
(702-object dataset goes from 47 to 28 batches).

Added 426 test case to publish-retry-classifier; verified the upgrade
error is not retried (otherwise old CLIs would loop indefinitely).
@neuromechanist

Copy link
Copy Markdown
Contributor Author

/review-pr findings + responses

Pushed ddf2ff9 to address issues from code-reviewer and silent-failure-hunter (codex-challenge agent failed to launch — missing Bash for the companion runtime, skipped).

Critical/High — addressed

1. Standalone CLI nemar admin s3 lock was structurally broken. It still sent body.offset (server ignores), expected total + failed: string[] (server returns failed: {key,error}[]), and would infinite-loop re-locking page 1 of any dataset > 25 objects, eventually printing [object Object] for failures. Fix: rewrote applyS3Lock to thread continuation_token, fixed S3LockResponse interface, fixed the CLI command formatting, added defensive throw if server says hasMore but doesn't return a token.

2. Truncated-with-missing-token = silent partial lock. applyObjectLockBatch previously short-circuited to hasMore: false when S3 returned IsTruncated=true with no NextContinuationToken (contract violation, proxy bug, etc.) — leaving the dataset partially locked while the orchestrator marked s3_lock complete. Fix: explicit throw so the orchestrator surfaces 500 and the CLI retries.

3. Empty-page early-return stranded the continuation chain. keys.length === 0 early-returned hasMore: false even when a token was present. Subsequent pages would never be locked. Fix: preserve nextContinuationToken on the empty-page path.

4. Old CLIs (v0.8.4 and earlier) silently report "lock complete". The schema accepted legacy s3_lock_offset but the response no longer carries it, so an old CLI's pagination loop breaks out on the first hasMore: true after locking only the first batch. The dataset gets published with most objects unlocked. Fix: explicit 426 Upgrade Required when s3_lock_offset is sent without s3_lock_continuation_token. Added 426 to the retry classifier's not-retried test cases so old CLIs see the upgrade error instead of looping.

5. Partial-fail response didn't echo the continuation token. On failed.length > 0 the orchestrator returned 500 without s3_lock_continuation_token, so the CLI's retry would lose its place and re-stream from page 1. Fix: echo the same token the caller sent so retry replays the exact failing batch (idempotent: 403=already-locked).

Important — addressed

6. batchSize=15 was overly conservative. Per-invocation budget on the SCCN deployment is ~50 subrequests; batchSize=15 left ~27 unused. Fix: bumped to 25 — still well under any plan's cap (~35 worst-case), but halves CLI round-trips for medium datasets (702-object dataset: 47 batches → 28).

Important — deferred (separate issue)

7. Large-dataset strategy ceiling. At batchSize=25, a 50,000-object dataset still takes ~2,000 sequential CLI invocations. For datasets above ~5K objects this approach is the wrong tool — should use S3 Batch Operations or bucket-level Default Object Lock Configuration. Current NEMAR datasets are small enough (max ~5K objects per nm-prefix dataset) that this isn't a live issue, but worth tracking. Will file a follow-up issue if no current dataset is at that scale; for now the immediate small-dataset breakage is fixed.

Comment / regex / replay

The comment-analyzer-style checks (continuation-token regex correctness, idempotency on replay, ListObjectsV2 contract guarantees) all came back clean from the reviewers. AWS doesn't emit prefixed forms of IsTruncated/NextContinuationToken, so the regex is fine. Replay with the same token is deterministic per AWS docs; 403 = already-locked = success keeps replay safe.

Test results

@neuromechanist
neuromechanist merged commit bcd3183 into dev Apr 28, 2026
14 of 15 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-385-s3-lock-continuation branch May 11, 2026 05:15
neuromechanist added a commit that referenced this pull request Sep 21, 2026
A lot of its state moved on 2026-09-20 and 2026-09-21. #387 and #397
merged, #399 landed the Python 3.12 floor and the Pyodide-bounded
dependency floors, #402 corrected #399, and #403 is open to merge
develop into the epic branch.

Records the correction rather than quietly restating the conclusion:
only compiled floors are a ceiling in the browser, because the test is
whether the package publishes a pure-Python wheel and not whether
Pyodide bundles it. The earlier claim that threadpoolctl>=3.6.0 was a
live broken install was wrong.

Also records the integration bug #403 exposed, since it is the argument
for not letting the epic branch drift again: MemmapData.__array_function__
returned NotImplemented for everything except copyto and put, and
defining that method opts a type into numpy's dispatch protocol where
NotImplemented raises rather than falling back. Develop's #351 test
covers that path and the epic branch never had it.

Notes that the case for holding #386 is weaker now that the epic branch
is no longer behind, and carries #400 and #401 as open.

This branch was previously deployed

1 inactive deployment
npm — ddf2ff91 Deployed Apr 28, 2026 by neuromechanist via publish #679
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