Repository navigation
feat: implement build-trace-v2 endpoint - #1272
Conversation
📝 WalkthroughSummary by CodeRabbit
<review_stack_artifact_start /> End-to-end implementation: data model, generated Ent artifacts, DB migrations, cache operations, server handlers, tests, and documentation.Defines BuildTraceEntry and BuildTraceSignature schemas, fields, indexes, timestamps, and signatures edge with cascade delete.range_95ffea5df670 range_381e70320277 range_8b90f4091718 range_916f8d69a4df range_bf8c75d085b6 range_b5875fa9f3c8Generated entity structs, edge containers, scan/assign helpers, dynamic Value access, Query/Update/Unwrap helpers for both entities.range_2cce646cda34 range_ff4e99fc020a range_4e64fdad34c6 range_96524e3eeb3e range_303129504d26 range_088599e01ec1 range_591e5b2a0aa8 range_57756dc2b694 range_d02b2bcfc559 range_21497a9290bb range_5ada7cfd63b8 range_ec9160ef6670Generated table/field constants, Columns/ValidColumn, validator variables, DefaultCreatedAt, and OrderOption/By* helpers including neighbor ordering.range_9d9bfeb3a18a range_4777e0b041f7 range_70ba33836e70 range_4e0eb8639cb1 range_33687fac1950 range_2b43da4f89ee range_9a191c746feb range_b24b35d24472 range_2246aeca642a range_4f353af94fa7 range_efb87281f495Field predicates (EQ/NEQ/IN/range), string match helpers, edge predicates and boolean combinators for both entities.range_5d60edf1bab7 range_51e812fbb934 range_d099455a3629 range_2596e901dd48 range_33cc5cc8ca4d range_e2dec7194045 range_2e20ffd14a1c range_17192b8d6e65 range_643d9a95b095 range_0da66ce018c8 range_663206a152bc range_b7ab3a100370 range_2e202a8de951 range_54dc81f2bc4b range_68ae3f7e2abc range_d12552e9d8be range_2ed2e0ddeb17Single and bulk create builders with defaults, validation, OnConflict/upsert APIs, and bulk conflict handling for entries and signatures.range_e0266a4f88e4 range_f9fdfc097753 range_60cdf75c9a63 range_4a160fa09a28 range_b9a97101d38d range_65f1ef2e4e11 range_f40b1759e464 range_af3d19c40079 range_11cf44205d6f range_14264c17cb22 range_aee2346b6f34 range_84b0ff402dc5 range_5c3bc566a8a6 range_4d2409697a29Generated delete builders and DeleteOne wrappers mapping zero-row deletes to NotFound errors.range_3af813fd2294 range_e7a6b02598a5 range_205dba346d19 range_e96cae598d0f range_d9cf5047e674 range_b8dbb48c1a5fQuery builders with predicate/pagination/ordering support, edge traversal/eager-loading, terminal operations, GroupBy and Select/Aggregate builders and scanning logic.range_ecf90eb6764d range_0fd7279da2fc range_c03bce535ace range_8afe55f2417a range_ed9879f3cfe6 range_140df75c59e8 range_60fbee52b980 range_0cff2fe983a0 range_389eb4344f91 range_707d43b56a07 range_50376340cf52Bulk and single-row update builders with nillable setters, Clear actions, edge add/remove/clear, validators, and SQLGraph save logic.range_357862703483 range_e3ef409c7688 range_d8395300c0f9 range_0a87d79aba2a range_b8e20e9f85c7 range_cad11355e2b2 range_4db715601fcc range_5dfb6d067bf0Wires generated clients into ent.Client/Tx, mutation types and routing, hook adapters, runtime validators/defaults, and migration metadata registration.range_7e527011198a range_f4bb994052df range_69769e7076a8 range_8eee785af160 range_a229921ff0a1 range_ac3239fc0da6 range_cd2abdd13568 range_badbec36486e range_131fee19de17 range_17bf95d89240 range_86585b5611f4 range_e279374e4c2e range_d8b425d09705 range_0ae77d106c74 range_df695c32af48 range_9361cd427909 range_ac5a84b63376 range_cc4f58e01711 range_112affe4483e range_386d1a048091 range_b8e87ed07f99 range_545c5b756f4b range_bfed45d1a7df range_30bbfdd8a58c range_2ecc62b1d9f6 range_b351ad584276 range_f1dd522966c7Per-dialect Goose migration SQL files creating build_trace_entries and build_trace_signatures with uniqueness constraints, indexes, FK cascade, and Down rollback paths.range_a0020621b39e range_21cd4c9c09bb range_8ba03e3f0917 range_ab2635d29489 range_a56cf8048ca3 range_89e8253574dfCache JSON types and helpers, deterministic fingerprint generation (strip signatures), HasBuildTrace, GetBuildTrace (reconstruct JSON + signatures), PutBuildTrace (validate, sign, transactional upsert, replace signatures via bulk insert with conflict handling), and ErrBadRequest sentinel.range_b2030e024b29 range_7e17b093366d range_1d034719b316 range_90a79702a739 range_f6d2e1ad370f range_ef1282d8ca75 range_078d0a9b5e10 range_5400284eefb5 range_99de2663c3d4 range_4e5e7f8713d8 range_b56910ba4436 range_078d0a9b5e10 range_5400284eefb5 range_99de2663c3d4Registers PUT (upload) and GET/HEAD endpoints, trims `.doi` from outputName, enforces putPermitted gating, maps cache/DB errors to HTTP responses, and delegates to cache methods.range_3d61d0000e5b range_483bc286157c range_b6526cd9c6b9 range_9febf1636f2f range_baa8f95193f4 range_9febf1636f2f range_9febf1636f2fUnit tests for fingerprinting and integration-style tests exercising Has/Put/Get lifecycle and HTTP handler behavior; test exports and test-suite registration.range_078d0a9b5e10 range_5400284eefb5 range_99de2663c3d4 range_804592a926e3 range_640493cb23ef range_615319a2db71 range_9b9ccc80c22e range_71c5fd8c73e1 range_0dfc715e6296 range_c63b99f327a5 range_50b36c97d7f4 range_270290b98649 range_2c486a3cf53f range_4e5e7f8713d8 range_b56910ba4436 range_5400284eefb5 range_99de2663c3d4 range_99de2663c3d4 range_4e5e7f8713d8 range_b56910ba4436 range_5400284eefb5 range_99de2663c3d4 range_4e5e7f8713d8 range_b56910ba4436 range_5400284eefb5 range_99de2663c3d4 range_4e5e7f8713d8 range_b56910ba4436Design doc, proposal, API surface, data-model spec, build-trace protocol spec, and tasks checklist documenting routes, validation rules, fingerprint/signature rules, and migration plan.range_6c9a18f43c87 range_b2017b2c6324 range_cbeb01f853d4 range_e49491f0f65a range_286692527d85 range_b36d6aa0f8bc range_600a4c7e2c48 range_73e600d62163 range_1ee787a8a419 range_2b2612b790ce range_0a86d35ede2c range_7cc7a7ad699e range_993a9c789ea0 range_efa107643c67 range_478b9bca90e0 range_b25d45a6b899 range_0445f6f16d80 range_847c5b71309b range_1205f7af3eaf range_5fcb5631b0d4 range_a6056fc7b574 range_3667c2e8afe5 range_1c1d8654c060 range_dd9c578f53d6 range_839f0cb53d72 range_6b914c86548d range_6499d487a542 range_e990fb3813bd range_5d661d9f71e1 range_0787a1d4f4f7 range_2ecc62b1d9f6✨ Finishing Touches📝 Generate docstrings
|
There was a problem hiding this comment.
Code Review
This pull request adds full support for the Nix build-trace-v2 binary cache protocol, implementing PUT, GET, and HEAD endpoints alongside new database schemas (build_trace_entries and build_trace_signatures) to persist CA-derivation build traces. The review feedback highlights several key improvements: optimizing the database upsert in PutBuildTrace by retrieving the inserted ID directly from the builder, correcting the signature deduplication logic to use the full key name (sig.Name) instead of c.hostName, and mitigating potential Denial of Service (DoS) vulnerabilities by limiting the request body reader size with io.LimitReader.
|
This change is part of the following stack: Change managed by git-spice. |
5a62b25 to
c825049
Compare
There was a problem hiding this comment.
Actionable comments posted: 10
🧹 Nitpick comments (1)
ent/schema/build_trace_signature.go (1)
47-51: ⚡ Quick winDrop the redundant single-column index on
build_trace_entry_id.Line 50 duplicates the leading column of the unique composite index at Line 49. Keeping both indexes adds unnecessary write and storage overhead.
Proposed change
func (BuildTraceSignature) Indexes() []ent.Index { return []ent.Index{ index.Fields("build_trace_entry_id", "key_name").Unique(), - index.Fields("build_trace_entry_id"), } }As per coding guidelines,
ent/**/*.go: “Ent schema files are the source of truth for DDL — hand-author schemas inent/schema/and commit the generated Ent client inent/directory after runningtask ent:generate”.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@ent/schema/build_trace_signature.go` around lines 47 - 51, The Indexes() declaration in BuildTraceSignature defines a unique composite index index.Fields("build_trace_entry_id", "key_name").Unique() and then immediately adds a redundant single-column index index.Fields("build_trace_entry_id"); remove the redundant index.Fields("build_trace_entry_id") entry from the BuildTraceSignature Indexes() slice to avoid duplicate leading-column indexing, then run the Ent generator (e.g., task ent:generate) and commit the regenerated Ent client to keep the DDL in sync.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@ent/client.go`:
- Around line 391-398: Remove the panic-based helper by deleting the GetX method
on BuildTraceEntryClient (the function that calls c.Get(ctx, id) and panics on
error) and any other similar GetX helpers (the ones referenced around lines
540-547), and update callers to call the existing Get(ctx, id) which returns
(*BuildTraceEntry, error); do not introduce panics or change Get's
signature—ensure all usages are replaced to handle the returned error instead.
In `@migrations/mysql/20260525175108_add_build_trace_entries.sql`:
- Around line 7-11: This migration includes destructive Down rollback statements
— remove the reverse/Down block so the migration is forward-only: delete or
comment out the lines that perform DROP TABLE for build_trace_signatures and
build_trace_entries (the "-- +goose Down" section and the two DROP TABLE
`build_trace_signatures`; DROP TABLE `build_trace_entries`; statements) so only
the forward (create/alter) statements remain, or replace the Down block with a
no-op per the repo's forward-only/expand-contract policy.
In `@migrations/postgres/20260525175108_add_build_trace_entries.sql`:
- Around line 13-23: The migration includes a "-- +goose Down" section with
destructive DROP INDEX and DROP TABLE statements (e.g. DROP INDEX
"buildtracesignature_build_trace_entry_id_key_name", DROP TABLE
"build_trace_signatures", DROP TABLE "build_trace_entries" and related index
drops) which violates the forward-only expand-contract policy; remove the "--
+goose Down" marker and all subsequent DROP statements so the file contains only
forward (up) DDL that creates the tables/indexes, ensuring no rollback SQL is
present.
In `@migrations/sqlite/20260525175108_add_build_trace_entries.sql`:
- Around line 56-63: The Down migration currently drops tables named
new_nar_files and new_narinfos which will not exist after the Up rename; instead
reverse the Up by renaming the new tables back to their original names (use
ALTER TABLE ... RENAME TO) and handle indexes against the correct table names
(or guard DROP INDEX / DROP TABLE with IF EXISTS). Specifically, replace the
DROP TABLE `new_nar_files` / DROP TABLE `new_narinfos` with ALTER TABLE
`new_nar_files` RENAME TO `nar_files` and ALTER TABLE `new_narinfos` RENAME TO
`narinfos`, and adjust DROP INDEX `narinfo_last_accessed_at` and DROP INDEX
`narinfo_hash` to target the index names that actually exist after Up (or use
DROP INDEX IF EXISTS) so the Down is idempotent and executable.
In `@openspec/changes/archive/2026-05-25-build-trace-support/design.md`:
- Around line 33-49: The fenced schema block containing build_trace_entries and
build_trace_signatures is missing a language tag; update the opening fence to
include a language identifier (e.g., change ``` to ```text) so the block becomes
a labeled code fence for markdownlint MD040 while leaving the schema content
(the build_trace_entries and build_trace_signatures definitions and comments)
unchanged.
In
`@openspec/changes/archive/2026-05-25-build-trace-support/specs/data-model/spec.md`:
- Around line 29-37: The spec and SQL example disagree on the type of the
signature column in build_trace_signatures: update the SQL example (CREATE TABLE
"build_trace_signatures") so that "signature" uses VARCHAR(255) to match the
textual spec and Ent's mapping (field.String()), or alternatively update the
spec text to say TEXT if you intend to keep the SQL as-is; ensure the change
references the build_trace_signatures table, the "signature" column, and
preserves the FOREIGN KEY to build_trace_entries (ON DELETE CASCADE) and the
existing "key_name" VARCHAR(255) semantics.
In `@openspec/specs/api-surface/spec.md`:
- Line 229: The spec contains conflicting status codes for denied uploads: the
line "Authorization: `putPermitted == false`" currently says 405 but other
upload sections state 403; pick one canonical response (either 403 or 405) and
make all upload-related references consistent. Update the "Authorization:
putPermitted == false" sentence and every upload/narinfo/NAR upload paragraph
that mentions 403/405 so they all use the chosen status code, and adjust any
explanatory text (e.g., "immediate 405 Method Not Allowed response") to match
the selected code.
In `@openspec/specs/data-model/spec.md`:
- Around line 317-325: The docs currently state Ent maps field.String() to
varchar(255) and imply `signature` is varchar(255`), but the SQL example defines
`signature` as TEXT; update the spec to remove the ambiguity by either (a)
changing the SQL example for build_trace_signatures so `signature` is
VARCHAR(255) to match the Ent mapping and the note about Ed25519 base64 length,
or (b) explicitly scope the SQL example per-dialect and add a sentence
explaining that in MySQL `key_name` and `signature` are VARCHAR(255) (per Ent
mapping) while other dialects may use TEXT—referencing the table name
`build_trace_signatures` and columns `signature` and `key_name` so readers can
find and reconcile the discrepancy.
In `@pkg/cache/build_trace.go`:
- Around line 168-177: The code currently compares only the basename of
entry.Key.DrvPath to drvName; change the validation to require full equality by
comparing entry.Key.DrvPath == drvFullPath(drvName) and return a
ErrBadRequest-style error (same format used now) when they differ; update both
occurrences (the block using bodyDrvName basename around the entry.Key.DrvPath
check and the later similar block at lines ~202-210) to use this full-path
equality check and ensure the error message mentions drvFullPath(drvName) vs
entry.Key.DrvPath for clear diagnostics.
- Around line 154-157: The read of the request body currently uses io.ReadAll(r)
with no limit and can OOM; wrap the reader passed to io.ReadAll with
io.LimitReader(r, maxSize) (pick a strict constant, e.g. maxTraceBodySize) and
after reading detect whether the body exceeded the limit (e.g. by comparing
bytes read to maxSize or attempting an extra byte) and return ErrBadRequest when
exceeded; update the code around the io.ReadAll call in build_trace.go (where
raw, err := io.ReadAll(r) is invoked) to use the limited reader and return
ErrBadRequest on limit violations.
---
Nitpick comments:
In `@ent/schema/build_trace_signature.go`:
- Around line 47-51: The Indexes() declaration in BuildTraceSignature defines a
unique composite index index.Fields("build_trace_entry_id", "key_name").Unique()
and then immediately adds a redundant single-column index
index.Fields("build_trace_entry_id"); remove the redundant
index.Fields("build_trace_entry_id") entry from the BuildTraceSignature
Indexes() slice to avoid duplicate leading-column indexing, then run the Ent
generator (e.g., task ent:generate) and commit the regenerated Ent client to
keep the DDL in sync.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: af23cd68-ab16-415b-bf2b-25a8b353ec8b
⛔ Files ignored due to path filters (3)
migrations/mysql/atlas.sumis excluded by!**/*.summigrations/postgres/atlas.sumis excluded by!**/*.summigrations/sqlite/atlas.sumis excluded by!**/*.sum
📒 Files selected for processing (44)
ent/buildtraceentry.goent/buildtraceentry/buildtraceentry.goent/buildtraceentry/where.goent/buildtraceentry_create.goent/buildtraceentry_delete.goent/buildtraceentry_query.goent/buildtraceentry_update.goent/buildtracesignature.goent/buildtracesignature/buildtracesignature.goent/buildtracesignature/where.goent/buildtracesignature_create.goent/buildtracesignature_delete.goent/buildtracesignature_query.goent/buildtracesignature_update.goent/client.goent/ent.goent/hook/hook.goent/migrate/schema.goent/mutation.goent/predicate/predicate.goent/runtime.goent/schema/build_trace_entry.goent/schema/build_trace_signature.goent/tx.gomigrations/mysql/20260525175108_add_build_trace_entries.sqlmigrations/postgres/20260525175108_add_build_trace_entries.sqlmigrations/sqlite/20260525175108_add_build_trace_entries.sqlopenspec/changes/archive/2026-05-25-build-trace-support/.openspec.yamlopenspec/changes/archive/2026-05-25-build-trace-support/design.mdopenspec/changes/archive/2026-05-25-build-trace-support/proposal.mdopenspec/changes/archive/2026-05-25-build-trace-support/specs/api-surface/spec.mdopenspec/changes/archive/2026-05-25-build-trace-support/specs/build-trace/spec.mdopenspec/changes/archive/2026-05-25-build-trace-support/specs/data-model/spec.mdopenspec/changes/archive/2026-05-25-build-trace-support/tasks.mdopenspec/specs/api-surface/spec.mdopenspec/specs/build-trace/spec.mdopenspec/specs/data-model/spec.mdpkg/cache/build_trace.gopkg/cache/build_trace_test.gopkg/cache/cache_test.gopkg/cache/export_test.gopkg/database/migrate/migrate_test.gopkg/server/build_trace_test.gopkg/server/server.go
c825049 to
41775d7
Compare
There was a problem hiding this comment.
Actionable comments posted: 5
♻️ Duplicate comments (3)
openspec/specs/api-surface/spec.md (1)
229-229:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winStatus-code consistency is still contradictory across upload specs.
This line says
405is consistent with existing narinfo/NAR upload behavior, but the narinfo/NAR upload sections still document403. Please normalize all upload authorization failure codes to one canonical value.Also applies to: 104-108, 169-170
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openspec/specs/api-surface/spec.md` at line 229, The spec currently inconsistently documents upload authorization failure codes; pick one canonical status (either 403 Forbidden or 405 Method Not Allowed), update the sentence that reads "Authorization: `putPermitted == false` ... 405 Method Not Allowed" to the chosen code, and then normalize every other upload-related occurrence (including the narinfo/NAR upload sections and any places referencing `putPermitted == false`) so all upload authorization failures use that same status code consistently throughout the spec.migrations/sqlite/20260525175108_add_build_trace_entries.sql (1)
52-63:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy liftReverse the SQLite table-recreation flow here.
After Line 11 and Line 23, the temp tables have already been renamed back to
narinfosandnar_files, soDROP TABLE new_narinfos/new_nar_fileswill fail on rollback. TheDownpath needs to mirror the recreate/copy/rename sequence against the live table names instead of targeting temp tables that no longer exist.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@migrations/sqlite/20260525175108_add_build_trace_entries.sql` around lines 52 - 63, The rollback SQL drops reference temporary tables that have already been renamed back to live names—modify the Down/rollback sequence so it targets the current live tables (narinfos and nar_files) or reorder the DROP statements to run before the RENAMEs; specifically update the DROP TABLE statements that reference new_narinfos and new_nar_files to instead drop narinfos and nar_files (or move those DROP TABLE new_* lines to occur before the ALTER TABLE/RENAME operations), ensuring the sequence mirrors the original recreate/copy/rename flow and uses the correct table identifiers (new_narinfos, new_nar_files, narinfos, nar_files).pkg/cache/build_trace.go (1)
153-156:⚠️ Potential issue | 🟠 Major | ⚡ Quick winDetect and reject oversized bodies instead of silently truncating.
io.LimitReader(r, 1024*1024)caps reads but does not indicate overflow. A payload larger than 1 MiB can be truncated and still parse, leading to incorrect persisted data.Suggested fix
+const maxBuildTraceBodyBytes = 1024 * 1024 + - raw, err := io.ReadAll(io.LimitReader(r, 1024*1024)) + raw, err := io.ReadAll(io.LimitReader(r, maxBuildTraceBodyBytes+1)) if err != nil { return fmt.Errorf("read body: %w", err) } + if len(raw) > maxBuildTraceBodyBytes { + return fmt.Errorf("%w: request body too large", ErrBadRequest) + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/cache/build_trace.go` around lines 153 - 156, Replace the current silent truncation via io.LimitReader by explicitly detecting oversized payloads: create a limit constant (e.g. maxBody := 1024*1024), read into a LimitedReader with N set to maxBody+1 (or use io.LimitedReader) from r, then call io.ReadAll; after reading, if len(raw) > maxBody return an error indicating the body is too large instead of proceeding (reference the variables/functions raw, r and the io.LimitReader/io.LimitedReader usage in build_trace.go).
🧹 Nitpick comments (1)
ent/schema/build_trace_signature.go (1)
47-51: ⚡ Quick winDrop the redundant single-column index on
build_trace_entry_id.
index.Fields("build_trace_entry_id", "key_name").Unique()already covers leading-column lookups bybuild_trace_entry_idin typical query plans, so keeping both indexes adds write/storage overhead.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@ent/schema/build_trace_signature.go` around lines 47 - 51, Remove the redundant single-column index in BuildTraceSignature.Indexes: the unique composite index created by index.Fields("build_trace_entry_id", "key_name").Unique() already covers lookups on build_trace_entry_id, so delete the separate index.Fields("build_trace_entry_id") entry to avoid unnecessary write/storage overhead while leaving the composite unique index intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@ent/buildtraceentry_create.go`:
- Around line 104-124: The generated panic-throwing helpers (SaveX, ExecX and
other *X variants produced by Ent, e.g., BuildTraceEntryCreate.SaveX / ExecX /
IDX) violate the rule "no panic outside main"; update the Ent code
generation/templates to stop emitting these panic helpers or replace their
implementations so they return errors instead of calling panic (e.g., change
SaveX to SaveOrError that returns (*BuildTraceEntry, error) or remove the method
entirely and ensure callers handle the error from Save/Exec); apply the same
change to all other generated *X helpers in this codegen so no generated method
calls panic.
In `@ent/buildtraceentry.go`:
- Around line 152-156: The Unwrap method on BuildTraceEntry currently panics
when config.driver is not a *txDriver; change Unwrap to return
(*BuildTraceEntry, error) instead of panicking: check _m.config.driver
type-assertion against txDriver, and if not ok return a descriptive error (e.g.,
"ent: BuildTraceEntry is not a transactional entity") rather than calling panic;
update all callers of BuildTraceEntry.Unwrap to handle the (entity, error)
return and propagate or handle the error accordingly; ensure references to
txDriver and _m.config.driver remain to locate the check to modify.
In `@openspec/changes/archive/2026-05-25-build-trace-support/design.md`:
- Around line 111-113: Replace the non-standard generation commands in the
migration plan (the lines that run `go generate ./ent/...`, `go run
./cmd/generate-migrations --name=add_build_trace_entries`, and the deploy note
about `ncps migrate up`) with the repo-standard tasks: run `task ent:generate`
to produce and commit the Ent client under ent/, and generate per-dialect Atlas
migrations using either `task migrations:gen NAME=add_build_trace_entries` (to
create migration directories) or `task migrations:sql
NAME=add_build_trace_entries` (to emit SQL), leaving the deploy note unchanged
about migrations being applied at startup.
In `@pkg/cache/build_trace_test.go`:
- Around line 123-126: Replace the panic(err) in the json.Marshal branch with
proper error propagation: have the helper that contains the json.Marshal(entry)
return (or forward) the error (or a wrapped error) instead of calling panic,
update its signature (e.g., return ([]byte, error)) and update any callers in
tests to handle the error (use require.NoError/require.Equal/etc. or t.Fatal on
error). Ensure you reference the json.Marshal(entry) result variable b and
propagate or wrap err so callers can assert on failures rather than the test
helper panicking.
In `@pkg/server/build_trace_test.go`:
- Around line 39-42: The helper btValidBody should not panic on json.Marshal
failure; change btValidBody to return (string, error) instead of string and
propagate the error from json.Marshal. Update all callers (tests that call
btValidBody) to handle the returned error and assert/fail the test on error
rather than relying on a panic; ensure the helper returns the marshaled string
on success and the original error on failure so callers can check it.
---
Duplicate comments:
In `@migrations/sqlite/20260525175108_add_build_trace_entries.sql`:
- Around line 52-63: The rollback SQL drops reference temporary tables that have
already been renamed back to live names—modify the Down/rollback sequence so it
targets the current live tables (narinfos and nar_files) or reorder the DROP
statements to run before the RENAMEs; specifically update the DROP TABLE
statements that reference new_narinfos and new_nar_files to instead drop
narinfos and nar_files (or move those DROP TABLE new_* lines to occur before the
ALTER TABLE/RENAME operations), ensuring the sequence mirrors the original
recreate/copy/rename flow and uses the correct table identifiers (new_narinfos,
new_nar_files, narinfos, nar_files).
In `@openspec/specs/api-surface/spec.md`:
- Line 229: The spec currently inconsistently documents upload authorization
failure codes; pick one canonical status (either 403 Forbidden or 405 Method Not
Allowed), update the sentence that reads "Authorization: `putPermitted == false`
... 405 Method Not Allowed" to the chosen code, and then normalize every other
upload-related occurrence (including the narinfo/NAR upload sections and any
places referencing `putPermitted == false`) so all upload authorization failures
use that same status code consistently throughout the spec.
In `@pkg/cache/build_trace.go`:
- Around line 153-156: Replace the current silent truncation via io.LimitReader
by explicitly detecting oversized payloads: create a limit constant (e.g.
maxBody := 1024*1024), read into a LimitedReader with N set to maxBody+1 (or use
io.LimitedReader) from r, then call io.ReadAll; after reading, if len(raw) >
maxBody return an error indicating the body is too large instead of proceeding
(reference the variables/functions raw, r and the
io.LimitReader/io.LimitedReader usage in build_trace.go).
---
Nitpick comments:
In `@ent/schema/build_trace_signature.go`:
- Around line 47-51: Remove the redundant single-column index in
BuildTraceSignature.Indexes: the unique composite index created by
index.Fields("build_trace_entry_id", "key_name").Unique() already covers lookups
on build_trace_entry_id, so delete the separate
index.Fields("build_trace_entry_id") entry to avoid unnecessary write/storage
overhead while leaving the composite unique index intact.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 584a05aa-a599-42f2-a079-0ac8cd21f6b0
⛔ Files ignored due to path filters (3)
migrations/mysql/atlas.sumis excluded by!**/*.summigrations/postgres/atlas.sumis excluded by!**/*.summigrations/sqlite/atlas.sumis excluded by!**/*.sum
📒 Files selected for processing (43)
ent/buildtraceentry.goent/buildtraceentry/buildtraceentry.goent/buildtraceentry/where.goent/buildtraceentry_create.goent/buildtraceentry_delete.goent/buildtraceentry_query.goent/buildtraceentry_update.goent/buildtracesignature.goent/buildtracesignature/buildtracesignature.goent/buildtracesignature/where.goent/buildtracesignature_create.goent/buildtracesignature_delete.goent/buildtracesignature_query.goent/buildtracesignature_update.goent/client.goent/ent.goent/hook/hook.goent/migrate/schema.goent/mutation.goent/predicate/predicate.goent/runtime.goent/schema/build_trace_entry.goent/schema/build_trace_signature.goent/tx.gomigrations/mysql/20260525175108_add_build_trace_entries.sqlmigrations/postgres/20260525175108_add_build_trace_entries.sqlmigrations/sqlite/20260525175108_add_build_trace_entries.sqlopenspec/changes/archive/2026-05-25-build-trace-support/.openspec.yamlopenspec/changes/archive/2026-05-25-build-trace-support/design.mdopenspec/changes/archive/2026-05-25-build-trace-support/proposal.mdopenspec/changes/archive/2026-05-25-build-trace-support/specs/api-surface/spec.mdopenspec/changes/archive/2026-05-25-build-trace-support/specs/build-trace/spec.mdopenspec/changes/archive/2026-05-25-build-trace-support/specs/data-model/spec.mdopenspec/changes/archive/2026-05-25-build-trace-support/tasks.mdopenspec/specs/api-surface/spec.mdopenspec/specs/build-trace/spec.mdopenspec/specs/data-model/spec.mdpkg/cache/build_trace.gopkg/cache/build_trace_test.gopkg/cache/cache_test.gopkg/cache/export_test.gopkg/server/build_trace_test.gopkg/server/server.go
✅ Files skipped from review due to trivial changes (8)
- openspec/changes/archive/2026-05-25-build-trace-support/.openspec.yaml
- openspec/changes/archive/2026-05-25-build-trace-support/tasks.md
- openspec/changes/archive/2026-05-25-build-trace-support/specs/api-surface/spec.md
- ent/runtime.go
- ent/ent.go
- ent/mutation.go
- openspec/specs/data-model/spec.md
- ent/client.go
| // SaveX calls Save and panics if Save returns an error. | ||
| func (_c *BuildTraceEntryCreate) SaveX(ctx context.Context) *BuildTraceEntry { | ||
| v, err := _c.Save(ctx) | ||
| if err != nil { | ||
| panic(err) | ||
| } | ||
| return v | ||
| } | ||
|
|
||
| // Exec executes the query. | ||
| func (_c *BuildTraceEntryCreate) Exec(ctx context.Context) error { | ||
| _, err := _c.Save(ctx) | ||
| return err | ||
| } | ||
|
|
||
| // ExecX is like Exec, but panics if an error occurs. | ||
| func (_c *BuildTraceEntryCreate) ExecX(ctx context.Context) { | ||
| if err := _c.Exec(ctx); err != nil { | ||
| panic(err) | ||
| } | ||
| } |
There was a problem hiding this comment.
Generated *X helpers violate the no-panic production rule.
SaveX/ExecX/IDX panic outside main, which conflicts with the repository rule for Go production code. Since this is generated Ent code, please either (a) switch Ent generation/templates to omit panic helpers, or (b) enforce a project rule that these *X helpers are never generated/used in committed code.
As per coding guidelines: "**/*.go: Do not use panic outside of the main function — always return errors instead".
Also applies to: 486-509, 579-599, 782-787
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@ent/buildtraceentry_create.go` around lines 104 - 124, The generated
panic-throwing helpers (SaveX, ExecX and other *X variants produced by Ent,
e.g., BuildTraceEntryCreate.SaveX / ExecX / IDX) violate the rule "no panic
outside main"; update the Ent code generation/templates to stop emitting these
panic helpers or replace their implementations so they return errors instead of
calling panic (e.g., change SaveX to SaveOrError that returns (*BuildTraceEntry,
error) or remove the method entirely and ensure callers handle the error from
Save/Exec); apply the same change to all other generated *X helpers in this
codegen so no generated method calls panic.
| func (_m *BuildTraceEntry) Unwrap() *BuildTraceEntry { | ||
| _tx, ok := _m.config.driver.(*txDriver) | ||
| if !ok { | ||
| panic("ent: BuildTraceEntry is not a transactional entity") | ||
| } |
There was a problem hiding this comment.
Unwrap() violates the no-panic rule outside main.
Please replace this panic path with an error-returning flow (or adjust generation/template strategy) so misuse does not crash process code paths.
As per coding guidelines **/*.go: "Do not use panic outside of the main function — always return errors instead".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@ent/buildtraceentry.go` around lines 152 - 156, The Unwrap method on
BuildTraceEntry currently panics when config.driver is not a *txDriver; change
Unwrap to return (*BuildTraceEntry, error) instead of panicking: check
_m.config.driver type-assertion against txDriver, and if not ok return a
descriptive error (e.g., "ent: BuildTraceEntry is not a transactional entity")
rather than calling panic; update all callers of BuildTraceEntry.Unwrap to
handle the (entity, error) return and propagate or handle the error accordingly;
ensure references to txDriver and _m.config.driver remain to locate the check to
modify.
| 2. Run `go generate ./ent/...`. | ||
| 3. Run `go run ./cmd/generate-migrations --name=add_build_trace_entries` to emit per-dialect SQL. | ||
| 4. Deploy: `ncps migrate up` applies migrations automatically at startup. No data backfill needed (new tables). |
There was a problem hiding this comment.
Use the repo-standard Ent/Atlas generation commands in the migration plan.
These steps currently document non-canonical commands. Please switch to the project-standard workflow (task ent:generate and task migrations:gen NAME=<name> or task migrations:sql NAME=<name>) to keep implementation guidance consistent.
As per coding guidelines "ent/**/*.go: ... commit the generated Ent client in ent/ directory after running task ent:generate" and "migrations/**/*.sql: ... generate per-dialect Atlas migrations using task migrations:gen NAME=<name> or ... task migrations:sql NAME=<name>".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@openspec/changes/archive/2026-05-25-build-trace-support/design.md` around
lines 111 - 113, Replace the non-standard generation commands in the migration
plan (the lines that run `go generate ./ent/...`, `go run
./cmd/generate-migrations --name=add_build_trace_entries`, and the deploy note
about `ncps migrate up`) with the repo-standard tasks: run `task ent:generate`
to produce and commit the Ent client under ent/, and generate per-dialect Atlas
migrations using either `task migrations:gen NAME=add_build_trace_entries` (to
create migration directories) or `task migrations:sql
NAME=add_build_trace_entries` (to emit SQL), leaving the deploy note unchanged
about migrations being applied at startup.
| b, err := json.Marshal(entry) | ||
| if err != nil { | ||
| panic(err) | ||
| } |
There was a problem hiding this comment.
Avoid panic in test helper; return an error instead.
Please avoid panic(err) here and propagate an error so callers can assert with test helpers.
Suggested refactor
- validBody := func(extraSig *cache.BuildTraceSig) string {
+ validBody := func(extraSig *cache.BuildTraceSig) (string, error) {
sigs := []cache.BuildTraceSig{}
if extraSig != nil {
sigs = append(sigs, *extraSig)
}
@@
- b, err := json.Marshal(entry)
- if err != nil {
- panic(err)
- }
-
- return string(b)
+ b, err := json.Marshal(entry)
+ if err != nil {
+ return "", err
+ }
+ return string(b), nil
}As per coding guidelines: “Do not use panic outside of the main function — always return errors instead”.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@pkg/cache/build_trace_test.go` around lines 123 - 126, Replace the panic(err)
in the json.Marshal branch with proper error propagation: have the helper that
contains the json.Marshal(entry) return (or forward) the error (or a wrapped
error) instead of calling panic, update its signature (e.g., return ([]byte,
error)) and update any callers in tests to handle the error (use
require.NoError/require.Equal/etc. or t.Fatal on error). Ensure you reference
the json.Marshal(entry) result variable b and propagate or wrap err so callers
can assert on failures rather than the test helper panicking.
| b, err := json.Marshal(entry) | ||
| if err != nil { | ||
| panic(err) | ||
| } |
There was a problem hiding this comment.
Replace panic in btValidBody with error propagation.
Use (string, error) and assert in callers instead of panicking in test helpers.
Suggested refactor
-func btValidBody() string {
+func btValidBody() (string, error) {
entry := map[string]any{
@@
b, err := json.Marshal(entry)
if err != nil {
- panic(err)
+ return "", err
}
-
- return string(b)
+ return string(b), nil
}As per coding guidelines: “Do not use panic outside of the main function — always return errors instead”.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| b, err := json.Marshal(entry) | |
| if err != nil { | |
| panic(err) | |
| } | |
| func btValidBody() (string, error) { | |
| entry := map[string]any{ | |
| // ... entry fields ... | |
| } | |
| b, err := json.Marshal(entry) | |
| if err != nil { | |
| return "", err | |
| } | |
| return string(b), nil | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@pkg/server/build_trace_test.go` around lines 39 - 42, The helper btValidBody
should not panic on json.Marshal failure; change btValidBody to return (string,
error) instead of string and propagate the error from json.Marshal. Update all
callers (tests that call btValidBody) to handle the returned error and
assert/fail the test on error rather than relying on a panic; ensure the helper
returns the marshaled string on success and the original error on failure so
callers can check it.
c76e0b5 to
8101033
Compare
7021a0b to
f7a3f55
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
pkg/cache/build_trace.go (1)
153-157:⚠️ Potential issue | 🟠 Major | ⚡ Quick winDetect over-limit bodies instead of silently truncating.
At Line 153, the current
LimitReadercap can drop trailing bytes without returning a size error. Please readmax+1and reject oversized requests explicitly withErrBadRequest.Suggested patch
+const maxBuildTraceBodyBytes = 1024 * 1024 // 1 MiB + func (c *Cache) PutBuildTrace(ctx context.Context, drvName, outputName string, r io.Reader) error { @@ - raw, err := io.ReadAll(io.LimitReader(r, 1024*1024)) + raw, err := io.ReadAll(io.LimitReader(r, maxBuildTraceBodyBytes+1)) if err != nil { return fmt.Errorf("read body: %w", err) } + if len(raw) > maxBuildTraceBodyBytes { + return fmt.Errorf("%w: request body too large", ErrBadRequest) + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@pkg/cache/build_trace.go` around lines 153 - 157, The code currently uses io.LimitReader with a 1MB cap and silently truncates bodies; change the read to call io.ReadAll(io.LimitReader(r, maxSize+1)) (use the existing 1024*1024 as maxSize constant or define one) so you can detect when the returned raw length > maxSize and in that case return ErrBadRequest instead of proceeding; keep the existing error wrapping (fmt.Errorf("read body: %w", err)) for read errors and reference the variables/funcs LimitReader, io.ReadAll, raw, r, and ErrBadRequest when making this change.openspec/changes/archive/2026-05-25-build-trace-support/design.md (1)
111-113:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winUse repo-standard task commands in the migration plan.
The documented commands don't match the project's standard workflow. Replace:
- Line 111:
go generate ./ent/...→task ent:generate- Line 112:
go run ./cmd/generate-migrations --name=add_build_trace_entries→task migrations:gen NAME=add_build_trace_entriesThis keeps implementation guidance consistent with the established conventions.
📝 Proposed fix
-2. Run `go generate ./ent/...`. -3. Run `go run ./cmd/generate-migrations --name=add_build_trace_entries` to emit per-dialect SQL. +2. Run `task ent:generate` to generate and commit the Ent client in `ent/`. +3. Run `task migrations:gen NAME=add_build_trace_entries` to emit per-dialect Atlas migrations.As per coding guidelines: "
ent/**/*.go: ... commit the generated Ent client inent/directory after runningtask ent:generate" and "migrations/**/*.sql: ... generate per-dialect Atlas migrations usingtask migrations:gen NAME=<name>or ...task migrations:sql NAME=<name>".🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openspec/changes/archive/2026-05-25-build-trace-support/design.md` around lines 111 - 113, Update the migration plan commands to use the repo-standard task wrappers: replace the literal `go generate ./ent/...` invocation with `task ent:generate` and replace `go run ./cmd/generate-migrations --name=add_build_trace_entries` with `task migrations:gen NAME=add_build_trace_entries`, ensuring generated Ent client and per-dialect Atlas migrations follow the project's established workflow.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@openspec/specs/data-model/spec.md`:
- Around line 299-300: The spec's "updated_at" column definition is inconsistent
with the generated schema: update the spec entry for the "updated_at" column to
match the migrations (or vice-versa). Specifically, locate the "updated_at"
column declaration in spec.md and change its declaration to the same
nullability/default used in your migrations—e.g., if migrations have a nullable
column with no default, use `"updated_at" TIMESTAMP NULL` (or `"updated_at"
TIMESTAMP NULL DEFAULT NULL`); if migrations actually set NOT NULL DEFAULT
CURRENT_TIMESTAMP, update migrations to match the spec instead. Ensure the
symbol "updated_at" is adjusted consistently across the spec and
schema/migrations so both definitions are identical.
---
Duplicate comments:
In `@openspec/changes/archive/2026-05-25-build-trace-support/design.md`:
- Around line 111-113: Update the migration plan commands to use the
repo-standard task wrappers: replace the literal `go generate ./ent/...`
invocation with `task ent:generate` and replace `go run
./cmd/generate-migrations --name=add_build_trace_entries` with `task
migrations:gen NAME=add_build_trace_entries`, ensuring generated Ent client and
per-dialect Atlas migrations follow the project's established workflow.
In `@pkg/cache/build_trace.go`:
- Around line 153-157: The code currently uses io.LimitReader with a 1MB cap and
silently truncates bodies; change the read to call io.ReadAll(io.LimitReader(r,
maxSize+1)) (use the existing 1024*1024 as maxSize constant or define one) so
you can detect when the returned raw length > maxSize and in that case return
ErrBadRequest instead of proceeding; keep the existing error wrapping
(fmt.Errorf("read body: %w", err)) for read errors and reference the
variables/funcs LimitReader, io.ReadAll, raw, r, and ErrBadRequest when making
this change.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: a6b58ddf-8507-4b6d-96ee-56dcb3d689d6
⛔ Files ignored due to path filters (3)
migrations/mysql/atlas.sumis excluded by!**/*.summigrations/postgres/atlas.sumis excluded by!**/*.summigrations/sqlite/atlas.sumis excluded by!**/*.sum
📒 Files selected for processing (43)
ent/buildtraceentry.goent/buildtraceentry/buildtraceentry.goent/buildtraceentry/where.goent/buildtraceentry_create.goent/buildtraceentry_delete.goent/buildtraceentry_query.goent/buildtraceentry_update.goent/buildtracesignature.goent/buildtracesignature/buildtracesignature.goent/buildtracesignature/where.goent/buildtracesignature_create.goent/buildtracesignature_delete.goent/buildtracesignature_query.goent/buildtracesignature_update.goent/client.goent/ent.goent/hook/hook.goent/migrate/schema.goent/mutation.goent/predicate/predicate.goent/runtime.goent/schema/build_trace_entry.goent/schema/build_trace_signature.goent/tx.gomigrations/mysql/20260525175108_add_build_trace_entries.sqlmigrations/postgres/20260525175108_add_build_trace_entries.sqlmigrations/sqlite/20260525175108_add_build_trace_entries.sqlopenspec/changes/archive/2026-05-25-build-trace-support/.openspec.yamlopenspec/changes/archive/2026-05-25-build-trace-support/design.mdopenspec/changes/archive/2026-05-25-build-trace-support/proposal.mdopenspec/changes/archive/2026-05-25-build-trace-support/specs/api-surface/spec.mdopenspec/changes/archive/2026-05-25-build-trace-support/specs/build-trace/spec.mdopenspec/changes/archive/2026-05-25-build-trace-support/specs/data-model/spec.mdopenspec/changes/archive/2026-05-25-build-trace-support/tasks.mdopenspec/specs/api-surface/spec.mdopenspec/specs/build-trace/spec.mdopenspec/specs/data-model/spec.mdpkg/cache/build_trace.gopkg/cache/build_trace_test.gopkg/cache/cache_test.gopkg/cache/export_test.gopkg/server/build_trace_test.gopkg/server/server.go
✅ Files skipped from review due to trivial changes (9)
- openspec/changes/archive/2026-05-25-build-trace-support/.openspec.yaml
- openspec/changes/archive/2026-05-25-build-trace-support/specs/data-model/spec.md
- openspec/changes/archive/2026-05-25-build-trace-support/specs/api-surface/spec.md
- ent/runtime.go
- pkg/cache/cache_test.go
- openspec/specs/api-surface/spec.md
- openspec/changes/archive/2026-05-25-build-trace-support/specs/build-trace/spec.md
- openspec/changes/archive/2026-05-25-build-trace-support/tasks.md
- ent/client.go
| "updated_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP | ||
| ); |
There was a problem hiding this comment.
updated_at nullability/default is inconsistent with actual schema.
At Line 299, the spec marks updated_at as NOT NULL DEFAULT CURRENT_TIMESTAMP, but generated schema/migrations define it nullable without that default. Please align this section to avoid schema-parity confusion.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@openspec/specs/data-model/spec.md` around lines 299 - 300, The spec's
"updated_at" column definition is inconsistent with the generated schema: update
the spec entry for the "updated_at" column to match the migrations (or
vice-versa). Specifically, locate the "updated_at" column declaration in spec.md
and change its declaration to the same nullability/default used in your
migrations—e.g., if migrations have a nullable column with no default, use
`"updated_at" TIMESTAMP NULL` (or `"updated_at" TIMESTAMP NULL DEFAULT NULL`);
if migrations actually set NOT NULL DEFAULT CURRENT_TIMESTAMP, update migrations
to match the spec instead. Ensure the symbol "updated_at" is adjusted
consistently across the spec and schema/migrations so both definitions are
identical.
nix copy sends PUT /upload/build-trace-v2/{drvName}/{outputName}
when uploading CA derivation realisation data. Previously this
returned 404 and caused nix copy to fail. This change fully
implements the endpoint so ncps stores and serves build traces
rather than rejecting or ignoring them.
How:
- Add two Ent schemas (BuildTraceEntry, BuildTraceSignature) with
a unique index on (drv_path, output_name) and CASCADE on delete.
- Emit per-dialect Atlas migrations for SQLite, PostgreSQL, MySQL.
- Implement HasBuildTrace, GetBuildTrace, PutBuildTrace on *Cache:
- PutBuildTrace validates URL/body key consistency, computes the
fingerprint (JSON minus signatures), appends ncps's Ed25519
signature, then upserts the entry and replaces all signatures.
- GetBuildTrace reconstructs the full JSON from DB columns so
ncps's signature is always present in the response.
- Register HEAD, GET /build-trace-v2/{drvName}/{outputName} in
registerRoutes and PUT under the /upload sub-router.
- Strip the .doi suffix from outputName in server handlers (nix
appends it for cache-entry content-addressable lookups).
- Add cache-layer unit tests (fingerprint, PUT/GET/HEAD/errors)
and server handler tests covering all response codes.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
io.ReadAll on an unbounded reader is a DoS vector — a caller could stream an arbitrarily large payload and exhaust server memory. Build trace entries are small JSON blobs, so 1 MiB is a generous ceiling that will never be hit in practice. Addresses: PRRT_kwDONV6tZs6EnUuY
Validate the full drvPath instead of just the basename, so a body
carrying /wrong/prefix/correct-name.drv is rejected with a 400 rather
than being accepted and then misfiring on the post-upsert re-query.
Removes the now-unused strings import.
Also fix doc inconsistencies flagged in review:
- Add language tag to fenced block in design.md (MD040)
- Align SQL examples to use VARCHAR(255) for the signature column,
matching the actual MySQL migration and Ent's field.String() mapping
Addresses: PRRT_kwDONV6tZs6EnpaA, PRRT_kwDONV6tZs6EnpZ1,
PRRT_kwDONV6tZs6EnpZ5, PRRT_kwDONV6tZs6EnpZ8
f7a3f55 to
7e8c7e3
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (1)
openspec/changes/archive/2026-05-25-build-trace-support/design.md (1)
111-112:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winUpdate migration commands to match repository standards.
These steps document non-canonical generation commands. The coding guidelines specify using
task ent:generateto generate the Ent client andtask migrations:gen NAME=add_build_trace_entriesto generate per-dialect Atlas migrations.As per coding guidelines: "
ent/**/*.go: commit the generated Ent client inent/directory after runningtask ent:generate" and "migrations/**/*.sql: Use Atlas-driven per-dialect migration generator viatask migrations:gen NAME=<name>".📝 Proposed fix
-2. Run `go generate ./ent/...`. -3. Run `go run ./cmd/generate-migrations --name=add_build_trace_entries` to emit per-dialect SQL. +2. Run `task ent:generate` to generate and commit the Ent client. +3. Run `task migrations:gen NAME=add_build_trace_entries` to emit per-dialect SQL migrations.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openspec/changes/archive/2026-05-25-build-trace-support/design.md` around lines 111 - 112, Replace the non-standard generation commands with the repository-standard tasks: change the Ent generation step to run task ent:generate (instead of go generate ./ent/...) and change the per-dialect migration generation step to task migrations:gen NAME=add_build_trace_entries (instead of go run ./cmd/generate-migrations --name=add_build_trace_entries); update the numbered steps that currently mention go generate and go run to use task ent:generate and task migrations:gen NAME=add_build_trace_entries respectively so the docs match the coding guidelines.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@ent/buildtracesignature_update.go`:
- Around line 94-114: The generated panic helpers SaveX and ExecX in
BuildTraceSignatureUpdate (methods SaveX, ExecX) violate the non-main panic
policy; remove or change them so they do not call panic(err). Update the Ent
generation/templates (or a post-generation cleanup) to either: 1) drop emitting
SaveX/ExecX entirely, or 2) change SaveX to propagate the error (e.g., return
(int, error) like Save) and change ExecX to return error (or remove it and rely
on Exec), ensuring no panic calls remain in BuildTraceSignatureUpdate.SaveX or
BuildTraceSignatureUpdate.ExecX (and the other similar helpers noted at lines
~277-297).
In `@openspec/specs/data-model/spec.md`:
- Around line 291-303: Update the example SQL for the table
"build_trace_entries" so its column types match the generated MySQL migration:
change "drv_path" and "out_path" from TEXT to VARCHAR(255), and change
"raw_json" from TEXT to LONGTEXT; keep the "id", timestamps, and the unique
index "idx_build_trace_entries_drv_path_output_name" unchanged.
In `@pkg/cache/build_trace.go`:
- Around line 239-250: The code removes existing self-signatures by comparing
Signature.KeyName to c.hostName but appends the new buildTraceSig using
sig.Name, causing mismatched keys and duplicate self-signatures; change the
appended signature to use the same key name used for filtering (e.g., set
KeyName to c.hostName or derive a single selfSigName variable) so the new
signature replaces existing ones (update the buildTraceSig creation where
KeyName is currently set to sig.Name and ensure filtering and append use the
identical identifier).
---
Duplicate comments:
In `@openspec/changes/archive/2026-05-25-build-trace-support/design.md`:
- Around line 111-112: Replace the non-standard generation commands with the
repository-standard tasks: change the Ent generation step to run task
ent:generate (instead of go generate ./ent/...) and change the per-dialect
migration generation step to task migrations:gen NAME=add_build_trace_entries
(instead of go run ./cmd/generate-migrations --name=add_build_trace_entries);
update the numbered steps that currently mention go generate and go run to use
task ent:generate and task migrations:gen NAME=add_build_trace_entries
respectively so the docs match the coding guidelines.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 4f1ed987-d99d-43fe-ace0-a4c690d28bba
⛔ Files ignored due to path filters (3)
migrations/mysql/atlas.sumis excluded by!**/*.summigrations/postgres/atlas.sumis excluded by!**/*.summigrations/sqlite/atlas.sumis excluded by!**/*.sum
📒 Files selected for processing (43)
ent/buildtraceentry.goent/buildtraceentry/buildtraceentry.goent/buildtraceentry/where.goent/buildtraceentry_create.goent/buildtraceentry_delete.goent/buildtraceentry_query.goent/buildtraceentry_update.goent/buildtracesignature.goent/buildtracesignature/buildtracesignature.goent/buildtracesignature/where.goent/buildtracesignature_create.goent/buildtracesignature_delete.goent/buildtracesignature_query.goent/buildtracesignature_update.goent/client.goent/ent.goent/hook/hook.goent/migrate/schema.goent/mutation.goent/predicate/predicate.goent/runtime.goent/schema/build_trace_entry.goent/schema/build_trace_signature.goent/tx.gomigrations/mysql/20260525175108_add_build_trace_entries.sqlmigrations/postgres/20260525175108_add_build_trace_entries.sqlmigrations/sqlite/20260525175108_add_build_trace_entries.sqlopenspec/changes/archive/2026-05-25-build-trace-support/.openspec.yamlopenspec/changes/archive/2026-05-25-build-trace-support/design.mdopenspec/changes/archive/2026-05-25-build-trace-support/proposal.mdopenspec/changes/archive/2026-05-25-build-trace-support/specs/api-surface/spec.mdopenspec/changes/archive/2026-05-25-build-trace-support/specs/build-trace/spec.mdopenspec/changes/archive/2026-05-25-build-trace-support/specs/data-model/spec.mdopenspec/changes/archive/2026-05-25-build-trace-support/tasks.mdopenspec/specs/api-surface/spec.mdopenspec/specs/build-trace/spec.mdopenspec/specs/data-model/spec.mdpkg/cache/build_trace.gopkg/cache/build_trace_test.gopkg/cache/cache_test.gopkg/cache/export_test.gopkg/server/build_trace_test.gopkg/server/server.go
✅ Files skipped from review due to trivial changes (8)
- pkg/cache/cache_test.go
- openspec/changes/archive/2026-05-25-build-trace-support/specs/api-surface/spec.md
- ent/ent.go
- openspec/specs/api-surface/spec.md
- openspec/specs/build-trace/spec.md
- openspec/changes/archive/2026-05-25-build-trace-support/tasks.md
- ent/mutation.go
- openspec/changes/archive/2026-05-25-build-trace-support/specs/data-model/spec.md
| // SaveX is like Save, but panics if an error occurs. | ||
| func (_u *BuildTraceSignatureUpdate) SaveX(ctx context.Context) int { | ||
| affected, err := _u.Save(ctx) | ||
| if err != nil { | ||
| panic(err) | ||
| } | ||
| return affected | ||
| } | ||
|
|
||
| // Exec executes the query. | ||
| func (_u *BuildTraceSignatureUpdate) Exec(ctx context.Context) error { | ||
| _, err := _u.Save(ctx) | ||
| return err | ||
| } | ||
|
|
||
| // ExecX is like Exec, but panics if an error occurs. | ||
| func (_u *BuildTraceSignatureUpdate) ExecX(ctx context.Context) { | ||
| if err := _u.Exec(ctx); err != nil { | ||
| panic(err) | ||
| } | ||
| } |
There was a problem hiding this comment.
Generated *X panic helpers violate the repo’s non-main panic policy.
SaveX/ExecX in this non-main package call panic(err). Please adjust Ent generation/templates (or post-generation checks) so these panic helpers are not emitted in committed production code.
As per coding guidelines, "!(cmd/*/main.go|main.go)**/*.go: Do not use panic outside of main. Return errors instead."
Also applies to: 277-297
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@ent/buildtracesignature_update.go` around lines 94 - 114, The generated panic
helpers SaveX and ExecX in BuildTraceSignatureUpdate (methods SaveX, ExecX)
violate the non-main panic policy; remove or change them so they do not call
panic(err). Update the Ent generation/templates (or a post-generation cleanup)
to either: 1) drop emitting SaveX/ExecX entirely, or 2) change SaveX to
propagate the error (e.g., return (int, error) like Save) and change ExecX to
return error (or remove it and rely on Exec), ensuring no panic calls remain in
BuildTraceSignatureUpdate.SaveX or BuildTraceSignatureUpdate.ExecX (and the
other similar helpers noted at lines ~277-297).
| ```sql | ||
| CREATE TABLE "build_trace_entries" ( | ||
| "id" BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, | ||
| "drv_path" TEXT NOT NULL, | ||
| "output_name" VARCHAR(255) NOT NULL, | ||
| "out_path" TEXT NOT NULL, | ||
| "raw_json" TEXT NOT NULL, | ||
| "created_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, | ||
| "updated_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP | ||
| ); | ||
| CREATE UNIQUE INDEX "idx_build_trace_entries_drv_path_output_name" | ||
| ON "build_trace_entries" ("drv_path", "output_name"); | ||
| ``` |
There was a problem hiding this comment.
Align build_trace_entries column types with the generated MySQL migration.
This SQL example uses TEXT for drv_path, out_path, and raw_json, but the migration defines VARCHAR(255), VARCHAR(255), and LONGTEXT. Given the schema-parity requirement in this spec, this is misleading.
💡 Suggested doc fix
CREATE TABLE "build_trace_entries" (
"id" BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
- "drv_path" TEXT NOT NULL,
+ "drv_path" VARCHAR(255) NOT NULL,
"output_name" VARCHAR(255) NOT NULL,
- "out_path" TEXT NOT NULL,
- "raw_json" TEXT NOT NULL,
+ "out_path" VARCHAR(255) NOT NULL,
+ "raw_json" LONGTEXT NOT NULL,
"created_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| ```sql | |
| CREATE TABLE "build_trace_entries" ( | |
| "id" BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, | |
| "drv_path" TEXT NOT NULL, | |
| "output_name" VARCHAR(255) NOT NULL, | |
| "out_path" TEXT NOT NULL, | |
| "raw_json" TEXT NOT NULL, | |
| "created_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, | |
| "updated_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP | |
| ); | |
| CREATE UNIQUE INDEX "idx_build_trace_entries_drv_path_output_name" | |
| ON "build_trace_entries" ("drv_path", "output_name"); | |
| ``` |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@openspec/specs/data-model/spec.md` around lines 291 - 303, Update the example
SQL for the table "build_trace_entries" so its column types match the generated
MySQL migration: change "drv_path" and "out_path" from TEXT to VARCHAR(255), and
change "raw_json" from TEXT to LONGTEXT; keep the "id", timestamps, and the
unique index "idx_build_trace_entries_drv_path_output_name" unchanged.
| // Remove any existing signature from ncps's own key, then append the new one. | ||
| sigs := make([]buildTraceSig, 0, len(entry.Value.Signatures)+1) | ||
| for _, s := range entry.Value.Signatures { | ||
| if s.KeyName != c.hostName { | ||
| sigs = append(sigs, s) | ||
| } | ||
| } | ||
|
|
||
| sigs = append(sigs, buildTraceSig{ | ||
| KeyName: sig.Name, | ||
| Sig: base64.StdEncoding.EncodeToString(sig.Data), | ||
| }) |
There was a problem hiding this comment.
Use a consistent self-signature key when replacing existing signatures.
The filter removes entries by c.hostName but the new signature is appended with sig.Name. If those differ, old self-signatures are retained and duplicate self-signatures can be inserted.
Suggested fix
- // Remove any existing signature from ncps's own key, then append the new one.
- sigs := make([]buildTraceSig, 0, len(entry.Value.Signatures)+1)
- for _, s := range entry.Value.Signatures {
- if s.KeyName != c.hostName {
- sigs = append(sigs, s)
- }
- }
+ // Remove any existing signature from ncps's own key(s), then append the new one.
+ ownKeyNames := map[string]struct{}{
+ sig.Name: {},
+ c.hostName: {},
+ }
+ sigs := make([]buildTraceSig, 0, len(entry.Value.Signatures)+1)
+ for _, s := range entry.Value.Signatures {
+ if _, isOwn := ownKeyNames[s.KeyName]; !isOwn {
+ sigs = append(sigs, s)
+ }
+ }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@pkg/cache/build_trace.go` around lines 239 - 250, The code removes existing
self-signatures by comparing Signature.KeyName to c.hostName but appends the new
buildTraceSig using sig.Name, causing mismatched keys and duplicate
self-signatures; change the appended signature to use the same key name used for
filtering (e.g., set KeyName to c.hostName or derive a single selfSigName
variable) so the new signature replaces existing ones (update the buildTraceSig
creation where KeyName is currently set to sig.Name and ensure filtering and
append use the identical identifier).
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #1272 +/- ##
============================
============================
☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
Summary
Closes #1152
nix copyunconditionally PUTs build trace entries to/upload/build-trace-v2/{drvName}/{outputName}.doiand GETs them back at/build-trace-v2/{drvName}/{outputName}.doiwhen working with CA derivations. Previously ncps had no routes for these paths and returned 404, causingnix copyto exit non-zero even when the NAR upload succeeded.BuildTraceEntry,BuildTraceSignature) mirroring the existing narinfos/narinfo_signatures pattern, with a unique index on(drv_path, output_name)andON DELETE CASCADEon signaturesHasBuildTrace,GetBuildTrace,PutBuildTraceon*Cache: validates URL/body key consistency, computes the fingerprint (JSON minus signatures per nix'srealisation.cc), appends ncps's Ed25519 signature, upserts the entry, and replaces all signatures atomicallyHEADandGET /build-trace-v2/{drvName}/{outputName}inregisterRoutesandPUTunder the/uploadsub-router, gated byputPermitted.doisuffix fromoutputNamein both handlers (nix appends it for content-addressable lookups)raw_jsonof the upload body as a forward-compatibility safety valve if nix's experimental format changesTest plan
buildTraceFingerprint(3 subtests: standard entry, multiple sigs stripped, empty sigs identical)runCacheTestSuite(SQLite + PostgreSQL + MySQL):HasBuildTrace,GetBuildTrace(not found, ncps sig appended),PutBuildTrace(success, duplicate upsert, malformed JSON, URL/body mismatch).doisuffix strippinggolangci-lint run --fix— 0 issuesnix fmt— 0 changesgo run ./cmd/ent-lint— all A1/A2/A4 checks passgo run ./cmd/atlas-sum-check— all three dialect sums match🤖 Generated with Claude Code