Skip to content

fix(ent): stop sqlite phantom narinfos/nar_files rebuild - #1339

Merged
kalbasit merged 2 commits into
mainfrom
user/wnasreddine/fix-issue-1328
Jun 7, 2026
Merged

kalbasit merged 2 commits into
mainfrom
user/wnasreddine/fix-issue-1328

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 7, 2026

Copy link
Copy Markdown
Owner

Summary

Fixes #1328.

task migrations:gen rebuilt the unrelated narinfos and nar_files
tables on every new sqlite migration, forcing each migration to be
hand-trimmed and risking a committed destructive table swap.

Root cause (traced via Ent's WithDiffHook): last_accessed_at
declared its DB default with entsql.Annotation{DefaultExpr: "CURRENT_TIMESTAMP"}, which Ent emits as a parenthesized Atlas
RawExpr. Atlas's sqlite inspector strips the parens on readback, so
desired ((CURRENT_TIMESTAMP)) and inspected (CURRENT_TIMESTAMP)
never compare equal — a perpetual ModifyColumn (ChangeDefault) that
sqlite expresses as a full table rebuild. created_at was immune
because the Timestamps mixin already uses the string form
entsql.Default("CURRENT_TIMESTAMP"). The issue's suggested corrective
migration would not have worked: the stored DDL is already
atlas-canonical; the mismatch is in Ent's desired-schema representation.

What changed

  • ent/schema/{narinfo,nar_file}.go: last_accessed_at now uses
    entsql.Default("CURRENT_TIMESTAMP"); regenerated the Ent client.
    Emitted DDL (DEFAULT (CURRENT_TIMESTAMP)) is unchanged, so no
    migration is needed
    and existing databases are untouched.
  • cmd/ent-lint: new invariant A6 rejecting the DefaultExpr
    form, to prevent regression (wired into nix flake check).
  • cmd/generate-migrations: TestSQLiteNoPhantomDiff pinning the
    empty-diff contract (RED before the fix, GREEN after).
  • .claude/rules/ent-migrations.md: documented the convention (§6).
  • Synced the database-migrations and ent-schema-lint specs.

Test plan

  • task fmt, task lint (0 issues), task test (29 pkgs, 0 fail)
  • task ent:check exits 0 (A6 PASS on all schemas; ent drift clean)
  • task migrations:gen produces no spurious migration across
    sqlite, postgres, and mysql (verified against live dev DBs)
  • git status shows zero changed files under migrations/

`task migrations:gen` rebuilt the unrelated narinfos and nar_files
tables on every new sqlite migration (issue #1328), forcing every
migration to be hand-trimmed and risking a committed destructive
table swap.

Root cause (traced via Ent's WithDiffHook): last_accessed_at declared
its DB default with entsql.Annotation{DefaultExpr: "CURRENT_TIMESTAMP"},
which Ent emits as a parenthesized Atlas RawExpr. Atlas's sqlite
inspector strips the parens on readback, so desired ((CURRENT_TIMESTAMP))
and inspected (CURRENT_TIMESTAMP) never compare equal -> a perpetual
ModifyColumn (ChangeDefault) that sqlite expresses as a full table
rebuild. created_at was immune because the Timestamps mixin uses the
string form entsql.Default("CURRENT_TIMESTAMP").

Fix: switch last_accessed_at in narinfo.go and nar_file.go to
entsql.Default("CURRENT_TIMESTAMP") and regenerate. The on-disk DDL
(DEFAULT (CURRENT_TIMESTAMP)) is unchanged, so no migration is needed;
the issue's suggested corrective migration would not have worked.

Add ent-lint invariant A6 forbidding the DefaultExpr form to prevent
regression, a generator test (TestSQLiteNoPhantomDiff) pinning the
empty-diff contract, and rule section 6 in ent-migrations.md.
Verified clean across sqlite, postgres, and mysql.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit

kalbasit commented Jun 7, 2026 •

Copy link
Copy Markdown
Owner Author

This change is part of the following stack:

Change managed by git-spice.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. bug Something isn't working go Pull requests that update go code labels Jun 7, 2026
@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 960ec78c-f391-40a7-ad83-4f6bd0ddbcfb

📥 Commits

Reviewing files that changed from the base of the PR and between 5770238 and ea2c97e.

📒 Files selected for processing (3)
  • cmd/ent-lint/main.go
  • cmd/ent-lint/main_test.go
  • cmd/ent-lint/testdata/a6_bad_pointer/schema.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/ent-lint/main.go

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes

    • Resolved SQLite "phantom diff" that caused spurious migration diffs for CURRENT_TIMESTAMP defaults.
  • New Features

    • Added a lint rule (A6) that rejects the problematic timestamp-default annotation and recommends the supported form.
  • Tests

    • Added tests covering the lint rule (good/bad fixtures) and a SQLite no-op migration verification.
  • Documentation

    • Updated migration rules, design, and specs with CURRENT_TIMESTAMP default guidance.

Walkthrough

Replace deprecated entsql.Annotation{DefaultExpr: "CURRENT_TIMESTAMP"} with entsql.Default("CURRENT_TIMESTAMP") in Ent schemas, add lint invariant A6 to reject the old form, add a generator-level SQLite no-op test, and update docs/specs/tasks to record the change and verification steps.

Changes

SQLite Phantom Diff Fix

Layer / File(s) Summary
A6 lint rule implementation
cmd/ent-lint/main.go, cmd/ent-lint/main_test.go, cmd/ent-lint/testdata/a6_*/*
Static analysis rule A6 detects and rejects entsql.Annotation{DefaultExpr: "CURRENT_TIMESTAMP"} (including pointer form), uses centralized entsqlPkg/annotationsMethod constants, and provides passing/failing fixtures and strengthened tests.
Update Ent schema defaults
ent/schema/nar_file.go, ent/schema/narinfo.go, ent/migrate/schema.go
Change last_accessed_at field defaults from inline entsql.Annotation{DefaultExpr: ...} to entsql.Default("CURRENT_TIMESTAMP"); generated migrate schema column defaults updated from schema.Expr("CURRENT_TIMESTAMP") to plain "CURRENT_TIMESTAMP".
Phantom diff validation
cmd/generate-migrations/main_test.go
New TestSQLiteNoPhantomDiff and copyDir helper verify SQLite migration generation produces no spurious table rebuilds or extra .sql files when schema is unchanged.
Documentation and specifications
.claude/rules/ent-migrations.md, openspec/changes/archive/..., openspec/specs/...
Design, proposal, task log, and spec updates document the root cause, schema fix, A6 lint guard, verification workflow, and the convention to prefer entsql.Default("CURRENT_TIMESTAMP").

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • kalbasit/ncps#1185: Related to the generate-migrations test infrastructure used by the new validation test.
  • kalbasit/ncps#1196: Introduced the entsql.Annotation{DefaultExpr: "CURRENT_TIMESTAMP"} form that this PR replaces and now lints against.
  • kalbasit/ncps#1187: Related tooling changes that affected dialect-skipping behavior used by the new test.

Suggested labels

size:M, merge-stack

Poem

🐰 A phantom diff that hopped in the night,
Two ways to say CURRENT_TIMESTAMP — which is right?
I swapped the old form for the one that will last,
Lint watches the burrow so ghosts don't come back fast.
Now SQLite sleeps sound, no rebuilds at last.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 61.11% 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 accurately summarizes the main change: fixing SQLite phantom table rebuilds for narinfos/nar_files by correcting the CURRENT_TIMESTAMP default declaration.
Description check ✅ Passed The description comprehensively explains the issue, root cause, changes made, and verification performed, directly relating to the changeset.
Linked Issues check ✅ Passed The PR fully addresses issue #1328: it identifies and fixes the root cause (entsql.Annotation{DefaultExpr} mismatch), implements the suggested diagnostic approach (Atlas verbose diffs), adds regression prevention (A6 lint invariant), and verifies the fix works across all DB dialects.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing the SQLite phantom diff issue: schema corrections, lint invariant A6, test coverage, documentation, and specifications. No unrelated modifications detected.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request resolves a perpetual phantom table rebuild issue in SQLite migrations (GitHub issue #1328) by updating the last_accessed_at column default declaration from entsql.Annotation{DefaultExpr: "CURRENT_TIMESTAMP"} to entsql.Default("CURRENT_TIMESTAMP") in the narinfo and nar_file schemas. It also introduces a static lint check (invariant A6) in cmd/ent-lint to prevent future regressions, along with corresponding tests and documentation. The review feedback suggests improving the robustness of the AST parser in cmd/ent-lint to handle pointer composite literals (e.g., &entsql.Annotation{...}) by unwrapping the unary address-of operator.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread cmd/ent-lint/main.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
.claude/rules/ent-migrations.md (1)

3-5: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Update the invariant count to six.

The document now contains six codegen invariants (1-6), but line 4 still refers to "the four codegen invariants below." Line 23 refers to "These five patterns."

📝 Proposed fix
 Whenever changes are made to the Ent schema (`apps/uar/ent/*/schema/*.go`), the
-versioned migrations must be regenerated and the four codegen invariants below
+versioned migrations must be regenerated and the six codegen invariants below
 MUST be honoured.

And:

 ## Codegen invariants
 
-These five patterns are silently miscompiled by Ent or represent latent security
+These six patterns are silently miscompiled by Ent or represent latent security
 risks. They are enforced by `task uar:ent:lint` (which runs as part of
🤖 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 @.claude/rules/ent-migrations.md around lines 3 - 5, Update the textual
references to match the new count of invariants: change "the four codegen
invariants below" to "the six codegen invariants below" and change "These five
patterns" to "These six patterns"; search the same document
(.claude/rules/ent-migrations.md) for any other occurrences of the numbers
referring to invariants/patterns and update them to six so the header and inline
references are consistent with the six listed invariants.
🧹 Nitpick comments (1)
openspec/changes/archive/2026-06-06-fix-sqlite-default-expr-phantom-diff/design.md (1)

7-12: 💤 Low value

Add language identifier to fenced code block.

The code block showing Atlas diff output should specify a language identifier for proper syntax highlighting and tooling support.

📝 Suggested improvement
-```
+```text
 ModifyTable narinfos:  ModifyColumn last_accessed_at  (ChangeKind=64 = ChangeDefault)
 ModifyTable nar_files: ModifyColumn last_accessed_at  (ChangeKind=64 = ChangeDefault)
   current  (inspected from stored DDL): RawExpr{"CURRENT_TIMESTAMP"}
   desired  (Ent):                       RawExpr{"(CURRENT_TIMESTAMP)"}
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

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-06-06-fix-sqlite-default-expr-phantom-diff/design.md
around lines 7 - 12, The fenced code block showing the Atlas diff (the block
containing "ModifyTable narinfos: ModifyColumn last_accessed_at..." and the
RawExpr lines) lacks a language identifier; update that fenced block to include
a language tag such as "text" (e.g., ```text) so tooling and syntax highlighting
correctly treat the output, leaving the contents (ModifyTable narinfos /
ModifyTable nar_files and the RawExpr lines) unchanged.


</details>

<!-- cr-comment:v1:f3d77c8aa870953fa9a16703 -->

</blockquote></details>

</blockquote></details>

<details>
<summary>🤖 Prompt for all review comments with AI agents</summary>

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 @cmd/ent-lint/main.go:

  • Around line 591-596: The failure message only prints file:line via
    relPath(sf.path) and v; modify the violation payload to carry the offending
    field identifier (e.g., add a fieldName string property on the violation struct)
    and change the detail fmt.Sprintf call (the call that constructs detail using
    relPath(sf.path) and v) to include that fieldName (e.g., "%s:%d %s
    entsql.Annotation{...} is forbidden" or similar), update the code paths that
    build this violation so they pass the offending field name (where the annotation
    is detected), and adjust the A6 test expectations to assert the new "[FAIL] A6"
    message includes the field identifier (e.g., last_accessed_at).

Outside diff comments:
In @.claude/rules/ent-migrations.md:

  • Around line 3-5: Update the textual references to match the new count of
    invariants: change "the four codegen invariants below" to "the six codegen
    invariants below" and change "These five patterns" to "These six patterns";
    search the same document (.claude/rules/ent-migrations.md) for any other
    occurrences of the numbers referring to invariants/patterns and update them to
    six so the header and inline references are consistent with the six listed
    invariants.

Nitpick comments:
In
@openspec/changes/archive/2026-06-06-fix-sqlite-default-expr-phantom-diff/design.md:

  • Around line 7-12: The fenced code block showing the Atlas diff (the block
    containing "ModifyTable narinfos: ModifyColumn last_accessed_at..." and the
    RawExpr lines) lacks a language identifier; update that fenced block to include
    a language tag such as "text" (e.g., ```text) so tooling and syntax highlighting
    correctly treat the output, leaving the contents (ModifyTable narinfos /
    ModifyTable nar_files and the RawExpr lines) unchanged.

</details>

<details>
<summary>🪄 Autofix (Beta)</summary>

Fix all unresolved CodeRabbit comments on this PR:

- [ ] <!-- {"checkboxId": "4b0d0e0a-96d7-4f10-b296-3a18ea78f0b9"} --> Push a commit to this branch (recommended)
- [ ] <!-- {"checkboxId": "ff5b1114-7d8c-49e6-8ac1-43f82af23a33"} --> Create a new PR with the fixes

</details>

---

<details>
<summary>ℹ️ Review info</summary>

<details>
<summary>⚙️ Run configuration</summary>

**Configuration used**: Organization UI

**Review profile**: CHILL

**Plan**: Pro

**Run ID**: `08fca5cc-1f7f-4e5e-a9d1-4eb30f768eef`

</details>

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 8f8a16256bdb15d6243526cab9992c70b0b52ea3 and 5770238bc16226d5c69c5936be3cfc1b837dd812.

</details>

<details>
<summary>📒 Files selected for processing (17)</summary>

* `.claude/rules/ent-migrations.md`
* `cmd/ent-lint/main.go`
* `cmd/ent-lint/main_test.go`
* `cmd/ent-lint/testdata/a6_bad/schema.go`
* `cmd/ent-lint/testdata/a6_good/schema.go`
* `cmd/generate-migrations/main_test.go`
* `ent/migrate/schema.go`
* `ent/schema/nar_file.go`
* `ent/schema/narinfo.go`
* `openspec/changes/archive/2026-06-06-fix-sqlite-default-expr-phantom-diff/.openspec.yaml`
* `openspec/changes/archive/2026-06-06-fix-sqlite-default-expr-phantom-diff/design.md`
* `openspec/changes/archive/2026-06-06-fix-sqlite-default-expr-phantom-diff/proposal.md`
* `openspec/changes/archive/2026-06-06-fix-sqlite-default-expr-phantom-diff/specs/database-migrations/spec.md`
* `openspec/changes/archive/2026-06-06-fix-sqlite-default-expr-phantom-diff/specs/ent-schema-lint/spec.md`
* `openspec/changes/archive/2026-06-06-fix-sqlite-default-expr-phantom-diff/tasks.md`
* `openspec/specs/database-migrations/spec.md`
* `openspec/specs/ent-schema-lint/spec.md`

</details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Comment thread cmd/ent-lint/main.go Resolved
Address PR #1339 review feedback on the A6 invariant:

- The A6 failure message printed only file:line; the spec requires
  naming the offending field. Thread the field identifier (walked from
  the field.X("name") call at the head of the builder chain) into the
  [FAIL] A6 message.
- entsqlAnnotationDefaultExpr only matched the value form
  entsql.Annotation{...}; the pointer form &entsql.Annotation{...} also
  satisfies schema.Annotation (value-receiver Name()), so the linter
  would silently miss it. Unwrap a leading address-of (token.AND) before
  matching the composite literal.

Add a pointer-form fixture (a6_bad_pointer) and a field-name assertion
to the A6 test cases.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit enabled auto-merge (squash) June 7, 2026 01:30
@kalbasit
kalbasit merged commit 6d23b71 into main Jun 7, 2026
34 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/fix-issue-1328 branch June 7, 2026 01:35
kalbasit added a commit to bryandph/ncps that referenced this pull request Jun 7, 2026
* origin/main:
  fix(cdc): heal orphaned mid-chunking NAR state via migration-lock liveness (kalbasit#1317)
  chore(deps): update codecov/codecov-action action to v7 (kalbasit#1340)
  feat(fsck): reclaim CDC chunked-NAR residue (grace-period mark-then-purge) (kalbasit#1335)
  fix(ent): stop sqlite phantom narinfos/nar_files rebuild (kalbasit#1339)
  chore: update flake.lock and run go mod tidy (kalbasit#1338)
  fix(deps): update module github.com/mattn/go-sqlite3 to v1.14.45 (kalbasit#1336)
  fix(cache,fsck): self-completing CDC drain (de-chunk never strands NARs) (kalbasit#1334)
  fix(cache,fsck): reconcile narinfo<->nar_file links (drain-mode unblock + prevention) (kalbasit#1333)
  fix(cache): close the CDC url=none/xz-NAR desync (prevention + repair) (kalbasit#1332)
  fix(cache): durable-bytes marker for /upload reference presence (kalbasit#1330)
  fix(cache): non-destructive narinfo purge on root path (kalbasit#1326)

# Conflicts:
#	migrations/mysql/atlas.sum
#	migrations/postgres/atlas.sum
#	migrations/sqlite/atlas.sum
#	pkg/cache/cache.go
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working go Pull requests that update go code size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

sqlite migration generator spuriously rebuilds the unrelated narinfos table on every new migration

1 participant