Skip to content

Phase 1: Tree-batched commit helper - #412

Merged
neuromechanist merged 2 commits into
feature/issue-406-epic-rate-limit-hardeningfrom
feature/issue-407-phase1-tree-batched-commits
May 10, 2026
Merged

neuromechanist merged 2 commits into
feature/issue-406-epic-rate-limit-hardeningfrom
feature/issue-407-phase1-tree-batched-commits

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

Summary

Introduces commitFilesAsTree() in backend/src/services/github.ts, a Git Data API primitive that commits N files in 4 REST calls instead of createOrUpdateFile()'s 2N. Rewrites the three highest-leverage callers and keeps createOrUpdateFile() for the genuine single-file paths.

Closes #407
Part of epic #406

Changes

  • New helper commitFilesAsTree(repo, branch, files, message, pat) in backend/src/services/github.ts. Resolves branch head -> creates tree -> creates commit -> fast-forwards ref. 4 calls regardless of N. Retries up to 3 times on 422 ref-conflict (refetching base each attempt).
  • deployWorkflows() rewritten to batch all workflow templates into one commit. Previous cost: 12 REST calls (2 per file x 6 templates) + 6 separate commits. New cost: 4 calls + 1 commit.
  • Admin enrichment handler (admin.ts) picks commitFilesAsTree when both .nemar/metadata.json and .bidsignore change, falls back to createOrUpdateFile when only metadata changes (per the N=1 crossover analysis in the plan).
  • Webhook enrichment handler (webhooks.ts) does the same. Preserves the existing partial-success error reporting (a failed batched commit reports the same error on both commitError and bidsignoreError so existing API consumers stay compatible).
  • Test-only NEMAR_GITHUB_API_URL global override so the Bun.serve fake GitHub can stand in for api.github.com. Read at call time via globalThis, no Node process types required, no production behavior change.

Tests

test/tree-batched-commit.test.ts (7 tests, all passing, no mocks; uses a real Bun.serve fake GitHub via the new test/helpers/fetch-counter.ts):

  1. Empty files array short-circuits to current SHA with zero writes.
  2. Single-file commit makes exactly 4 GitHub calls.
  3. Six-file commit (deployWorkflows shape) still makes exactly 4 calls.
  4. 422 ref-conflict retries with a fresh base and succeeds on the second attempt (8 total calls).
  5. Persistent 422 conflict exhausts retries and throws after 12 calls (3 attempts x 4).
  6. deployWorkflows end-to-end: success path, all workflow names returned, exactly 4 calls.
  7. deployWorkflows failure path: error propagated, empty deployed list.

Test plan

  • Unit + integration tests pass (bun test test/tree-batched-commit.test.ts -> 7/7).
  • Backend tsc --noEmit clean.
  • CLI lint (bun run lint) clean apart from a pre-existing warning in src/lib/git-annex.ts:120 unrelated to this PR.
  • Related test files unaffected (bun test test/admin-restructure.test.ts test/bids-ci.test.ts test/datacite.test.ts -> 144/144 pass).
  • E2E against nm099999 (nemar admin e2e-test --verbose) — run as part of epic finalization, not per-phase, since the publish flow path is also touched by Phase 3.

Out of scope (deferred to later phases per the epic)

  • Publish orchestrator file writes (admin.ts:3238, admin.ts:3307) — Phase 3 restructures the publish flow itself.
  • Rate-limit header inspection — Phase 2 (Phase 1: Tree-batched commits via Git Data API #408).
  • Replacing getTreeAtRef+getBlobContent with a single Contents API read — separate optimization, no rate-limit impact.

@github-actions

github-actions Bot commented May 10, 2026 •

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR412

Version: 0.8.9-PR412.8d1a234
Commit: 8d1a234


🤖 Updated on each push.

@neuromechanist

Copy link
Copy Markdown
Contributor Author

Pushed review fixes in 8d1a234. Addresses all 13 findings from the multi-agent review.

Production-code fixes

  1. 422 conflict body parsing (github.ts:1572-1588) — new isFastForwardConflict422() inspects the GitHub response message and only retries on "not a fast forward". Non-FF 422s (bad ref, signed-commit policy, missing reference) surface immediately so production hits on nm000109 (master) or nm000110-114 (adjusted/master(unlocked)) get a clear error instead of three 1-second sleeps + misleading message.
  2. commitFilesAsTree path validation — new validateTreeFiles() rejects empty paths, leading /, trailing /, .. segments, NUL bytes, and duplicates before any network call. Five dedicated tests.
  3. deployWorkflows return-value checks at the two call sites that previously dropped it on the floor (datasets.ts:1733, admin.ts:2709). Now throw instead of silently continuing with no workflows.
  4. Shared commitEnrichmentWithBidsignore helper (github.ts) extracted from the near-identical admin + webhook enrichment paths. Returns commitMode ("batched" | "single"), surfaces a soft bidsignoreReadError when the .bidsignore read fails, and throws a typed EnrichmentCommitError carrying the attempted commitMode so callers can decide error-field semantics.
  5. admin.ts resilience regression fixed — .bidsignore read failure no longer blocks the metadata commit (mirrors the webhook pattern).
  6. commit_mode field added to both admin and webhook enrichment responses so monitoring consumers can disambiguate batched-vs-single failures.
  7. Dropped "120000" from the mode union (YAGNI; re-addable without breakage when symlinks are needed).
  8. Removed dead throw lastError ?? ... (unreachable); the exhausted-retry case now annotates the final 422 throw with (exhausted 3 attempts).

Test fixes

  1. fetch-counter.ts captures request bodies so tests can verify call shape, not just call counts.
  2. Retry test now asserts rebased parents — parses the second POST /git/commits body and confirms parents[0] and base_tree reference the advanced base.
  3. 5 new tests for commitEnrichmentWithBidsignore — bidsignore missing entirely, bidsignore exists missing entry, bidsignore already includes entry (single-file fallback), bidsignore read failure surfaces soft error, commit failure throws typed error with correct commitMode for both batched and single paths.
  4. Test for non-fast-forward 422 ("Reference does not exist") throwing immediately without retries.
  5. Test for non-main branch (uses "master") end-to-end.
  6. Test for transient 502 on tree-creation retried via githubFetchWithRetry.
  7. Empty-array test tightened — asserts exactly 1 call and that it's the /git/ref/heads/... read.
  8. deployWorkflows failure test now matches the error string content.

Comment fixes

  1. Retry-count claim corrected ("up to 3 attempts (2 retries)" instead of "retry up to 3 times").
  2. "4 calls regardless of N" qualified to "happy path".
  3. New deployWorkflows JSDoc documenting all-or-nothing semantics.
  4. Trimmed redundant inline Step 1/2/3/4 comments; kept the 422-retry one.
  5. Trimmed verbose TreeFile JSDoc and the GITHUB_API rationale (focused on what's load-bearing).

Verification

  • 21/21 tests pass in tree-batched-commit.test.ts (was 7).
  • Backend tsc --noEmit clean.
  • Lint clean (the lone pre-existing warning at git-annex.ts:120 is unchanged).
  • Related test files unaffected: bun test test/admin-restructure.test.ts test/bids-ci.test.ts test/datacite.test.ts -> 144/144 pass.

@neuromechanist
neuromechanist merged commit db04d9f into feature/issue-406-epic-rate-limit-hardening May 10, 2026
1 check passed
@neuromechanist
neuromechanist deleted the feature/issue-407-phase1-tree-batched-commits branch May 10, 2026 22:33

This branch was previously deployed

1 inactive deployment
npm — 8d1a2348 Deployed May 10, 2026 by neuromechanist via publish #718
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