Repository navigation
fix(functions): remove orphaned deployment records on function deletion - #1444
Conversation
When a function is deleted via DELETE /api/functions/:slug, deployment records in functions.deployments that reference the deleted slug in their JSONB functions array are now cleaned up. Previously these records remained indefinitely as orphans since the table has no FK constraint. Uses the @> containment operator to find all deployments referencing the deleted slug, consistent with how the JSONB array is stored. Closes InsForge#1365
|
Thanks for the PR, @eunseo9311! This links #1365, but that issue isn't assigned to you. Our workflow is claim the issue first (get it assigned), then submit the PR. It'll still be reviewed, but please claim the issue (comment that you'd like it assigned to you) to keep ownership clear. |
WalkthroughdeleteFunction now performs the function deletion and deployment-record cleanup inside a DB transaction: it deletes the function definition, removes the slug from any matching ChangesOrphaned deployment cleanup on function deletion
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Code Review — fix(functions): remove orphaned deployment records on function deletion
The intent is correct and the problem is real. Two blocking issues must be resolved before merge, plus one additional correctness concern worth addressing in the same pass.
Critical / Blocking
1. Non-atomic double-delete — the race condition the PR aims to fix remains reproducible
function.service.ts ~line 318
The definitions DELETE and the deployments DELETE are two separate, independent pool.query() calls with no enclosing transaction. If the process crashes, the DB connection drops, or the second query throws after the first has committed, the function definition is gone but the deployment rows survive — the exact orphan situation this PR is meant to prevent. The fix must be atomic.
The cleanest solution that requires no transaction block is a single CTE:
WITH deleted AS (
DELETE FROM functions.definitions
WHERE slug = $1
RETURNING slug
)
DELETE FROM functions.deployments
WHERE functions @> $2::jsonb
AND EXISTS (SELECT 1 FROM deleted);Alternatively, wrap both statements in an explicit BEGIN / COMMIT using a pooled client.
2. Bare await introduces a new throwing path after partial success
function.service.ts ~line 318
If the deployments DELETE throws (transient DB error, connection timeout), deleteFunction() propagates the exception even though functions.definitions has already been committed. Callers that catch this error will incorrectly believe the function still exists. The cleanup query should either be run inside the same transaction as (1), or its failure should be handled gracefully (log + swallow, or surface a dedicated error type that communicates "definition deleted, cleanup failed").
Important
3. @> containment deletes deployment rows shared by multiple functions
function.service.ts ~line 317
WHERE functions @> '["slug"]'::jsonb matches every row whose functions array contains the slug — including rows that also list other slugs. If any deployment record covers more than one function (e.g., functions = ["func-a", "func-b"]), deleting func-a silently removes func-b's deployment record too.
If the invariant is "one deployment row ↔ exactly one function slug", please add a CHECK (jsonb_array_length(functions) = 1) constraint to the table so this assumption is enforced at the DB level. If multi-function rows are possible, the DELETE must be scoped differently (e.g., remove the element from the array rather than deleting the row).
Minor / Test quality
4. Missing test for the new exception path
backend/tests/unit/function-delete-cleanup.test.ts
There is no test for the case where the deployment cleanup query throws after the definition is deleted. This is the most operationally surprising new behaviour the PR introduces, and it should be verified explicitly.
5. toHaveBeenCalledTimes(2) is brittle
function-delete-cleanup.test.ts line 55
This assertion hard-codes the total number of DB queries inside deleteFunction(). Any unrelated future addition (audit log, notification) will silently break this test with no clear diagnostic. Prefer asserting on the specific calls that matter rather than the total count, or at least add a comment explaining the expected sequence.
Summary
| Severity | Count |
|---|---|
| Critical / Blocking | 2 |
| Important | 1 |
| Minor | 2 |
The transaction-safety issue (#1) and the new error-path contract (#2) must be addressed. Issue #3 should be resolved in the same PR since the queries are already being written. The tests are a good start — extend them for the failure path once the logic is corrected.
Greptile SummaryThis PR wraps
Confidence Score: 5/5The change is functionally correct and safe to merge; the transaction boundary, ROLLBACK handling, and client release are all implemented properly. The transaction wrapping, COMMIT/ROLLBACK paths, and backend/src/services/functions/function.service.ts — specifically the UPDATE query inside deleteFunction where function_count is not adjusted. Important Files Changed
Sequence DiagramsequenceDiagram
participant Caller
participant FunctionService
participant PgClient
participant DB as functions.definitions / functions.deployments
Caller->>FunctionService: deleteFunction(slug)
FunctionService->>PgClient: connect()
PgClient-->>FunctionService: client
FunctionService->>PgClient: BEGIN
PgClient->>DB: (transaction open)
FunctionService->>PgClient: "DELETE FROM functions.definitions WHERE slug=$1"
PgClient-->>FunctionService: rowCount
alt "rowCount === 0"
FunctionService->>PgClient: ROLLBACK
FunctionService->>PgClient: release() [finally]
FunctionService-->>Caller: false
else "rowCount > 0"
FunctionService->>PgClient: "UPDATE functions.deployments SET functions = functions - $1 WHERE functions @> $2::jsonb"
Note over PgClient,DB: Removes slug from JSONB array in ALL matching historical rows
PgClient-->>FunctionService: ok
FunctionService->>PgClient: COMMIT
FunctionService->>FunctionService: scheduleDeployment() [debounced]
FunctionService->>PgClient: release() [finally]
FunctionService-->>Caller: true
end
opt Error during transaction
FunctionService->>PgClient: ROLLBACK (best-effort, errors swallowed)
FunctionService->>PgClient: release() [finally]
FunctionService-->>Caller: throws error
end
Reviews (3): Last reviewed commit: "test: remove redundant mock setup in bef..." | Re-trigger Greptile |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
backend/src/services/functions/function.service.ts (1)
307-324:⚠️ Potential issue | 🟠 Major | ⚡ Quick winWrap the two delete statements in a single DB transaction.
Line 310 and Line 319 form one logical mutation, but they currently execute outside a transaction. If the deployment cleanup fails after the definition delete, the method throws while the function is already removed (partial commit + misleading failure response).
Suggested fix
async deleteFunction(slug: string): Promise<boolean> { + const client = await this.getPool().connect(); try { - const result = await this.getPool().query( + await client.query('BEGIN'); + const result = await client.query( 'DELETE FROM functions.definitions WHERE slug = $1', [slug] ); if (result.rowCount === 0) { + await client.query('ROLLBACK'); return false; } // Remove deployment records that reference the deleted function - await this.getPool().query('DELETE FROM functions.deployments WHERE functions @> $1::jsonb', [ + await client.query('DELETE FROM functions.deployments WHERE functions @> $1::jsonb', [ JSON.stringify([slug]), ]); + await client.query('COMMIT'); // Trigger redeployment without the deleted function this.scheduleDeployment(); return true; } catch (error) { + await client.query('ROLLBACK').catch(() => undefined); logger.error('Failed to delete function', { error: error instanceof Error ? error.message : String(error), operation: 'deleteFunction', slug, }); throw error; + } finally { + client.release(); } }As per coding guidelines:
backend/src/**/*.{ts,js}: "Implement proper database transaction handling".🤖 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 `@backend/src/services/functions/function.service.ts` around lines 307 - 324, The deleteFunction method currently issues two separate DB mutations (the DELETE from functions.definitions and the DELETE from functions.deployments) outside a transaction; modify deleteFunction to acquire a client from getPool(), start a transaction (BEGIN), perform both DELETE queries using that client (referencing the same parameterized slug/JSON payload as now), COMMIT if both succeed, and on any error ROLLBACK before releasing the client and rethrowing/returning the error; ensure scheduleDeployment() is invoked only after a successful COMMIT and that the client is always released in a finally block to avoid connection leaks.
🤖 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.
Outside diff comments:
In `@backend/src/services/functions/function.service.ts`:
- Around line 307-324: The deleteFunction method currently issues two separate
DB mutations (the DELETE from functions.definitions and the DELETE from
functions.deployments) outside a transaction; modify deleteFunction to acquire a
client from getPool(), start a transaction (BEGIN), perform both DELETE queries
using that client (referencing the same parameterized slug/JSON payload as now),
COMMIT if both succeed, and on any error ROLLBACK before releasing the client
and rethrowing/returning the error; ensure scheduleDeployment() is invoked only
after a successful COMMIT and that the client is always released in a finally
block to avoid connection leaks.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: cda67ba4-c1d7-4598-b6fa-87d6e32a262c
📒 Files selected for processing (2)
backend/src/services/functions/function.service.tsbackend/tests/unit/function-delete-cleanup.test.ts
There was a problem hiding this comment.
2 issues found across 2 files
Confidence score: 2/5
- High-confidence, user-impacting risk in
backend/src/services/functions/function.service.ts: theDELETEusing@>can remove all deployment snapshots that include the slug, which can unintentionally wipe unrelated deployment records. deleteFunctionappears non-atomic inbackend/src/services/functions/function.service.ts(separate autocommit operations), so a cleanup failure can leave partial state with the function deleted but deployment data not fully reconciled.- Given two medium-high severity issues (8/10 and 7/10) with strong confidence, this is high risk to merge until deletion scope and transaction boundaries are tightened.
- Pay close attention to
backend/src/services/functions/function.service.ts- deletion query scope and missing transaction boundary can cause unintended data loss and inconsistent state.
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
…t cleanup - Wrap definition DELETE + deployment cleanup in BEGIN/COMMIT transaction - Replace broad DELETE with UPDATE ... SET functions = functions - $1 to remove only the deleted slug, preserving shared deployment history - Add ROLLBACK on error with client.release() in finally block - Add error-path test for partial failure scenario
There was a problem hiding this comment.
🧹 Nitpick comments (1)
backend/tests/unit/function-delete-cleanup.test.ts (1)
51-54: 💤 Low valueOptional: Remove redundant mock setup.
The
mockPool.connectmock is already configured at lines 9-12 with the same behavior. Re-mocking it inbeforeEachis redundant unless you need to override it in specific tests.♻️ Simplify by removing redundant setup
beforeEach(() => { vi.clearAllMocks(); - mockPool.connect.mockResolvedValue({ - query: clientQueryMock, - release: releaseMock, - }); service = FunctionService.getInstance(); });🤖 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 `@backend/tests/unit/function-delete-cleanup.test.ts` around lines 51 - 54, Remove the redundant mock setup in the beforeEach: the connect mock on mockPool is already set to return { query: clientQueryMock, release: releaseMock } earlier, so delete the duplicate mockPool.connect.mockResolvedValue(...) call inside the beforeEach (or only keep it if a specific test overrides it). Ensure the tests still use the existing mockPool.connect configuration and that clientQueryMock and releaseMock remain available to tests that need them.
🤖 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.
Nitpick comments:
In `@backend/tests/unit/function-delete-cleanup.test.ts`:
- Around line 51-54: Remove the redundant mock setup in the beforeEach: the
connect mock on mockPool is already set to return { query: clientQueryMock,
release: releaseMock } earlier, so delete the duplicate
mockPool.connect.mockResolvedValue(...) call inside the beforeEach (or only keep
it if a specific test overrides it). Ensure the tests still use the existing
mockPool.connect configuration and that clientQueryMock and releaseMock remain
available to tests that need them.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 80c4e7e0-f76d-425f-9a1c-7a100bd7c679
📒 Files selected for processing (2)
backend/src/services/functions/function.service.tsbackend/tests/unit/function-delete-cleanup.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- backend/src/services/functions/function.service.ts
|
Addressed all review feedback in dd801fe and ff726b7:
Ready for re-review when you get a chance. |
jwfing
left a comment
There was a problem hiding this comment.
Review — fix(functions): remove orphaned deployment records on function deletion
Summary: Wrapping the definition delete + deployment-record cleanup in a transaction is a sound, well-tested improvement, but the implementation edits the JSONB functions array rather than deleting rows, which diverges from the PR title/description and leaves the underlying "rows accumulate indefinitely" concern unaddressed.
Requirements context
No matching spec/plan found under docs/superpowers/specs|plans — none of the existing design docs cover function-deletion cleanup. Assessed against the PR description and linked issue #1365 (text not available to me; relying on the author's paraphrase in the PR body).
I verified the core mechanic: functions.deployments.functions is JSONB holding an array of slug strings (migration 022_create-function-deployments.sql:8; written by saveDeployment as JSON.stringify(string[]), function.service.ts:606-614). So functions = functions - $1 (remove string element) and functions @> $2::jsonb (containment) are semantically correct for this shape. 👍 The transaction handling is also correct: BEGIN/conditional ROLLBACK+return false/UPDATE/COMMIT, guarded ROLLBACK().catch(...) in the error path, client.release() in finally, and scheduleDeployment() moved after COMMIT.
Critical
(none) — no correctness, security, data-loss, or broken-behavior issues found.
Suggestion
1. Functionality — implementation does not "remove orphaned records"; rows still accumulate. function.service.ts:323-326 mutates the JSONB array in place; it never deletes rows from functions.deployments. A deployment that referenced only the deleted function becomes functions: [] and remains in the table. If issue #1365's actual goal is to bound unbounded table growth, this PR does not achieve it (the table keeps growing at the same rate). If the goal is instead "scrub references to deleted functions," the current approach is fine — but then the PR title ("remove orphaned deployment records") and the top Summary paragraph ("removes all deployment records referencing the deleted function slug") are inaccurate. Please confirm which goal #1365 intends and align the code or the description accordingly.
2. Functionality / data consistency — function_count drifts. The UPDATE removes a slug from functions but does not decrement the sibling function_count column (migration 022:7). After cleanup the two are inconsistent. Impact is low today because neither column is read back anywhere (only id/url/status are ever SELECTed from this table), but it's worth keeping them in sync — e.g. SET functions = functions - $1, function_count = function_count - 1.
3. Performance — no index for the @> predicate. migration 022 indexes only created_at and status, so WHERE functions @> $2::jsonb does a sequential scan of functions.deployments on every deletion — over a table that grows unbounded (per finding #1). Function deletion isn't a hot path, but if this table is expected to grow large, consider a GIN index on functions (CREATE INDEX ... USING gin (functions)).
4. Software engineering — tests don't exercise the JSONB semantics. function-delete-cleanup.test.ts mocks the pg client and asserts SQL strings + call ordering. That covers the control flow (transaction, rollback, not-found, redeploy) well, but the query is never executed against a real Postgres, so the part the fix actually hinges on — that functions - $1 removes the element and @> matches — is unverified. A wrong operator (or an array-of-objects shape) would still pass these tests. The repo has tests/local and tests/cloud suites; a local integration test that inserts a deployment row and asserts the slug is gone after deleteFunction would close this gap.
Information
- PR description is stale. The title and top "Summary" describe a row-delete approach; the implemented behavior is an array edit. The cubic and Macroscope summaries are accurate — please refresh the human-written Summary to match.
- Operator-resolution hardening. Since no real-DB test runs this query, note that
functions - $1relies on Postgres resolving the untyped bound param to thejsonb - textoverload. This works in practice, butfunctions - $1::textmakes the intent explicit and removes any ambiguity. - Test nit:
vi.spyOn(service, 'scheduleDeployment')(line ~115) has no.mockImplementation, so it calls through to the real method and schedules a real debouncedsetTimeoutduring the test. Harmless (Deno Subhosting is mocked as unconfigured, sotriggerDeploymentno-ops), but.mockImplementation(() => {})avoids a dangling timer.
Security: no security-relevant concerns — slug reaches SQL only via parameterized queries (here and pre-existing), no secrets/PII are newly logged, no auth/authorization changes, no new dependencies.
Verdict: approved (non-blocking)
No Critical findings. The transactional cleanup is a real improvement and is correctly implemented for the chosen approach. The suggestions above — chiefly confirming that the array-edit approach satisfies #1365 and fixing the now-inaccurate title/description — are worth addressing before merge but are not blocking. (This is the bot's assessment; explicit GitHub approval remains a separate human action.)
Summary
When a function is deleted via
FunctionService.deleteFunction(), the corresponding records infunctions.deploymentsare left behind. Sincefunctions.deployments.functionsis a JSONB array (no FK constraint), these orphaned rows accumulate indefinitely.This PR adds a cleanup query that removes all deployment records referencing the deleted function slug immediately after the definition is deleted, before triggering the next deployment cycle.
Closes #1365
How did you test this change?
backend/tests/unit/function-delete-cleanup.test.ts:@>JSONB containment when function is foundscheduleDeployment()is still triggered after cleanupnpm run typecheck,eslint, andprettierall passSummary by cubic
Cleans up references to deleted functions in
functions.deploymentsusing a scoped, transactional update to keep deployment data accurate while preserving shared history.UPDATE ... SET functions = functions - $1 WHERE functions @> $2::jsonbto remove only the deleted slug.scheduleDeployment()after commit.Written for commit ff726b7. Summary will update on new commits.
Note
Remove orphaned deployment records atomically on function deletion in
FunctionServicedeleteFunctionnow runs inside an explicit DB transaction: it deletes fromfunctions.definitionsand, if a row was deleted, removes the slug from thefunctionsJSONB array infunctions.deploymentsusing the-operator.false. On any error during delete or cleanup, the transaction is rolled back and the error is rethrown.scheduleDeploymentis called only after a successful commit.function-delete-cleanup.test.tscover the full BEGIN/DELETE/UPDATE/COMMIT flow, rollback paths, and post-commit scheduling.Macroscope summarized ff726b7.
Summary by CodeRabbit
Bug Fixes
Tests