Skip to content

fix(store): give an imported request a usage id of the importing deployment's - #2189

Merged
thesyncim merged 4 commits into
mainfrom
fix/ai-3477-imported-usage-ids-derived
Nov 23, 2026
Merged

thesyncim merged 4 commits into
mainfrom
fix/ai-3477-imported-usage-ids-derived

Conversation

@thesyncim

@thesyncim thesyncim commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Problem
Fixed charges (a number's rental month, 10DLC fees, knowledge storage hours) get a usage id derived from a fixed key, and Requests.InsertMany skips a row whose usage id already exists (ON CONFLICT (usage_id) DO NOTHING). An imported requests row kept the usage id it was sent with. A row sent with the id of a future charge therefore made that charge look already recorded, and it was never billed.

Fix

  • importRow gives an imported request a usage id of its own, importedUsageID(customer, origin), where origin is the usage id the row had where it was first recorded. No imported row can carry the id of a charge this deployment has yet to make.
  • The origin is kept in a new nullable column, requests.source_usage_id (shard migration 20270119000000). Importing a row again, or a copy of it moved on from another deployment, writes one row.
  • A row taken back to where it was first recorded keeps its usage id when this customer already holds it there, so a move there and back is one row. An id the customer already holds names no charge still to come.
  • deleteRow finds a delete in a change batch by the id made from the one the key names, and never removes a request this deployment recorded itself.
  • A moved request no longer counts as this deployment's record of a charge. The one charge this could bill twice, a bought number's month, goes away with fix(store): an import writes only numbers on the customer's own trunk #2182 (merged).
  • Merge order: the migration sits below the shard migrations of fix(phone): seal parked bridge passwords, hash call tokens, sweep expired bridges #2195 and fix(store): make the migrations after the baseline safe on a live database #2208, so this merges first or is renumbered.

Tests

  • TestAnImportedRequestNamingANumbersComingMonthDoesNotStopItBeingBilled, TestAnImportedRequestIsGivenAUsageIDOfItsOwnAndIsNeverShipped, TestAMovedRequestNeverOverwritesTheDestinationsRowWithItsID: failed before the fix.
  • TestARequestMovedBackIsOneRowWhereItWasRecorded, TestARequestMovedOnFromACopyIsOneRowWhereverItLands: a move back, or on from a copy, is one row. Each failed on the previous head.
  • TestADeleteNamingARequestRecordedHereLeavesIt, TestARequestImportedByTwoAppsIsHeldByEach, TestADeleteNamingAMovedRequestInCapitalsFindsIt: each fails under the change it guards (delete by the raw usage id, a derivation ignoring the app, no uuid normalisation).

Fixes AI-3477

@thesyncim
thesyncim force-pushed the fix/ai-3477-imported-usage-ids-derived branch from e5680c5 to 0397ea5 Compare November 23, 2026 11:04
@thesyncim thesyncim added the data-layer-review: ready Data layer review fix: passed automated review, merges cleanly, ready for a human review label Nov 23, 2026
@thesyncim
thesyncim marked this pull request as ready for review November 23, 2026 11:27
@thesyncim
thesyncim requested a review from kanat November 23, 2026 11:31
@thesyncim
thesyncim force-pushed the fix/ai-3477-imported-usage-ids-derived branch from 0397ea5 to e435def Compare November 23, 2026 11:34
@thesyncim
thesyncim force-pushed the fix/ai-3477-imported-usage-ids-derived branch from e435def to 58786fb Compare November 23, 2026 12:49

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewed #2189 at 58786fb (rebased onto main 2a62887; its code tree is the one tested). Touched suites pass there: TestDataMoveSuite, TestMeteringSuite. CI: green except integration (api) pending when read.

[Should fix] R1.3 acceleration/README.md:2773-2776 (not in the diff) still says a request row "is imported by its usage_id" and "a delete of it is replayed by its usage_id". After this PR both use an id made from the importing app and the sent id. Fix: update the paragraph to say so.

Overlaps: #2181 also edits identity() for requests (it sets billable = false). #2182 is a prerequisite, as the body says. A local three-way merge of this PR, #2181 and #2182 onto main is clean.

Checked and sound: every deterministic usage id (number months, 10DLC fees, knowledge storage, sandbox, STS, call legs, leases) is deduped only through requests.usage_id. So covering requests covers the imported pre-claim class. A derived id cannot be steered onto a deterministic one, because the hash forms differ and the sent value is a parsed uuid or integer. Insert and delete agree: the old insert and the old delete lookup each fail the new tests. The phone test fails with the old insert.

Verdict: request changes, for R1.1-R1.3.

Comment thread acceleration/internal/store/datamove.go Resolved
Comment thread acceleration/internal/store/datamove.go Resolved
Comment thread CHANGELOG.md Resolved
thesyncim added a commit that referenced this pull request Nov 23, 2026
…#2182)

**Problem**

`importRow` wrote any imported `phone_numbers` row, so a number bought
at a vendor became a row held by the importing customer. The release and
attach paths trust that row. The row also carried the source's line,
trunk and use case. It was billed a second time as well: `Rentals.Bill`
charged the months before its release here, although the source had
already billed them. And a row, or a replayed delete, naming the id of a
number bought here and still held could update or delete it.

**Fix**

- `importableNumber` now skips any row whose vendor is not exactly
`sip_trunk`, on import and on change replay, with no insert, no update
and no error. Such a row has nothing this deployment can use, and its
bills already move in `requests`. A customer that moves keeps a bought
number by buying or porting it at the destination. `SIP_TRUNK`,
`sip_trunk ` and an empty vendor count as bought numbers.
- A `sip_trunk` row is checked with `PhoneNumber.Validate`: E.164, a
vendor, and a cost that is not negative. #2181 leaves `phone_numbers` to
this PR. The check for a number another customer holds, `vendorKeys` and
`ErrNumberHeldElsewhere` only mattered for bought numbers, so they are
removed. The `released_at` override from the first commit is removed
too.
- The conflict `WHERE` in `importRow` and the conditions in `deleteRow`
now leave alone any row that was bought here and is still held, whatever
id it names.
- No imported number keeps its `dlc_use_case_id`.
- #2189 relies on this PR for the rental case.

**Tests**

Each test below was run on this commit and passes, and was run with
`datamove.go` and `phone_number.go` reset to the previous head, where it
fails.

- `TestAnImportedNumberNotOnItsOwnTrunkIsNotStored` covers telnyx,
`SIP_TRUNK`, `sip_trunk ` and an empty vendor, by import and by change.
Before the fix, each was stored.
- `TestAMovedBoughtNumberDoesNotArrive`: neither a held nor a released
bought number arrives. Before the fix, both did.
- `TestANumberBoughtHereIsNotWrittenOverByARowWithItsID` sends rows that
reuse the id, as telnyx, as `sip_trunk` and as released. The number
keeps its vendor, line and release state. Before the fix, it was
overwritten.
- `TestAReplayedDeleteLeavesANumberBoughtHere`: before the fix, the
number was deleted.
- `TestAnImportedNumberWithANegativeCostIsRefused`: before the fix, the
row was accepted.
- `TestAMovedCustomersBoughtNumberIsNotBilledAgainHere` (MeteringSuite)
runs `Rentals.Bill` after an import. Before the fix, a month was billed.
- `TestAnImportedNumberIsNeverGivenBackAtTheVendor` (AppsSuite): release
and attach of the imported number find nothing.
- The existing tests for number forms, other holders and replication now
use `sip_trunk` numbers, and the API tests show a bought row is not
stored and a malformed `sip_trunk` row is refused.

Fixes AI-3476
@thesyncim
thesyncim force-pushed the fix/ai-3477-imported-usage-ids-derived branch from 58786fb to c3c3799 Compare November 23, 2026 13:02
@thesyncim thesyncim removed the data-layer-review: ready Data layer review fix: passed automated review, merges cleanly, ready for a human review label Nov 23, 2026
@thesyncim
thesyncim force-pushed the fix/ai-3477-imported-usage-ids-derived branch from c3c3799 to 8b4f5ce Compare November 23, 2026 13:48
@thesyncim

Copy link
Copy Markdown
Member Author

On R1.3: rewrote that README paragraph. It now says how the imported usage id is made, that the original stays in source_usage_id, what happens when a row comes back, and how a delete in a change batch is found.

Heads-up on order: this adds shard migration 20270119000000, and #2195 (20270124…) and #2208 (20270125…) also add shard migrations. Goose refuses a migration older than one already applied, so they need to land in that order, or the later one gets renumbered.

…oyment's

An imported request no longer keeps the usage_id it was sent with. Its usage
id is made from the importing customer and the one sent (or the source id for
a row from before usage ids), on insert and when a replayed delete finds it,
so re-importing and replaying still name the same row and a fixed charge such
as a number's month is billed under its own usage id.
An import keeps the usage id a request had where it was first recorded as
requests.source_usage_id and makes the row's usage id from it, so a copy
moved on from a copy is the copy already there, and a row taken back where
it was first recorded keeps that usage id and is the row it came from.
Tests pin that a replayed delete leaves a request recorded here, that each
importing app holds its own copy, and that a usage id in capitals is the
same uuid.
@thesyncim
thesyncim force-pushed the fix/ai-3477-imported-usage-ids-derived branch from 8b4f5ce to bc9d1ca Compare November 23, 2026 13:54
@thesyncim

Copy link
Copy Markdown
Member Author

Update on the order: #2195 has merged, so I moved this PR's migration to 20270126000000, after #2195's and #2208's. That means #2208 needs to land before this one.

@thesyncim thesyncim added the data-layer-review: ready Data layer review fix: passed automated review, merges cleanly, ready for a human review label Nov 23, 2026
@thesyncim
thesyncim merged commit 51289e2 into main Nov 23, 2026
18 of 19 checks passed
@thesyncim
thesyncim deleted the fix/ai-3477-imported-usage-ids-derived branch November 23, 2026 14:53

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Delta review of #2189 at 4be1ded (rebased onto 16ab0c6). The PR was merged as 51289e2 while I ran this; its six files are identical to 4be1ded, so I ran the touched suites on main: TestDataMoveSuite and TestMeteringSuite pass. The previous release (f03b4a2) with the new migration passes its own TestDataMoveSuite and TestMigrat*. CI on the head: all 13 checks pass.

Round 1

  • R1.1 fixed. The three mutants (delete matches the raw id too, hash ignores the customer, delete without ::uuid) each fail one new test.
  • R1.2 fixed. A move A to B to A is one row (my probe from round 1 passes). Dropping the home check, ignoring the customer in it, ignoring the origin or not writing source_usage_id each fail a new test. One mutant survives: R2.2.
  • R1.3 fixed (README). R1.4 withdrawn (the CHANGELOG entry is gone).

Migration: ADD COLUMN nullable with no default, Down drops it: expand-only. Its version is newer than every shard migration on main (20270124000100) and in #2208 (20270125000000 to 000300). The previous release ignores the column.

Two new findings, inline: R2.1 and R2.2. Both need a small follow-up PR, as this one is merged.

Verdict: NO-GO on R2.1 and R2.2 (a follow-up, not a revert).


-- The usage id a request had where it was first recorded, kept by an import, which gives the row
-- a usage id of this deployment's: a row taken back where it was recorded is then known there.
ALTER TABLE requests ADD COLUMN IF NOT EXISTS source_usage_id uuid;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Should fix] R2.1 No SET LOCAL lock_timeout = '5s'; before the ALTER on requests, the hottest write table. A lock request that waits behind a long query queues every insert behind it. Main's 20270124000000_hash_call_tokens.sql starts with it, and #2208 adds TestEveryTransactionalMigrationAfterTheBaselineSetsALockTimeout, which fails on this file after that merge (I merged #2208 onto main: it reports starts with "ALTER TABLE requests ADD COLUMN ...", once activity_digests is fixed). Fix: put the SET LOCAL first in Up. With it the test passes here.

origin, importedUsageID("customer_id", "COALESCE("+origin+"::text, id::text)"))
if j := slices.Index(columns, "source_usage_id"); j >= 0 {
// Where the row was first recorded, however many moves ago.
picked[j] = origin

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Should fix] R2.2 A mutation survives the whole DataMoveSuite: picked[j] = "r.usage_id" (keep the sent usage id, not origin, as source_usage_id). Then a copy of a copy of a copy stores the first copy's derived id as its origin, and a row sent home after two hops lands twice. TestARequestMovedOnFromACopyIsOneRowWhereverItLands passes under it only by chance: it deletes the original, and the second hop then finds the copy by its derived id.

Ready row for DataMoveSuite (passes on head, fails under the mutant with 2 rows): home := s.takenRequest(s.source, id); s.move("acme", "acme"); import each row of exportFrom(s.destination, "acme") into s.destination as globex; import each row of exportFrom(s.destination, "globex") into s.source as acme; then exportFrom(s.source, "acme").of("requests") has 1 row with usage_id == home.UsageID.

thesyncim added a commit that referenced this pull request Nov 23, 2026
…d changes, and an import naming another customer's row is refused (#2221)

**Problem**
Forgetting an end user rewrote or deleted their rows but left the
changes `data_changes` had recorded of those rows, so `GET
/v1/data/changes` still served the user's id and the words of their
hidden messages until the retention prune. Separately, `importRow`
resolved a conflict on a table's key with an update guarded by who holds
the row, so an imported row whose `id` another customer already held
here was dropped without an error.

**Fix**
- `Requests.RenameUser` and `ForgetUserSettings` replace the user's id
with the replacement in every recorded change of the app's requests and
campaigns that names them, deleted rows' included, in the same statement
as the rewrite. A request recorded after the statement, which a later
forget-user run rewrites, keeps its change.
- `BranchMessages.DeleteUser` and `Sessions.Delete` turn the recorded
inserts and updates of the copies of hidden messages they delete into
deletes that carry nothing. The copy's own delete change stays, so a
move still removes it.
- Changes are rewritten in place, never deleted: `Changes` refuses a
cursor below the oldest change kept of any customer, so deleting one
would send other apps' followers back to a full copy.
- Changes of rows forget leaves in place (sessions, users, tasks) stay,
since the export carries those rows as they are.
- `importRow` returns `ErrAnotherCustomersRow` when it wrote nothing and
another customer holds the row's key. An import or an applied change
stops there with a 400 where it used to skip the row. Re-importing the
importer's own row still succeeds. A request is not refused this way:
since #2189 an imported request takes a usage id of this deployment's,
so it lands beside the other customer's row.

**Tests**
Each failed before its fix:
- `TestForgettingAUserRenamesThemInTheChangesRecordedOfTheirCampaigns`:
another app's change under the same campaign id and user id stays.
-
`TestForgettingAUserRenamesThemInTheChangesOfTheRequestsRewrittenAlone`:
a late request and a session keep their changes.
- `TestForgettingAUserRenamesThemInTheChangesOfACampaignDeletedBefore`
and `TestRenamingAUserRenamesThemInTheChangesOfARequestDeletedBefore`
- `TestForgettingAUserOfOneAppLeavesAnotherAppsFollowerWhereItWas`:
another app's follower is not expired.
- `TestForgettingAUserEmptiesTheChangesRecordedOfTheirCopies`: covers
the copy's delete change, change numbers and a call of the session.
-
`TestForgettingAUserAfterTheirSessionWasDeletedLeavesNoChangeOfItsCopies`
- `TestAnImportCannotOverwriteAnotherCustomersRow`, and
`TestAReplayedChangeCannotDeleteAnotherCustomersRow` for a replayed
insert.

These fail under a broken check rather than before the fix:
- `TestARequestWhoseIDsAnotherCustomerHoldsHereLandsBesideTheirs`
-
`TestALogTakenBackWhereItCameFromIsNotRefusedOverAnotherAppsLogWithItsCopysID`
- `TestReimportingTheImportersOwnRowsIsTheSameAsImportingThemOnce`

Part of AI-3485
kanat added a commit that referenced this pull request Nov 23, 2026
Test only, no code change. There is no production caller: the PR pins
code that is already on main.

## Problem

[#2189 round-2
review](#2189 (review)),
finding R2.2: mutant N3 survives the whole `DataMoveSuite` on main. N3
changes `picked[j] = origin` to `picked[j] = "r.usage_id"` at
`acceleration/internal/store/datamove.go:761`, the line that keeps the
first recorded usage id as `source_usage_id` of a copy. A request that
moves on twice and comes back (A -> B -> C -> A) is then two rows at A.

## Test

`TestARequestMovedOnTwiceAndBackIsOneRowWhereItWasRecorded`, next to
`TestARequestMovedOnFromACopyIsOneRowWhereverItLands`:

```
source acme (A) --move--> destination acme (B) --import--> destination globex (C) --import--> source acme (A)
```

Expected: one row at A, with the usage id it had first. The request id
is random (`crypto/rand`).

## Mutation

| Mutant | Result |
| --- | --- |
| N3: `picked[j] = "r.usage_id"` (datamove.go:761) | the test fails with
2 rows (expected 1); restored |

`go test -tags integration ./internal/store/ -run TestDataMoveSuite`:
pass on the head (33 s).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

data-layer-review: ready Data layer review fix: passed automated review, merges cleanly, ready for a human review docs project-info

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants