Skip to content

Release 0.8.14: queue cleanup batch (10 issues + 7 stale closures) - #474

Merged
neuromechanist merged 101 commits into
mainfrom
dev
May 14, 2026
Merged

neuromechanist merged 101 commits into
mainfrom
dev

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

Summary

Cleanup batch: closes 17 issues, addresses 10 user-visible bugs / features / refactors. Auto-tag pipeline will strip -devN suffix and tag v0.8.14 on merge.

Closed via this PR (10 merges)

# Title
#94 Exit non-zero on publish request/status errors
#275 Key rate limiter on user id for admins (500/60s, token-hash bucket)
#284 Show step + s3-lock progress in publish approve
#287 Validate workflow parseability after CI deploy
#339 Sync to nemar.org on version DOI publish (Zenodo branch parity)
#381 Add admin notify --user <username> for per-user emails
#447 Fix dataset list --mine auth header (stale-token detection)
#452 Fix 4 failing tests + gate bun test in CI (unit-test-all job)
#459 Skip empty funder/creator entries in DataCite XML
#460 Warn when pulling a dataset still being ported (with --skip-port-check)

Closed up-front (7 stale/subsumed)

#196, #205, #346, #366, #367, #368, #389.

Migrations

  • 0021_broadcast_user_recipient.sql — relax CHECK on broadcast_emails.recipient_group to allow user:<username> for per-user notify (transactional rebuild, no PRAGMA, no FK drops).

New CI

  • unit-test-all job in .github/workflows/test.yml runs every test/*.test.ts except long-running e2e/sandbox suites on PRs to dev and main. Branch protection updated to require it.

Follow-up issues filed during the work

Test plan

  • bun test (unit-test-all in CI) green on dev HEAD
  • Two-round Sonnet PR review on each of the 10 feature PRs (criticals + importants addressed before merge)
  • Brand-new dev → main Sonnet review (pending on this PR)
  • auto-tag.yml runs on merge: strips -dev10, tags v0.8.14, triggers npm-publish.yml
  • sync-dev.yml advances dev to 0.8.15-dev0 after publish

nemar-bot and others added 30 commits May 13, 2026 07:04
- Add xx-prefix (sandbox) to shouldSyncToNemarAfterVersionDoi skip list;
  sandbox datasets pass the gate, causing false-alarm failed sync rows
- Remove redundant && published.doi guard on the Zenodo trigger: true
  already guarantees versionDoi is non-null via the no_doi predicate;
  align with EZID caller which doesn't repeat this check
- Add sandbox log line to the Zenodo else branch for consistency
- Add backend/test/version-doi-sync-trigger.test.ts covering all
  decision paths including the new sandbox case (10 tests)
- Rename BucketSelection -> __BucketSelection (test-only convention)
- Rename AUTH_MAX_REQUESTS_AUTHED -> TOKEN_MAX_REQUESTS_AUTHED (clearer)
- Tighten AUTH_PATHS matching: exact or /- or ?-prefixed subpath only
- Replace "unknown" IP fallback with crypto.randomUUID() to avoid pooling
- Add TTL-aware InMemoryCache and window-reset test (14th test)
Adds the missing unconditional test for publish resend (mirrors the
existing status/request bogus-key tests). Also changes nm000104 to
nm099999 in the two existing bogus-key tests (test convention).
- Mark authAttempted as optional in Variables type (was a lie)
- Extend stale-token 401 hint to GET /datasets/:id
- Note lowercase bearer fallthrough in middleware comment
- Fix test comment: authMiddleware -> optionalAuthMiddleware
- Add negative assertion and test for /:id stale-token path
Apply trim-and-length guards to awardNumber and awardTitle in
buildDataCiteXml so whitespace-only values are suppressed. Also trim
uploaderName before pushing to contributors so surrounding whitespace
does not appear in emitted XML.

Adds tests for whitespace-only awardNumber/awardTitle suppressed,
padded values emitted trimmed, and padded uploaderName emitted trimmed.
Backend was returning s3_lock_total and s3_lock_batch_count on the
hasMore=true and error paths but not on the final non-paging success
path. The CLI accumulates s3_lock_batch_count from every response so
the last batch was never counted — progress read short by one full
page (e.g. 3963/4963 at "complete" for a 4963-object dataset).

Fix: capture s3LockFinalTotal/s3LockFinalBatchCount before calling
updateProgress("s3_lock") and include them in the final c.json
response. Also update the test comment to make the contract explicit
so the fixture can no longer mask this class of bug.
Two Important review findings addressed:

1. Spinner reset on Worker retry: add s3LockResumed flag to
   PublishProgressInfo. When an outer retry fires while the continuation
   token is set (mid-s3_lock), subsequent progress events carry
   s3LockResumed=true and renderProgress appends "(resumed)" to the
   spinner line. The locked counter (s3LockLocked) is kept at function
   scope across retries so the display shows accumulated progress rather
   than appearing to restart from zero.

2. Subrequest budget for getDatasetS3Stats: add maxPages parameter that
   caps the LIST sweep at N pages. The s3_lock path in admin.ts passes
   MAX_COUNT_LISTS=20 (covers up to 20000 objects). If the dataset is
   larger, objectCount returns undefined and the CLI degrades to a
   running count without a denominator — correct behaviour rather than
   risking "Too many subrequests" on the first Worker invocation. All
   callers updated to handle objectCount: number | undefined.
- fix: API-fail false-negative in get: fall back to reading local
  .nemar/metadata.json when backend is unreachable so port check
  fires even offline
- fix: update detectImportMarker JSDoc to clarify -1 semantics
  (most recent commit, not any-commit) and add forward-compat note
- feat: add --skip-port-check to both download and get commands so
  admins and automation can bypass the check
- fix: replace misleading retry hint in download; clone already
  exists, instruct user to wait then run get from that dir
- fix: replace "~5 minutes" with "5-30 minutes depending on size"
  in both commands
- docs: add unknown-case comment at both call sites
- test: add git-rm deletion case for detectImportMarker
- Add validation_warnings field to AddCiResponse type
- Print yellow warning block after workflow list in ci add
- Print per-dataset warnings in --all loop with dsSpinner.warn()
- Add --no-validate flag to ci add for fleet deploys
- Pass ?validate=false query param to backend when --no-validate used
- Backend reads validate param and forwards to deployWorkflows()
- Include validation_warnings in audit log details
- Add retry in deployWorkflows: probe at 2.5s, retry once at 5s if missing
- Document disabled workflow state behavior in comments and JSDoc
- Add per_page=100 pagination comment in validateWorkflowsParseable
- Add 429 handling note in comment with TODO for future test coverage
- Update tests: expect 2 listing calls on missing, 3 on server-error
Make notify_user step non-fatal in publish approve
Remove BEGIN/COMMIT from migration 0021 (D1 rejects)
@neuromechanist

Copy link
Copy Markdown
Contributor Author

Second-pass silent-failure audit (pass 2)

New release blockers

None found.

New important

#484 notify_user double-failure: Resend error message is preserved correctly.
When both Resend and the inner audit INSERT fail, notifyUserWarning is set from errorMessage(err) on line 4138 before the inner try block runs. The inner catch (auditErr) only logs auditErr via console.warn; it does not overwrite notifyUserWarning. The Resend error message propagates to the response warning field as intended. No issue here.

#487 D1 migration 0021 partial-failure risk: MEDIUM concern.
The comment correctly notes D1 wraps each migration in an implicit transaction. However, D1's documented behavior is that a migration file is executed as a single batch — if one statement errors, it is unclear from public docs whether the entire migration rolls back or only the failing statement is skipped. The migration has 6 statements (CREATE, INSERT-SELECT, DROP, ALTER, CREATE INDEX x2). If DROP TABLE broadcast_emails fails after the INSERT-SELECT succeeded, broadcast_emails_new holds data but broadcast_emails still exists, leaving duplicate tables. Recommend adding a smoke-test query after the migration runs in CI to confirm broadcast_emails has the new CHECK constraint and broadcast_emails_new does not exist.

Acceptable (not release blockers)

#483 email_service_unconfigured only mapped to HTTP 500 in /admin/notify.
The sendPublicationApprovedEmail path in notify_user (step 15 of the publish orchestrator) calls sendEmail directly — not sendBroadcast — so it never returns the broadcast_id: -1 / error: "email_service_unconfigured" sentinel. A missing RESEND_API_KEY there just throws from fetch, which the non-fatal notify_user catch handles correctly. No unchecked path.

#486 authAttempted?: true tristate removal.
The type was narrowed from boolean | undefined to true | undefined. All consumers (datasets.ts lines 462 and 970) only check truthiness (if (attempted), if (!user && c.get("authAttempted"))). No consumer depended on the distinction between false and undefined. Safe narrowing.

#486 RecipientGroupOrUser template literal type runtime safety.
The user:${string} branch is only constructed from lookup.username, which comes from a validated D1 row. The user field in the request body goes through Zod z.string().min(3).max(30) before reaching the lookup. The DB CHECK constraint OR recipient_group LIKE 'user:%' handles any username, so no bypass of the constraint is possible from this path.

#475 process.exit(1) after auth discrimination.
The get command in dataset.ts runs inside the Commander action handler. No open file handles or network sockets are held at the point where the auth error is detected — the request has already completed and the response has been read. process.exit(1) is the correct CLI idiom here.

Confirmed-fixed from pass 1

No new release blockers. Safe to proceed with CI green.

@neuromechanist

Copy link
Copy Markdown
Contributor Author

Second-pass test coverage review — v0.8.14 (#474)


Coverage blockers (new)

None. No new critical gaps found in the changes introduced since pass 1.


Important gaps (new)

[I-1] notify_user failure test: audit_log write not asserted (criticality: 6)

test/publish-progress.test.ts line 384 verifies result.status === "published", notify_user step has status: "failed", and result.warning contains "Notification email failed". This is good. However the test drives a fake HTTP server, so it cannot observe whether the backend wrote an audit_log row via INSERT INTO audit_log ... action='notify_user_failed' (admin.ts lines 4141-4151). That inner try/catch also has a silent console.warn if the D1 write itself throws. A future refactor that drops the audit insert would not be caught by any existing test. The CLI-level test is exercising the contract correctly for its layer; the gap is an untested backend branch. Low urgency since it requires a D1-level integration test to close, but worth a follow-up issue.

[I-2] optionalAuthMiddleware authAttempted=true path not directly tested (criticality: 5)

The new code in backend/src/middleware/auth.ts sets authAttempted=true for malformed tokens (length < 32) and for valid-length tokens that fail DB lookup. The unit-test-all job covers backend/test/ but there is no test in backend/test/ that exercises GET /datasets?mine=true through optionalAuthMiddleware with a stale or malformed bearer token and asserts the 401 response says "stale token" rather than "Authentication required". The regression this prevents (#447) is the exact reason the code was added. A Hono in-process test using app.request() with a 40-char garbage token and ?mine=true would lock it in.


Confirmed-fixed from pass 1

[C-1] backend/test/ glob gap — Fixed by #475. The unit-test-all job in .github/workflows/test.yml now explicitly globs backend/test/*.test.ts via the for f in test/*.test.ts backend/test/*.test.ts loop with shopt -s nullglob. The no test files matched guard (exit 1) prevents the job from silently passing with zero backend tests.

Migration 0021 test completeness — All 5 invariants from issue #479 are covered. The BEGIN/COMMIT removal from #487 has no impact: the test never relied on transaction rollback semantics; it applies the migration as a script via db.exec() and validates the resulting schema state. No assertions are silently dead.

sendBroadcast RESEND_API_KEY precondition (#483) — Three tests in test/broadcast.test.ts (empty string, whitespace-only, valid key) operate at the service function level, not the HTTP handler layer. They correctly verify that sendBroadcast returns error: "email_service_unconfigured" and makes zero Resend calls. The HTTP-layer mapping (503 response when key is missing) is not covered by a unit test, which is an acceptable gap given the existing pattern.

HTTP-layer notify_user test (#486) — test/publish-progress.test.ts uses a real Bun.serve in-process fake backend, not the live dev API. This correctly exercises the request/response contract including JSON serialization, pagination drive, and the warning field surface. It does not call the live Cloudflare Worker.

unit-test-all CI gate — Confirmed. The job correctly excludes e2e-sandbox, e2e-upload, zenodo-sandbox, and ezid-sandbox by basename, not path, so relocation of those files would not accidentally re-include them. The nullglob guard prevents silent empty-run.


New test count (cumulative diff)

8 test files added or substantially modified: backend/test/migrations.test.ts (migration 0021, 11 tests), backend/test/rate-limit-buckets.test.ts, backend/test/version-doi-sync-trigger.test.ts (8 tests), test/broadcast.test.ts (schema + RESEND precondition, ~20 tests), test/publish-progress.test.ts (stepIndexFor + approvePublication, 9 tests), test/publish-workflow.test.ts, test/datacite.test.ts, test/api.test.ts.


Final coverage verdict

Pass 2 finds no blockers. The two important gaps (audit_log observability for notify_user failure, authAttempted stale-token path) are backend-integration-layer concerns suitable as follow-up issues rather than merge blockers. The primary risks from pass 1 (glob gate, migration correctness, non-fatal notify) are all closed. Safe to merge after CI is green.

@neuromechanist
neuromechanist merged commit 24ef389 into main May 14, 2026
20 of 21 checks passed

This branch was previously deployed

2 inactive deployments
development — 226edd90 Deployed May 14, 2026 by neuromechanist via deploy-dev #267
npm — 226edd90 Deployed May 14, 2026 by neuromechanist via publish #871
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