Skip to content

fix(backend): add self-reference guard, label/webhook_log FKs, retention index - #167

Merged
getappz merged 1 commit into
masterfrom
feat/agentflare-backend-schema-constraints
Jul 13, 2026
Merged

getappz merged 1 commit into
masterfrom
feat/agentflare-backend-schema-constraints

Conversation

@getappz

@getappz getappz commented Jul 13, 2026 •

Copy link
Copy Markdown
Owner

What

Migration 0002_schema_constraints.sql, addressing the 4 schema-hardening items CodeRabbit flagged on #166 (against schema content that PR only renamed, didn't modify):

  • item_dependencies: CHECK (item_id != depends_on_item_id) — there was no guard anywhere (app or db) against an item depending on itself. item::add_dependency does a raw INSERT OR IGNORE.
  • labels.project_id now REFERENCES projects(id) (still nullable — NULL means a workspace-only label).
  • webhook_logs.webhook_id now REFERENCES webhooks(id).
  • webhook_logs: added an index on created_at to make a future retention/purge query cheap. Raw request/response bodies here can carry secrets/PII forwarded through webhooks with no TTL today — actually scheduled purging is a separate, not-yet-requested piece of work; this just removes the cost of adding it later.

Implementation notes

SQLite has no ALTER TABLE ADD CONSTRAINT, so adding a CHECK or FOREIGN KEY to an existing table means rebuilding it. Each rebuild here creates the replacement under a _new name, copies data across, drops the original, then renames _new into the original's name — deliberately in that order. Doing it the other way (rename original to _old first) hits a real SQLite gotcha: renaming a table away from its name silently rewrites other tables' existing FK definitions that reference it by that name (item_labels.label_id REFERENCES labels(id) became REFERENCES labels_old(id) when I first tried it, breaking label assignment once labels_old was dropped). Going new-name-first sidesteps this since nothing references the _new name. Caught by a full cargo test -p agentflare-backend run before pushing — two pre-existing label tests failed until this was fixed.

The item_dependencies self-reference CHECK: any pre-existing violating row is silently dropped during the copy rather than failing the migration (there's no way for a self-referencing row to have been intentional, and failing the migration over it would just brick startup for whoever has one).

Testing

Added to crates/agentflare-backend/src/db.rs:

  • migration_0002_preserves_data_and_drops_bad_self_reference — seeds a v1-only db (only migration 0001 applied, matching real installed backend.db state before this PR) with valid data plus one self-referencing item_dependencies row, opens it through open_db, and asserts: the bad row is gone, all other data survived, user_version reflects both migrations applied.
  • migration_0002_enforces_new_constraints — on a fresh db, asserts inserting a self-referencing dependency, a label with a bogus project_id, and a webhook_log with a bogus webhook_id all now fail with a constraint violation.

Also ran:

  • cargo test -p agentflare-backend — 59/59 pass
  • cargo build --workspace
  • cargo clippy --locked --workspace --all-targets --all-features -- -D warnings -A unsafe_code -A clippy::pedantic (CI's exact flags)
  • cargo fmt --check
  • cargo deny check

Summary by CodeRabbit

  • Bug Fixes
    • Improved database integrity by enforcing valid relationships between items, labels, webhooks, and workspaces.
    • Prevented invalid self-referencing item dependencies.
    • Preserved valid existing data during database upgrades while removing invalid dependency records.
    • Strengthened uniqueness rules for active labels within projects and workspaces.
    • Added indexes to improve webhook log lookups and support future cleanup operations.

@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: c0ee2879-3d50-4277-bfe6-d1f65e5e50e2

📥 Commits

Reviewing files that changed from the base of the PR and between a833965 and 6898b54.

📒 Files selected for processing (2)
  • crates/agentflare-backend/src/db.rs
  • crates/agentflare-backend/src/migrations/0002_schema_constraints.sql

📝 Walkthrough

Walkthrough

Changes

The database migration list now includes migration 0002. The migration rebuilds item_dependencies, labels, and webhook_logs with foreign keys, checks, unique constraints, and indexes. Tests verify legacy-data migration, cleanup, version tracking, and constraint enforcement.

Schema constraint migration

Layer / File(s) Summary
Constrained table rebuilds
crates/agentflare-backend/src/migrations/0002_schema_constraints.sql
Rebuilds three SQLite tables with stronger relationships, filters invalid self-references, adds conditional uniqueness rules, and creates webhook log indexes.
Migration registration and verification
crates/agentflare-backend/src/db.rs
Registers migration 0002, updates migration-version assertions, verifies legacy data migration, and tests rejected constraint violations.

Estimated code review effort: 3 (Moderate) | ~20 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% 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 backend schema-hardening changes and added migration tests.
Description check ✅ Passed The description covers the change, implementation notes, and testing, but it doesn't follow the requested template headings or checklist exactly.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/agentflare-backend-schema-constraints

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

@getappz
getappz merged commit ad00202 into master Jul 13, 2026
14 checks passed
@getappz
getappz deleted the feat/agentflare-backend-schema-constraints branch July 13, 2026 10:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant