Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions acceleration/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2771,9 +2771,13 @@ so an export is the caller's own data and an import lands under the caller's own
however the file was edited on the way. An import upserts and refuses a row whose primary
key belongs to another tenant, so replaying the same change twice lands where applying it
once would and a guessed id overwrites nothing. A request row is the exception: each
deployment numbers its own, so it is imported by its `usage_id` with an id the destination
gives it, written once, and a delete of it is replayed by its `usage_id`, or for a row from
before usage ids by the one its import made from its source id.
deployment numbers its own, so it is imported with an id the destination gives it, under a
`usage_id` made from the importing app and the `usage_id` the row had where it was first
recorded (its source id, for a row from before usage ids), and written once. It keeps that
first `usage_id` as `source_usage_id`, so the row is written once wherever it moves, and a
row taken back where it was first recorded is the row it was copied from. A delete of it in a
change batch is found by the `usage_id` made from the one the change names, and never removes
a request this deployment recorded itself.

Key rows, sealed secrets, OAuth access and refresh tokens, organizations and apps are not
exported. A moved deployment mints its own keys and re-authorizes its plugin connections.
Expand Down
52 changes: 52 additions & 0 deletions acceleration/internal/phone/metering_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
"github.com/GetStream/Vision-Agents/acceleration/internal/store"
"github.com/GetStream/Vision-Agents/acceleration/internal/testenv"
"github.com/GetStream/Vision-Agents/acceleration/internal/testenv/redisready"
"github.com/GetStream/Vision-Agents/acceleration/internal/usage"
"github.com/GetStream/Vision-Agents/acceleration/prices"
)

Expand Down Expand Up @@ -821,6 +822,57 @@ func (s *MeteringSuite) TestANumberIsBilledEachMonthAfterTheOneItWasBoughtIn() {
s.Len(s.rows(ModelNumber), 2, "a number released is not billed again")
}

func (s *MeteringSuite) TestAnImportedRequestNamingANumbersComingMonthDoesNotStopItBeingBilled() {
s.Require().NoError(s.store.PhoneNumbers.Release(s.ctx, s.customer, s.e164, s.clock.now()))
bought, err := s.service.Buy(s.ctx, Purchase{Vendor: s.vendor.vendor, E164: aNumber(), Owner: s.owner()})
s.Require().NoError(err)
s.row(ModelNumber)
next := monthAfter(bought.PurchasedAt, 1)
month := routing.UsageID("number", bought.Vendor, bought.E164,
strconv.FormatInt(bought.PurchasedAt.UTC().UnixMicro(), 10), next.Format("2006-01"))

// A request row as an export carries it, sent with the usage id of the number's next month.
other := "customer-" + uuid.NewString()
s.Require().NoError(s.store.Requests.Insert(s.ctx, &store.Request{UsageID: uuid.Must(uuid.NewV7()), CustomerID: other,
Modality: string(routing.Phone), Provider: s.vendor.vendor, Model: ModelNumber, StartedAt: next, Success: true}))
var row map[string]any
_, err = s.store.ExportCustomer(s.ctx, other, func(table string, encoded json.RawMessage) error {
if table == "requests" {
return json.Unmarshal(encoded, &row)
}
return nil
})
s.Require().NoError(err)
s.Require().NotNil(row)
row["usage_id"] = month.String()
encoded, err := json.Marshal(row)
s.Require().NoError(err)
s.Require().NoError(s.store.ImportRow(s.ctx, s.customer, "requests", encoded))
s.Require().NoError(s.store.ImportRow(s.ctx, s.customer, "requests", encoded))

// Rows written to ship to a usage service that is not there, so they stay to be shipped.
client, err := usage.NewClient(usage.ClientOptions{URL: "http://127.0.0.1:1", Token: "token"})
s.Require().NoError(err)
writer := routing.NewWriter(routing.WriterOptions{Store: s.store, Usage: client, Logger: slog.New(slog.DiscardHandler)})
s.T().Cleanup(func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
writer.Close(ctx)
})
recorder := routing.NewRecorderOn(routing.Phone, writer, s.prices, slog.New(slog.DiscardHandler))
_, err = Rentals{Store: s.store, Recorder: recorder, Logger: slog.New(slog.DiscardHandler)}.
Bill(s.ctx, bought.PurchasedAt.Add(-time.Hour), next.Add(time.Hour))
s.Require().NoError(err)

s.Require().Eventually(func() bool {
var billed []store.Request
s.Require().NoError(s.store.ShardDB().NewSelect().Model(&billed).
Where("customer_id = ?", s.customer).Where("usage_id = ?", month).Scan(s.ctx))
return len(billed) == 1 && billed[0].Billable && billed[0].ToShip && billed[0].APIKey == OriginNumberRental
}, 5*time.Second, 25*time.Millisecond, "the number's next month is billed")
s.Len(s.rows(ModelNumber), 3, "the month it was bought in, the next one, and the imported row once")
}

func (s *MeteringSuite) TestAMonthThatBeganBeforeFromIsNeverBilled() {
now := time.Now().UTC().Truncate(time.Second)
e164 := aNumber()
Expand Down
34 changes: 22 additions & 12 deletions acceleration/internal/store/datamove.go
Original file line number Diff line number Diff line change
Expand Up @@ -747,10 +747,19 @@ func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table str
quoted := strings.Join(columns, ", ")
picked := slices.Clone(columns)
if i := slices.Index(columns, "usage_id"); spec.name == "requests" && i >= 0 {
// A row from before usage ids has none, and the table refuses a new row without one.
// Its usage id is made from the source's id for it, so importing it again names the
// same unit of work.
picked[i] = "COALESCE(usage_id, " + importedUsageID("customer_id", "id") + ")"
// The usage id is this deployment's, made from the one the row had where it was first
// recorded, or from the source's id for a row from before usage ids. A usage id names a
// unit of work this deployment bills, such as a month of a number, so the one sent is
// not kept. Importing the row again, from wherever it moved since, names the same row.
// A row taken back where it was first recorded is that row again: one this customer
// already holds here names no charge still to come.
origin := "COALESCE(r.source_usage_id, r.usage_id)"
picked[i] = fmt.Sprintf("CASE WHEN EXISTS (SELECT 1 FROM requests AS h WHERE h.usage_id = %[1]s AND h.customer_id = r.customer_id) THEN %[1]s ELSE %[2]s END",
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.

}
}
if i := slices.Index(columns, spec.copied); spec.copied != "" && i >= 0 {
// The source's id, whatever the source kept as the id of where the row came from.
Expand Down Expand Up @@ -1546,9 +1555,9 @@ func (t dataTable) captured(s shape) []string {
return s.keys
}

// importedUsageID is the usage id a request from before usage ids is imported under, as SQL,
// made from the customer importing it and its id in the source, so importing it again and
// replaying its delete name the same row.
// importedUsageID is the usage id a request is imported under, as SQL, made from the customer
// importing it and the request's usage id where it was first recorded (its id in the source, for
// one from before usage ids), so importing it again and replaying its delete name the same row.
func importedUsageID(customer, sourceID string) string {
return fmt.Sprintf("md5('import:' || %s || ':' || %s)::uuid", customer, sourceID)
}
Expand Down Expand Up @@ -1725,11 +1734,12 @@ func (s *Store) deleteRow(ctx context.Context, db bun.IDB, customerID string, ch
var conditions []string
var args []any
if spec.across != "" {
// Never by the id, which names another row here. A row from before usage ids has none,
// and was imported under one made from its source id, which the change carries too.
conditions = append(conditions, fmt.Sprintf("t.%s = COALESCE((?::jsonb ->> '%s')::uuid, %s)",
spec.across, spec.across, importedUsageID("?::text", "(?::jsonb ->> 'id')")))
args = append(args, string(change.Key), customerID, string(change.Key))
// Never by the id, which names another row here: by the usage id the row was imported
// under, made from the one the change carries, or from its source id for a row from
// before usage ids.
conditions = append(conditions, fmt.Sprintf("t.%s = %s", spec.across, importedUsageID("?::text",
Comment thread
thesyncim marked this conversation as resolved.
Resolved
fmt.Sprintf("COALESCE((?::jsonb ->> '%s')::uuid::text, ?::jsonb ->> 'id')", spec.across))))
args = append(args, customerID, string(change.Key), string(change.Key))
} else if spec.copied != "" {
// Never by the id either: by the source's id, which a copied row keeps. A row copied
// before the copied column holds none and is left, as the id it holds may as well be
Expand Down
89 changes: 84 additions & 5 deletions acceleration/internal/store/datamove_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3516,16 +3516,18 @@ func (s *DataMoveSuite) TestARequestFromBeforeUsageIDsIsImportedWithTheSameIDEve
s.Equal(first["usage_id"], again["usage_id"], "importing it again names the same unit of work")
}

func (s *DataMoveSuite) TestAnImportedRequestKeepsItsUsageIDAndIsNeverShipped() {
func (s *DataMoveSuite) TestAnImportedRequestIsGivenAUsageIDOfItsOwnAndIsNeverShipped() {
usageID := uuid.Must(uuid.NewV7())
shippedAt := time.Now().UTC().Add(-time.Minute)
s.Require().NoError(s.source.Requests.Insert(s.ctx, &Request{UsageID: usageID, Modality: "stt", CustomerID: "acme",
Provider: "deepgram", Model: "flux", StartedAt: time.Now().UTC(), Success: true, ToShip: true,
ShippedAt: &shippedAt, ShipError: "missing_api_key"}))

moved := s.movedRequest(false)
again := s.movedRequest(false)

s.Equal(usageID.String(), moved["usage_id"])
s.NotEqual(usageID.String(), moved["usage_id"], "the usage id sent names a unit of work of the source's")
s.Equal(moved["usage_id"], again["usage_id"], "importing it again names the same row")
s.Equal(false, moved["to_ship"], "the deployment that recorded it bills it")
s.Nil(moved["shipped_at"], "what the other deployment's usage service answered stays there")
s.Equal("", moved["ship_error"])
Expand Down Expand Up @@ -3572,8 +3574,12 @@ func (s *DataMoveSuite) TestAMovedRequestNeverOverwritesTheDestinationsRowWithIt
s.Require().Len(rows, 2, "the moved row beside the destination's own, once however often it is imported")
s.EqualValues(id, rows[own.UsageID.String()]["id"])
s.Equal(true, rows[own.UsageID.String()]["to_ship"], "the destination's own row is left as it was")
s.NotEqualValues(id, rows[moved.UsageID.String()]["id"], "the moved row is given an id of the destination's")
s.Equal(false, rows[moved.UsageID.String()]["to_ship"])
delete(rows, own.UsageID.String())
s.NotContains(rows, moved.UsageID.String(), "the moved row is given a usage id of the destination's")
for _, row := range rows {
s.NotEqualValues(id, row["id"], "the moved row is given an id of the destination's")
s.Equal(false, row["to_ship"])
}
}

func (s *DataMoveSuite) TestADeletedRequestIsReplayedByItsUsageID() {
Expand All @@ -3594,7 +3600,7 @@ func (s *DataMoveSuite) TestADeletedRequestIsReplayedByItsUsageID() {
s.Require().NoError(s.destination.ApplyChanges(s.ctx, "acme", changes))

rows := s.requestsByUsage()
s.NotContains(rows, doomed.UsageID.String())
s.Len(rows, 1, "the moved row is deleted")
s.Contains(rows, own.UsageID.String(), "the destination's row with the deleted row's id is not the row deleted")
}

Expand All @@ -3616,6 +3622,79 @@ func (s *DataMoveSuite) TestADeletedRequestFromBeforeUsageIDsIsReplayedToo() {
s.Contains(rows, kept.UsageID.String())
}

func (s *DataMoveSuite) TestADeleteNamingARequestRecordedHereLeavesIt() {
id := time.Now().UnixNano() % 1_000_000_000_000
own := s.takenRequest(s.destination, id)

key := fmt.Sprintf(`{"usage_id": %q, "id": %d}`, own.UsageID, id)
s.Require().NoError(s.destination.ApplyChanges(s.ctx, "acme", []DataChange{
{Table: "requests", Op: ChangeDelete, Key: json.RawMessage(key)},
}))

s.Contains(s.requestsByUsage(), own.UsageID.String(), "a replayed delete names a moved row, never one recorded here")
}

func (s *DataMoveSuite) TestARequestImportedByTwoAppsIsHeldByEach() {
s.takenRequest(s.source, time.Now().UnixNano()%1_000_000_000_000)
exported := s.export("acme").of("requests")
s.Require().Len(exported, 1)
encoded, err := json.Marshal(exported[0])
s.Require().NoError(err)

s.Require().NoError(s.destination.ImportRow(s.ctx, "acme", "requests", encoded))
s.Require().NoError(s.destination.ImportRow(s.ctx, "globex", "requests", encoded))

s.Len(s.exportFrom(s.destination, "globex").of("requests"), 1, "the usage id is made from the app importing the row")
}

func (s *DataMoveSuite) TestADeleteNamingAMovedRequestInCapitalsFindsIt() {
id := time.Now().UnixNano() % 1_000_000_000_000
moved := s.takenRequest(s.source, id)
s.move("acme", "acme")
s.Require().Len(s.requestsByUsage(), 1)

key := fmt.Sprintf(`{"usage_id": %q, "id": %d}`, strings.ToUpper(moved.UsageID.String()), id)
s.Require().NoError(s.destination.ApplyChanges(s.ctx, "acme", []DataChange{
{Table: "requests", Op: ChangeDelete, Key: json.RawMessage(key)},
}))

s.Empty(s.requestsByUsage(), "a usage id is the same uuid however it is written")
}

func (s *DataMoveSuite) TestARequestMovedBackIsOneRowWhereItWasRecorded() {
home := s.takenRequest(s.source, time.Now().UnixNano()%1_000_000_000_000)
s.move("acme", "acme")

for _, row := range s.exportFrom(s.destination, "acme").of("requests") {
encoded, err := json.Marshal(row)
s.Require().NoError(err)
s.Require().NoError(s.source.ImportRow(s.ctx, "acme", "requests", encoded))
s.Require().NoError(s.source.ImportRow(s.ctx, "globex", "requests", encoded))
}

rows := s.exportFrom(s.source, "acme").of("requests")
s.Require().Len(rows, 1, "the moved copy is the row it was copied from")
s.Equal(home.UsageID.String(), rows[0]["usage_id"])
s.Len(s.exportFrom(s.source, "globex").of("requests"), 1, "another app's import of it is a row of that app's")
}

func (s *DataMoveSuite) TestARequestMovedOnFromACopyIsOneRowWhereverItLands() {
id := time.Now().UnixNano() % 1_000_000_000_000
s.takenRequest(s.source, id)
s.move("acme", "acme")
_, err := s.source.ShardDB().ExecContext(s.ctx, "DELETE FROM requests WHERE id = ?", id)
s.Require().NoError(err)
for _, row := range s.exportFrom(s.destination, "acme").of("requests") {
encoded, err := json.Marshal(row)
s.Require().NoError(err)
s.Require().NoError(s.source.ImportRow(s.ctx, "acme", "requests", encoded))
}

s.move("acme", "acme")

s.Len(s.requestsByUsage(), 1, "a copy of a copy is the copy already here")
}

// drewNothing restarts the sequence behind a column, so the store has drawn nothing from it yet.
// A truncate leaves sequences where they were, and the databases outlive a run.
func (s *DataMoveSuite) drewNothing(store *Store, table, column string) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
-- +goose Up

-- 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.


-- +goose Down
ALTER TABLE requests DROP COLUMN IF EXISTS source_usage_id;
1 change: 1 addition & 0 deletions acceleration/schema/shard.sql
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,7 @@ TABLE requests
ship_error text NOT NULL DEFAULT ''::text
shipped_at timestamp with time zone
sku text NOT NULL DEFAULT ''::text
source_usage_id uuid
started_at timestamp with time zone NOT NULL
success boolean NOT NULL
tags jsonb NOT NULL DEFAULT '{}'::jsonb
Expand Down
Loading