capgo icon indicating copy to clipboard operation
capgo copied to clipboard

[codex] Store uploaded manifest file sizes

Open riderx opened this issue 6 months ago β€’ 9 comments

Summary (AI generated)

  • Add a service-role-only uploaded_file_sizes table populated by backend upload/storage observation, not CLI manifest payloads.
  • Hydrate manifest.file_size from backend-observed upload records and ignore any client-provided manifest size values.
  • Keep the legacy R2 HEAD fallback for old or missing upload records, then cache the observed fallback size for future manifests.
  • Gate the manifest insert trigger so only rows matching a backend-observed size skip on_manifest_create; forged or missing sizes still queue verification.
  • Isolate queue-consumer per-message failures so one thrown message becomes one failed result instead of failing the whole batch.

Motivation (AI generated)

on_manifest_create was doing one follow-up R2 metadata lookup per manifest row. Large bundles can contain thousands of files, which creates queue/archive growth and risks worker limits. The fix moves size capture into backend-controlled upload handling while preserving the R2 fallback for legacy rows.

The trust boundary matters here: the CLI can send malformed or malicious manifest data, but manifest.file_size is now written from sizes observed by the backend upload/storage layer only.

The queue consumer should also keep draining successful messages when one message handler throws before returning an HTTP response. That failure now stays attached to the one message, while successful messages can still be deleted.

Business Impact (AI generated)

This reduces new on_manifest_create queue pressure for modern uploads, makes large delta bundles more reliable, and avoids turning manifest size into a client-trusted billing/storage signal. It also reduces queue blast radius when one message handler fails unexpectedly.

Test Plan (AI generated)

  • [x] bun lint:backend
  • [x] bun typecheck
  • [x] bun run --cwd cli lint
  • [x] bun run supabase:with-env -- bunx vitest run tests/queue-consumer-message-shape.unit.test.ts tests/manifest-uploaded-size.unit.test.ts tests/files-r2-error.test.ts
  • [x] bun run supabase:db:reset
  • [x] bash scripts/check-supabase-migration-order.sh
  • [x] git diff --check
  • [x] GitHub CI after force-push

Generated with AI

riderx avatar May 13 '26 15:05 riderx

[!NOTE]

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • [ ] ▢️ Resume reviews
  • [ ] πŸ” Trigger review
πŸ“ Walkthrough

Walkthrough

This PR implements end-to-end manifest file-size tracking and improves queue resilience. Changes add a new uploaded_file_sizes table to persist backend-observed upload sizes, record completed TUS uploads across multiple handlers, hydrate manifest entries from observed sizes, type the CLI upload manifest, isolate queue message errors, and update tests for cache-first read behavior.

Changes

Manifest file_size tracking and queue resilience

Layer / File(s) Summary
CLI: typed partial upload manifest entries
cli/src/bundle/partial.ts
Introduce PartialUploadManifestEntry interface with file_name, s3_path, file_hash fields; type uploadPartial return as Promise<PartialUploadManifestEntry[] | null> and batch aggregation from any[] to typed array.
Type defs: uploaded_file_sizes table types
cli/src/types/supabase.types.ts, supabase/functions/_backend/utils/supabase.types.ts
Add Database["public"]["Tables"]["uploaded_file_sizes"] table type with Row, Insert, Update shapes for s3_path, file_size, app_id, owner_org, created_at, updated_at.
Files handlers: durable-object integration and response plumbing
supabase/functions/_backend/files/files.ts
Import upload-size helpers, record completed durable-object TUS responses via recordCompletedTusUpload, and return the stored durable-object response from the upload handler.
TUS proxy and recording: detect and record completed uploads
supabase/functions/_backend/files/supabaseTusProxy.ts
Parse uploadId from Supabase Location, copy Upload-Length into responses, read upstream progress (HEAD) or storage object size when needed, derive completed sizes, and safely call recordUploadedFileSize() on successful create/patch.
uploadHandler: conditional Upload-Length header
supabase/functions/_backend/files/uploadHandler.ts
Refactor TUS create/patch responses to build a Headers object and set Upload-Length only when uploadInfo.uploadLength is present.
Backend: uploadSize utilities
supabase/functions/_backend/files/uploadSize.ts
Add normalizeUploadedFileSize, recordUploadedFileSize to upsert into public.uploaded_file_sizes, and getCompletedTusUploadSize to derive completion from TUS Upload-Offset/Upload-Length headers.
Manifest trigger and version update: use observed sizes
supabase/functions/_backend/triggers/on_manifest_create.ts, supabase/functions/_backend/triggers/on_version_update.ts
on_manifest_create short-circuits when record.file_size is already positive and uses recordUploadedFileSize() to persist computed sizes; migration introduces a trigger function that queues on_manifest_create only when NEW.file_size is positive and matches public.uploaded_file_sizes. on_version_update adds getUploadedFileSizes() and hydrates inserted manifest rows' file_size from observed backend sizes (fallback 0), exporting test utilities.
Queue consumer: per-message error isolation
supabase/functions/_backend/triggers/queue_consumer.ts
Wrap per-message HTTP execution and CF-ID bulk update in try/catch to return synthetic 500 JSON responses on failures and continue cleanup instead of letting a rejection fail the whole batch.
Migration: uploaded_file_sizes table, trigger, and cleanup
supabase/migrations/20260513152858_fix_queue_archive_cleanup.sql
Create public.uploaded_file_sizes with file_size > 0 constraint, enable RLS and restrictive policies, revoke broad privileges, grant service_role, add index on (owner_org, app_id), add trigger_verified_manifest_create() that only enqueues when NEW.file_size is positive and matches a uploaded_file_sizes row, replace the manifest trigger to call it, add cleanup_queue_messages() SECURITY DEFINER function with per-queue isolation, and harden process_all_cron_tasks() ownership/exec grants and cron schedule for cleaning.
Tests: cached reads and manifest size validation
tests/files-app-read-guard.unit.test.ts, tests/manifest-uploaded-size.unit.test.ts
Reorder a mock assertion in the cache-read test and add manifest-uploaded-size.unit.test.ts validating handleManifest hydrates manifest.file_size from public.uploaded_file_sizes (observed value or 0 fallback).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

  • Cap-go/capgo#2247: Both PRs modify cli/src/bundle/partial.ts's uploadPartial output/metadata generation (returned manifest entry file_name/s3_path plus related typing), so the changes are directly code-level related.

Poem

🐰 A rabbit hops through layers deep,

where upload sizes now we keep.
I count each chunk, then store it right,
Manifests shine with size in sight,
Queues breathe easy through the night.

πŸš₯ Pre-merge checks | βœ… 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
βœ… Passed checks (4 passed)
Check name Status Explanation
Title check βœ… Passed The title clearly and specifically summarizes the main change: adding storage and tracking of uploaded manifest file sizes from the backend.
Linked Issues check βœ… Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check βœ… Passed Check skipped because no linked issues were found for this pull request.
Description check βœ… Passed PR description includes required sections (Summary, Test plan, and Checklist items) with substantive content covering motivation, business impact, and testing approach.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
πŸ§ͺ Generate unit tests (beta)
  • [ ] Create PR with unit tests
  • [ ] Commit unit tests in branch codex/manifest-file-size-upload

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 13 '26 15:05 coderabbitai[bot]

Merging this PR will not alter performance

βœ… 43 untouched benchmarks
⏩ 2 skipped benchmarks[^skipped]


Comparing codex/manifest-file-size-upload (eff81cb) with main (7d53749)

Open in CodSpeed

[^skipped]: 2 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

codspeed[bot] avatar May 13 '26 17:05 codspeed[bot]

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

This looks like it turns manifest.file_size into a client-trusted value for new uploads.

The migration changes on_manifest_create to only enqueue the R2 HEAD fallback when NEW.file_size IS NULL OR NEW.file_size <= 0, and on_version_update then copies entry.file_size into the version manifest via normalizeManifestFileSize(entry.file_size). The new CLI sends the real finalBuffer.length, but that value is still supplied by the client/upload request path, not derived server-side from R2.

A modified CLI or direct API caller can set any small positive file_size for uploaded manifest rows. Because the trigger skips on_manifest_create, the server never re-HEADs the object and the bogus size is persisted into the app version manifest. Any downstream storage/bandwidth/accounting, quota, or audit code that trusts the manifest size can then be under-reported while the actual R2 object is larger.

I think the optimization needs a trust boundary: either keep the R2 HEAD verification for client-provided positive sizes, or only skip the trigger when the row is written by a trusted backend path that has independently measured the uploaded object size. At minimum, the DB trigger should not let arbitrary positive file_size bypass server-side verification.

digzrow-coder avatar May 13 '26 20:05 digzrow-coder

Addressed in the latest commit. The CLI no longer sends file_size in manifest entries, and on_version_update ignores any client-provided size value. New manifest rows are hydrated only from public.uploaded_file_sizes, which is populated by backend upload/storage observation or by the legacy R2 HEAD fallback. The manifest trigger also only skips on_manifest_create when the inserted manifest.file_size matches that service-role-owned observed-size row; forged or missing values still enqueue the R2 verification path.

riderx avatar May 13 '26 22:05 riderx

One blocker remains in the forged/untrusted positive file_size path.

The migration now does the right first step: trigger_verified_manifest_create() only skips the queue when NEW.file_size matches public.uploaded_file_sizes; otherwise it enqueues on_manifest_create so the R2 HEAD fallback can verify it.

But the queued handler still exits immediately for any positive value:

if (record.file_size && record.file_size > 0) {
  return c.json(BRES)
}

So a manifest row inserted with file_size = 123 and no matching uploaded_file_sizes row follows this path:

  1. migration trigger enqueues it because the size is not backend-observed;
  2. on_manifest_create receives the row;
  3. updateManifestSize() returns before calling getManifestSizeWithRetry().

That means forged or stale positive sizes are still accepted instead of being revalidated, which contradicts the migration comment that β€œLegacy/missing or forged records still keep the fallback R2 HEAD.” The early return needs to distinguish verified backend-observed sizes from queued/unverified positive sizes, or the queued path should ignore the existing positive value and run the R2 size check before deciding whether to keep it.

nagiexplorer88 avatar May 13 '26 23:05 nagiexplorer88

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.