Repository navigation
fix: customer delete - #3326
fix: customer delete#3326turip wants to merge 1 commit into
Conversation
Use a different field to determine if the usage_attribution of the subject has been deleted due to the customer being deleted or if the mapping has changend. I would prefer this approach instead of checking for equality with the customer.deleted_at field as it makes it more explicit why the deletion have happened.
📝 WalkthroughWalkthroughIntroduces a new nullable field customer_deleted_at on customer_subjects, updates Ent-generated structs, predicates, builders, mutations, and helpers to support it, adjusts indexes and schema/migrations, and switches customer deletion logic in the adapter to use CustomerDeletedAt-based predicates and setters. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Warning Review ran into problems🔥 ProblemsGit: Failed to clone repository. Please run the ✨ Finishing Touches
🧪 Generate unit tests
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.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (5)
openmeter/customer/adapter/customer.go (5)
58-66: Subject filter should also require CustomerDeletedAtIsNil.Without this, customers may match via subject mappings deleted because the customer was deleted.
Apply:
- query = query.Where(customerdb.HasSubjectsWith( - customersubjectsdb.SubjectKeyContainsFold(*input.Subject), - customersubjectsdb.Or( - customersubjectsdb.DeletedAtIsNil(), - customersubjectsdb.DeletedAtGT(now), - ), - )) + query = query.Where(customerdb.HasSubjectsWith( + customersubjectsdb.SubjectKeyContainsFold(*input.Subject), + customersubjectsdb.CustomerDeletedAtIsNil(), + customersubjectsdb.Or( + customersubjectsdb.DeletedAtIsNil(), + customersubjectsdb.DeletedAtGT(now), + ), + ))
155-161: Key-vs-subject conflict check must match new “active” semantics.This check should exclude mappings deleted by customer to avoid false conflicts when recreating a customer after deletion.
Apply:
- Where(customersubjectsdb.DeletedAtIsNil()). + Where(customersubjectsdb.DeletedAtIsNil()). + Where(customersubjectsdb.CustomerDeletedAtIsNil()).
445-451: Update path: same conflict check gap.Match the partial unique index predicate to avoid false positives.
Apply:
- Where(customersubjectsdb.DeletedAtIsNil()). + Where(customersubjectsdb.DeletedAtIsNil()). + Where(customersubjectsdb.CustomerDeletedAtIsNil()).
387-393: GetCustomerByUsageAttribution: exclude mappings deleted by customer.Align selection with “active” mapping definition.
Apply:
- Where(customerdb.HasSubjectsWith( - customersubjectsdb.SubjectKey(input.SubjectKey), - customersubjectsdb.Or( - customersubjectsdb.DeletedAtIsNil(), - customersubjectsdb.DeletedAtGT(now), - ), - )). + Where(customerdb.HasSubjectsWith( + customersubjectsdb.SubjectKey(input.SubjectKey), + customersubjectsdb.CustomerDeletedAtIsNil(), + customersubjectsdb.Or( + customersubjectsdb.DeletedAtIsNil(), + customersubjectsdb.DeletedAtGT(now), + ), + )).
642-648: withSubjects should enforce CustomerDeletedAtIsNil for “active” edge.Prevents loading edges that are deleted via customer.
Apply:
func withSubjects(query *entdb.CustomerQuery, at time.Time) *entdb.CustomerQuery { return query.WithSubjects(func(query *entdb.CustomerSubjectsQuery) { - query.Where(customersubjectsdb.Or( - customersubjectsdb.DeletedAtIsNil(), - customersubjectsdb.DeletedAtGT(at), - )) + query.Where( + customersubjectsdb.CustomerDeletedAtIsNil(), + customersubjectsdb.Or( + customersubjectsdb.DeletedAtIsNil(), + customersubjectsdb.DeletedAtGT(at), + ), + ) }) }
🧹 Nitpick comments (10)
openmeter/ent/schema/customer.go (1)
107-114: Partial unique now correctly excludes rows deleted via either flag.Good change. As a follow-up, consider adding a secondary (non-unique) partial index to speed up frequent filters by (namespace, customer_id) for “active” mappings:
Apply via Ent (not the generated schema):
func (CustomerSubjects) Indexes() []ent.Index { return []ent.Index{ index.Fields("namespace", "customer_id", "deleted_at"), index.Fields("namespace", "subject_key"). Annotations( // Partial index: We skip the index on active non deleted customer subjects. entsql.IndexWhere("deleted_at IS NULL AND customer_deleted_at IS NULL"), ). Unique(), + index.Fields("namespace", "customer_id"). + Annotations( + entsql.IndexWhere("deleted_at IS NULL AND customer_deleted_at IS NULL"), + ), } }tools/migrate/migrations/20250907132537_differentiate-customer-and-subject-mapping-deletion.up.sql (2)
1-6: Safe DDL: consider IF EXISTS/IF NOT EXISTS and (optionally) CONCURRENTLY.If your migration runner allows, prefer:
- DROP INDEX IF EXISTS ...
- CREATE UNIQUE INDEX CONCURRENTLY ... (requires running outside a transaction)
This reduces lock time on large tables.
Do you run migrations inside a transaction? If yes, skip CONCURRENTLY. Also verify the index name matches existing environments to avoid failures during DROP.
4-6: Backfill for historical rows likely needed.To classify past deletions correctly, backfill rows where cs.deleted_at was set due to customer deletion:
Proposed SQL (run after adding the new column, before recreating the unique index if you need the backfill for analytics; uniqueness isn’t affected either way):
UPDATE customer_subjects cs SET customer_deleted_at = cs.deleted_at, deleted_at = NULL FROM customers c WHERE cs.customer_id = c.id AND cs.deleted_at IS NOT NULL AND c.deleted_at IS NOT NULL AND cs.deleted_at = c.deleted_at;Want me to package this as a separate migration file?
openmeter/customer/adapter/customer.go (1)
565-572: Optional: avoid touching subject mappings already deleted via customer.Add CustomerDeletedAtIsNil() to narrow the update scope for removals during update.
Apply:
- Where(customersubjectsdb.DeletedAtIsNil()). + Where(customersubjectsdb.DeletedAtIsNil()). + Where(customersubjectsdb.CustomerDeletedAtIsNil()).openmeter/ent/db/migrate/schema.go (1)
1385-1395: Optional: consider an additional partial index for common filters.If you often filter CustomerSubjects by (namespace, customer_id) and “active” semantics, add a partial index via Ent (see suggestion in schema/customer.go comment). This avoids scanning rows with non-nil customer_deleted_at.
openmeter/ent/db/customersubjects_update.go (1)
129-134: Set/Clear ordering: verify mutation semantics so Clear doesn’t unintentionally win.sqlSave applies SetField then ClearField, which is standard for ent, but relies on SetCustomerDeletedAt() resetting the “cleared” flag in the mutation. Please verify the mutation methods ensure “last call wins” (i.e., Set after Clear results in a set value). If business rules require mutual exclusivity between deleted_at and customer_deleted_at, consider enforcing via an ent hook or a DB CHECK constraint rather than touching generated code.
Run:
#!/bin/bash # Expect: SetCustomerDeletedAt resets the cleared flag; Clear sets it. rg -n -C3 'type CustomerSubjectsMutation struct' openmeter/ent/db/mutation.go rg -n -C3 '\bSetCustomerDeletedAt\(' openmeter/ent/db/mutation.go rg -n -C3 '\bClearCustomerDeletedAt\(' openmeter/ent/db/mutation.go # Optional: confirm column presence across generated code. rg -n 'FieldCustomerDeletedAt|CustomerDeletedAt' openmeter/ent/db/**/*openmeter/ent/db/customersubjects/where.go (1)
373-421: Predicate set is complete; add domain-level helpers for common filtersConsider small, non-generated helpers to express intent and avoid repeating predicate combinations at call sites.
Example (place in a non-generated file, e.g., openmeter/customer/adapter/predicates.go):
package adapter import ( "github.com/openmeterio/openmeter/openmeter/ent/db/customersubjects" "github.com/openmeterio/openmeter/openmeter/ent/db/predicate" ) func CSActive() predicate.CustomerSubjects { return customersubjects.And( customersubjects.DeletedAtIsNil(), customersubjects.CustomerDeletedAtIsNil(), ) } func CSDeletedByCustomer() predicate.CustomerSubjects { return customersubjects.CustomerDeletedAtNotNil() } func CSDeletedByMappingChange() predicate.CustomerSubjects { return customersubjects.DeletedAtNotNil() }Run to ensure call sites switched from DeletedAt* to CustomerDeletedAt* where appropriate:
#!/bin/bash set -euo pipefail echo "Legacy DeletedAt-based usages:" rg -n --type go -C2 'customersubjects\.(DeletedAt(IsNil|NotNil|EQ|NEQ|In|NotIn|GT|GTE|LT|LTE)|SetDeletedAt|ClearDeletedAt)\(' || true echo echo "New CustomerDeletedAt usages:" rg -n --type go -C2 'customersubjects\.CustomerDeletedAt' || trueopenmeter/ent/db/customersubjects_create.go (3)
298-315: Upsert API: add convenience to enforce exclusivity when setting reasonProvide small wrappers (non-generated) to set one and clear the other to avoid accidental dual-setting.
Example helpers:
func CSSetDeletedByCustomer(u *db.CustomerSubjectsUpsert, t time.Time) { u.ClearDeletedAt().SetCustomerDeletedAt(t) } func CSSetDeletedByMapping(u *db.CustomerSubjectsUpsert, t time.Time) { u.ClearCustomerDeletedAt().SetDeletedAt(t) }
391-411: UpsertOne: mirror the exclusivity helpersExpose thin wrappers so call sites don’t forget to clear the opposite field.
Example:
func CS1SetDeletedByCustomer(u *db.CustomerSubjectsUpsertOne, t time.Time) { u.ClearDeletedAt().SetCustomerDeletedAt(t) }
653-673: UpsertBulk: same convenience for bulk pathsBulk operations benefit most from safe helpers that clear the opposite field.
Example:
func CSBulkSetDeletedByCustomer(u *db.CustomerSubjectsUpsertBulk, t time.Time) { u.ClearDeletedAt().SetCustomerDeletedAt(t) }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
tools/migrate/migrations/atlas.sumis excluded by!**/*.sum
📒 Files selected for processing (12)
openmeter/customer/adapter/customer.go(1 hunks)openmeter/ent/db/customersubjects.go(4 hunks)openmeter/ent/db/customersubjects/customersubjects.go(3 hunks)openmeter/ent/db/customersubjects/where.go(2 hunks)openmeter/ent/db/customersubjects_create.go(5 hunks)openmeter/ent/db/customersubjects_update.go(4 hunks)openmeter/ent/db/migrate/schema.go(3 hunks)openmeter/ent/db/mutation.go(10 hunks)openmeter/ent/db/setorclear.go(1 hunks)openmeter/ent/schema/customer.go(2 hunks)tools/migrate/migrations/20250907132537_differentiate-customer-and-subject-mapping-deletion.down.sql(1 hunks)tools/migrate/migrations/20250907132537_differentiate-customer-and-subject-mapping-deletion.up.sql(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
- GitHub Check: E2E
- GitHub Check: Quickstart
- GitHub Check: Analyze (go)
🔇 Additional comments (22)
openmeter/ent/db/customersubjects/customersubjects.go (1)
27-28: LGTM: field constant, Columns entry, and order helper added consistently.No issues spotted.
Also applies to: 50-50, 107-110
tools/migrate/migrations/20250907132537_differentiate-customer-and-subject-mapping-deletion.down.sql (1)
1-6: Down migration matches the up migration’s intent.Index drop, column drop, and index recreation look correct.
openmeter/ent/schema/customer.go (1)
99-101: LGTM: new nullable field customer_deleted_at on CustomerSubjects.Matches the PR semantics.
openmeter/ent/db/customersubjects.go (1)
31-32: LGTM: model field, scan/assign branches, and String() update are correct.Consistent with ent patterns.
Also applies to: 68-69, 122-128, 186-190
openmeter/ent/db/setorclear.go (1)
2018-2030: LGTM: SetOrClearCustomerDeletedAt mirrors existing pattern.Matches SetOrClearDeletedAt behavior.
openmeter/customer/adapter/customer.go (2)
296-298: LGTM: switch to CustomerDeletedAt for customer-wide subject deletion.Correctly narrows to active mappings and sets the new flag.
1-710: Repo-wide verification for active subject mapping filters.Search for other places that treat “active” CustomerSubjects as DeletedAtIsNil (or GT) without also requiring CustomerDeletedAtIsNil.
Run:
#!/bin/bash # Find CustomerSubjects predicates that likely need CustomerDeletedAtIsNil alongside DeletedAt* checks. rg -n --hidden --glob '!**/node_modules/**' --glob '!**/dist/**' \ -C2 -e 'customersubjectsdb\.(DeletedAtIsNil|DeletedAtGT)\(' # Also list all uses of CustomerDeletedAtIsNil to confirm coverage. rg -n --hidden --glob '!**/node_modules/**' --glob '!**/dist/**' \ -C2 -e 'CustomerDeletedAtIsNil\('openmeter/ent/db/migrate/schema.go (1)
1362-1364: LGTM: generated schema updates align with the new field and index predicate.Column order/indices/foreign keys adjusted correctly.
Also applies to: 1373-1374, 1387-1388, 1394-1395
openmeter/ent/db/customersubjects_update.go (3)
51-70: New CustomerDeletedAt setters/clearers mirror DeletedAt — looks correct.Public API is consistent with ent’s conventions and the existing DeletedAt methods. Chainability and nillable helper are good.
175-194: UpdateOne: symmetric CustomerDeletedAt setters/clearers — LGTM.API parity with the multi-update builder is maintained.
283-288: UpdateOne sql path includes CustomerDeletedAt set/clear — LGTM.Behavior aligns with the multi-update path.
openmeter/ent/db/mutation.go (9)
31114-31128: CustomerSubjectsMutation struct wiring looks consistent.New field and related state are added in line with existing mutation patterns. No concerns.
31531-31531: Prealloc capacity updated — OK.Capacity bump to 6 aligns with the added field.
31547-31549: Include customer_deleted_at in Fields() — OK.Ensures mutation reports the field when set.
31568-31570: Field(name) support added — OK.Returns the (time.Time, bool) pair consistent with other nullable time fields.
31589-31591: OldField(name) support added — OK.UpdateOne guard and oldValue retrieval are correct.
31635-31641: SetField handling — OK.Type assertion to time.Time and delegation to SetCustomerDeletedAt are correct.
31675-31677: ClearedFields() wiring — OK.New field is surfaced when cleared. Will work once ClearCustomerDeletedAt is fixed.
31695-31697: ClearField delegating — OK.Delegates to ClearCustomerDeletedAt; depends on the nil-map fix above.
31721-31723: ResetField support — OK.ResetCustomerDeletedAt correctly restores state and clears the clearedFields flag.
openmeter/ent/db/customersubjects/where.go (1)
83-86: LGTM: alias predicate added correctlyAlias matches the existing pattern (e.g., DeletedAt) and references FieldCustomerDeletedAt as expected.
openmeter/ent/db/customersubjects_create.go (1)
72-85: LGTM: setters for customer_deleted_at on createMatches existing patterns (nillable and direct setters).
| if value, ok := _c.mutation.CustomerDeletedAt(); ok { | ||
| _spec.SetField(customersubjects.FieldCustomerDeletedAt, field.TypeTime, value) | ||
| _node.CustomerDeletedAt = &value | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Enforce “at most one” non-null between deleted_at and customer_deleted_at
Without a guard, both fields can be set, which breaks the deletion-reason invariant and can invalidate partial indexes.
Options:
- DB check constraint (preferred for integrity):
ALTER TABLE customer_subjects
ADD CONSTRAINT customer_subjects_del_at_mono_null
CHECK (NOT (deleted_at IS NOT NULL AND customer_deleted_at IS NOT NULL));- Ent hook (non-generated file) to validate on create/update:
client.CustomerSubjects.Use(func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
csm, ok := m.(*db.CustomerSubjectsMutation); if !ok { return next.Mutate(ctx, m) }
da, daOK := csm.DeletedAt()
cda, cdaOK := csm.CustomerDeletedAt()
if (daOK && !da.IsZero()) && (cdaOK && !cda.IsZero()) {
return nil, fmt.Errorf("both deleted_at and customer_deleted_at set")
}
return next.Mutate(ctx, m)
})
})Verify schema/migrations and partial indexes reflect the new logic (unique on active rows where both are NULL):
#!/bin/bash
set -euo pipefail
echo "Schema references to customer_deleted_at:"
rg -n -C2 'customer_deleted_at' openmeter/ent/schema || true
echo
echo "Migrations updating indexes/constraints:"
rg -n -C2 -e 'customer_deleted_at' -e 'deleted_at IS NULL' -e 'WHERE.*customer_deleted_at' tools/migrate/ migrations/ || true🤖 Prompt for AI Agents
In openmeter/ent/db/customersubjects_create.go around lines 207-210, the
mutation currently allows both deleted_at and customer_deleted_at to be set
which violates the invariant; add a guard to enforce at-most-one non-null by
either (A) adding a DB CHECK constraint in the migrations (preferred): add a
migration that runs ALTER TABLE customer_subjects ADD CONSTRAINT
customer_subjects_del_at_mono_null CHECK (NOT (deleted_at IS NOT NULL AND
customer_deleted_at IS NOT NULL)); and update any partial indexes to reflect
unique-on-active-rows semantics, or (B) add an Ent hook (in a non-generated
file) that validates the mutation on create/update and returns an error if both
timestamps are present; finally, update/verify schema migrations and any partial
indexes to reference customer_deleted_at/deleted_at appropriately.
Overview
Use a different field to determine if the usage_attribution of the subject has been deleted due to the customer being deleted or if the mapping has changend.
I would prefer this approach instead of checking for equality with the customer.deleted_at field as it makes it more explicit why the deletion have happened.
Migration
Most probably the following migration would work to update the DB (but it's fine to test it seperately):
Summary by CodeRabbit
New Features
Bug Fixes
Chores