Repository navigation
fix(metrics): keep each account's metrics apart - #955
Conversation
The metrics table had no account column on any backend, so two accounts that each had a table of the same name wrote to one row, and the counts and latencies /metrics reported for that name were the two tables' added together. Every metric of a request, and the TTL metrics of a table, now carry the account they were recorded for: the collector's key, the flushed bucket and the stored row have an account, and /metrics reports it as an AccountId dimension and takes an account_id filter. Metrics of the whole deployment (pool, worker, storage query, backup jobs) have none. Migration 10, account_metrics, replaces the catalog's metrics table (a collection on MongoDB) with account_metrics, whose key has the account, on every backend. A partition key cannot be changed on Cassandra and a primary key cannot be altered on SQLite, so the table is new everywhere. The old rows carry no account and are dropped. The migration is breaking and convergent. MetricsStore::query_metrics takes a MetricsFilter (account, table name, metric). extenddb_storage::metrics_conformance checks each backend's store against a migrated catalog. Part of #728.
LeeroyHannigan
left a comment
There was a problem hiding this comment.
I read the change against main at 9c3fbfb. I ran nothing, so each point below comes from reading the code. CI passes apart from CodeQL, which fails on the new alert at metrics_pages_tests.rs:182.
After this change the feed returns one row per account. The console's Raw Metrics table (metrics_content.rs:109 and :180) shows only Metric, Table and Operation. Two accounts' rows for Orders therefore show as two rows with the same labels and different sums. The charts sum the rows of each timestamp, which adds the accounts together, and the table prints each row as it arrives. Please add an Account column from the AccountId dimension, or sum the rows of one table name as the charts do.
docs/manuals/07-upgrade-manual.md:983, in the v0.1.15 entry on the admin-only dashboard, still says "The metrics table has no account column". The new v0.1.15 entry at line 369 says the opposite. Please put that sentence in the past tense, for example "Before migration 10 the metrics table had no account column".
| pub(super) struct SegmentPoint { | ||
| pub(super) operation: String, | ||
| #[allow(dead_code)] // TODO(cleanup): used when console adds per-account latency breakdown | ||
| pub(super) account_id: String, |
There was a problem hiding this comment.
/metrics?account_id=X reads only X's rows from the store. render_metrics then sets segments from query_segments(window), which takes no account, and the console feed at metrics_pages.rs:143 does the same. The filtered response carries the request count and the average auth, authz, throttle, dispatch and response latencies per operation of every account. The upgrade manual at line 369 says the parameter "returns one account's metrics only". The design doc (06-component-server.md:315) says "only the metrics of this account". record_segments sets this field, and nothing reads it. Please filter the segment points by account in query_segments, with a test that records segments for two accounts and reads one. test_the_account_filter_returns_that_accounts_rows_only could check segments too. If segments should stay deployment-wide, please say so in both docs and drop this field.
There was a problem hiding this comment.
Fixed in 3ec94e1. query_segments takes the account and keeps that account's points only; /metrics and /console/metrics-data pass account_id to it, and an empty one is no filter. segments_are_filtered_by_account records segments for two accounts and reads each, and test_the_account_filter_applies_to_the_latency_segments checks that the first account's segments have no Scan, which only the second account sent. With the filter removed from query_segments, the unit test fails.
| want_first.sort_by(|a, b| format!("{a:?}").cmp(&format!("{b:?}"))); | ||
| assert_eq!(first_only, want_first, "the first account's rows"); | ||
|
|
||
| // Every filter together. |
There was a problem hiding this comment.
This read still passes if a store drops its table filter or its metric filter. The second account has one row, for Orders and ConsumedWriteCapacityUnits, and those two filters keep it anyway. This PR rewrote the table and metric filters in all four stores, and this module is the only store-level test of them. Please give the second account a row under another table name and a row under another metric, so this read has rows to exclude. A read with only table_name and one with only metric would test each filter alone.
There was a problem hiding this comment.
Fixed in 5a44c5c. The second account also has a row under Other and a row under UserErrors, and the check reads with the table filter alone and the metric filter alone. With either filter removed from the SQLite query, the check fails on that read.
| state.metrics.record( | ||
| extenddb_core::metrics::MetricName::ConsumedReadCapacityUnits, | ||
| m.read_capacity_units, | ||
| Some(&ctx.account_id), |
There was a problem hiding this comment.
Only PutItem's write capacity has a test of the account the handler records, in test_metrics_accounts.py. By my reading, no test fails if this line passes None, or if the handler passes "" to record_latency, record_request_count or record_error_metrics. Nothing in the tests calls handle_request. The TTL metrics have no test of their account, and record_ttl_deletion(table_name, table_name) compiles because both parameters are &str. Please add a test that sends requests for two accounts through the router and checks the AccountId of each metric the handler records. Please also add a TTL test on one backend that checks the account of TimeToLiveDeletedItemCount.
There was a problem hiding this comment.
In 3ec94e1 test_metrics_accounts.py sends, as each account, a PutItem, a GetItem, a Query, a DeleteItem whose condition fails and a GetItem on a missing table, and puts an expired item for the TTL sweep. It checks the AccountId of read and write capacity, returned items and bytes, failed conditions, UserErrors, RequestCount, the latency count and TimeToLiveDeletedItemCount. The wire suites run it on all four backends. Against a rebuilt SQLite server, it fails with this line passing None, and with the SQLite TTL worker passing "" to record_ttl_deletion. every_scoped_recorder_keeps_its_account covers each of the 14 per-account recorders, and the record_error_metrics tests now check the account on SystemErrors, failed conditions and TransactionConflict. I did not add a router-level Rust test, and the throttle site has no test.
| pub struct MetricsRow { | ||
| pub bucket: time::OffsetDateTime, | ||
| /// The account the row was recorded for; `None` for a metric of the | ||
| /// whole deployment. Stored as the empty string. |
There was a problem hiding this comment.
On MongoDB a deployment metric has no account_id field, because management_store.rs:2166 inserts it only for Some. "Stored as the empty string" holds on SQLite, PostgreSQL and Cassandra. Please say that the field is absent on MongoDB, here and in the PR body.
There was a problem hiding this comment.
Fixed in 5a44c5c: the comment says that the field is empty on SQLite, PostgreSQL and Cassandra and absent on MongoDB. The PR body says the same.
| PRIMARY KEY (bucket, account_id, metric, table_name, index_name, operation) | ||
| ); | ||
|
|
||
| CREATE INDEX IF NOT EXISTS idx_account_metrics_bucket ON account_metrics (bucket); |
There was a problem hiding this comment.
The primary key starts with bucket, so its index already serves the bucket >= ? AND bucket <= ? read and the prune's bucket < ?. This index is a second B-tree that each flush also writes. The PostgreSQL body has the same index at line 26. The table is new, so dropping the index now needs no later migration. Please drop it from both bodies and the schema dumps, or say in the comment which query needs it.
| ); | ||
| assert!( | ||
| accounts.contains(&account), | ||
| "admin feed lacks the account of {table}: {accounts:?}" |
There was a problem hiding this comment.
CodeQL fails on this message (alert 219, rust/cleartext-logging) because it prints account ids. The ids are the made-up values in TABLES, so the message logs nothing sensitive. Please drop {accounts:?} from the message, so main does not carry the alert after the merge.
There was a problem hiding this comment.
Fixed in 3ec94e1: the message no longer prints the ids. The two other alerts on this PR, in the SQLite migration test, are fixed the same commit: the test inserts with a literal statement.
Review of #955: - The latency segments of /metrics and /console/metrics-data take the account_id filter: query_segments keeps the requests of that account only. Before, a response filtered by account still held every account's per-operation counts and latencies. - The console's raw metrics table has an Account column. - An empty account_id is no filter in the in-memory collector, as in the stores. - The named record_* methods move to collector_record.rs, keeping collector.rs under the 500-line limit. - Tests: every one of the 14 per-account recorders keeps its account; segments are filtered by account; SystemErrors, failed conditions and transaction conflicts carry the account. The store check gives its deployment row a key of its own run, and checks that two inserts of one key add up and that the prune deletes an old row (not on Cassandra, which overwrites and expires by TTL). The wire test sends a GetItem, a Query, a Scan, a failed condition and a request on a missing table as each account, puts an expired item for the TTL sweep, and waits for the PutItem sums to reach their final values; it checks the account on each metric, the TTL deletions and the filtered segments. The MongoDB metrics store test runs with EXTENDDB_TEST_MONGODB_REQUIRED in CI. - Docs: the account is part of the row key on SQLite, PostgreSQL and Cassandra; on MongoDB each document records it. AccountId is ExtendDB's own dimension. The storage query metrics carry no account. Dropping metrics on Cassandra keeps a snapshot when auto_snapshot is on. Stale text about the metrics table having no account is updated. Part of #728.
Review of #955: - The store check gives the second account a row under another table name and a row under another metric, and reads with the table filter alone and the metric filter alone, so a store that ignored either filter fails it. - account_metrics has no separate bucket index on SQLite and PostgreSQL: the primary key starts with bucket, so its index serves the range reads and the prune. - MetricsRow says that a deployment row has no account_id field on MongoDB. Part of #728.
|
3ec94e1 and 5a44c5c address the review. The Raw Metrics table has an Account column, read from the |
LeeroyHannigan
left a comment
There was a problem hiding this comment.
I checked the round-1 items against 3ec94e1 and 5a44c5c, by reading the code this round. The two commits fix seven of the eight. For the handler comment, each metric the handler records with an account now has a test, except the three throttle metrics (handler.rs:234). CodeQL shows no open alert on this PR now. The other comment is on text the new commits rewrote.
| state.metrics.record( | ||
| metric, | ||
| 1.0, | ||
| Some(&ctx.account_id), |
There was a problem hiding this comment.
ReadThrottleEvents, WriteThrottleEvents and ThrottledRequests still have no account check. Line 369 of the upgrade manual now lists throttles among the metrics that carry the account. No test fails if this line or line 242 passes None. tests/rust/src/capacity_throttling.rs already throttles a table provisioned with 1 write capacity unit by sending 50 PutItems. Please give each account in test_metrics_accounts.py such a table, write to it until the first ProvisionedThroughputExceededException, and check the AccountId of WriteThrottleEvents and ThrottledRequests.
There was a problem hiding this comment.
Fixed in 4d8eb8d. Each account gets a table provisioned with one write capacity unit and sends PutItems to it until one answers ProvisionedThroughputExceededException; test_each_throttle_metric_names_its_account checks that WriteThrottleEvents and ThrottledRequests under that table have a row for each account. Against a rebuilt SQLite server with throttling_enabled on, the fixture fails with line 234 passing None, and again with line 242 passing None. ReadThrottleEvents comes from the same record call as WriteThrottleEvents, and the test sends no read that throttles.
|
|
||
| ### v0.1.15: metrics carry their account (catalog migration required) | ||
|
|
||
| **What changed.** The metrics of a request that have a table or an operation dimension (capacity, latency, errors, throttles, returned items and bytes, `RequestCount`), and the TTL metrics of a table, now carry the account they were recorded for. The catalog stores the account with each metrics row (migration 10, `account_metrics`), so two accounts that each have a table of the same name keep their own rows: before this release they wrote to one row, and the counts and latencies `/metrics` reported for that name were the two tables' added together. `/metrics` and the console's `/console/metrics-data` report the account as an `AccountId` dimension, beside `TableName`, `GlobalSecondaryIndexName` and `Operation`, and `/metrics` takes an `account_id` query parameter that returns one account's metrics only. Metrics of the whole deployment, such as the connection pool, worker, storage query and backup job metrics, have no `AccountId` dimension, and the `account_id` filter leaves them out. The filter also applies to the latency `segments` of the response. `AccountId` is ExtendDB's own dimension, not one of CloudWatch's DynamoDB dimensions. The console dashboard still serves admin sessions only and shows every account's metrics: its raw metrics table names each row's account, and its charts add the accounts together. |
There was a problem hiding this comment.
The handler records StorageQueryCount and StorageQueryLatency for each request, with the query category as their Operation dimension, and they carry no account. The rule at the start of this paragraph, "metrics of a request that have a table or an operation dimension", includes them. A later sentence lists them among the deployment's metrics. Please drop "that have a table or an operation dimension", so the list in parentheses names the metrics that carry the account.
There was a problem hiding this comment.
Fixed in 4d8eb8d: the sentence now reads "The metrics of a request (capacity, latency, errors, throttles, returned items and bytes, RequestCount), and the TTL metrics of a table, now carry the account".
Review of #955: - test_metrics_accounts.py gives each account a table provisioned with one write capacity unit and writes to it until a PutItem is throttled, then checks the AccountId of WriteThrottleEvents and ThrottledRequests under that table. - The upgrade manual's list of the request metrics that carry the account no longer has a qualifier that also covered the storage query metrics, which carry none. Part of #728.
LeeroyHannigan
left a comment
There was a problem hiding this comment.
I checked 4d8eb8d against the two comments. Each account now sends PutItems to a table with one write capacity unit until the server throttles one. test_each_throttle_metric_names_its_account then checks the account of WriteThrottleEvents and ThrottledRequests, and ReadThrottleEvents comes from the same record call at handler.rs:231. The test passes in the wire jobs of all four backends. The upgrade manual sentence now lists the metrics without the rule.
Main at a55b2b6 adds #955, whose catalog migration 10, account_metrics, applies on all four backends. This branch had also taken 10, for attribute_name_escape. Main keeps 10, and attribute_name_escape is now migration 11 on every backend. These files conflicted: - crates/storage/src/migrations/registry.rs: AccountMetrics = 10 comes first, then AttributeNameEscape = 11. The RELEASED_THROUGH comment now says the v1.0 release PR raises it to 11. - crates/storage-postgres/src/migrations/mod.rs: both arms stay, and both ids are in the transactional arm of runs_in(). The arm now names the module m0011_attribute_name_escape. - crates/storage-sqlite/src/migrations/mod.rs, crates/storage-cassandra/src/migrations/mod.rs and crates/storage-mongodb/src/migrations/mod.rs: main's account_metrics arm comes first, then this branch's not applicable arm for migration 11. - crates/storage-mongodb/tests/migrations_fresh.rs: a fresh store records 10 as applied and 11 as not applicable. On a reconverge, 10 runs again and 11 does not apply. The rows that stand for a later binary's migration move to id 12, and the LATEST assertion expects 11. - CONTRIBUTING.md: the table_note example moves to 12, the next free id. Its runs_in() arm lists both new ids. - docs/manuals/07-upgrade-manual.md: main's migration 10 paragraph comes first, then this branch's paragraph as migration 11. The other places that named this branch's migration 10 now say 11: - The PostgreSQL module is renamed m0011_attribute_name_escape.rs. Its SOURCE, FINGERPRINT and doc comment name 11. - The golden fixture is renamed 0011_attribute_name_escape.txt. The tests in migrations_name_escape.rs read the ledger notes of 11 and expect "Skipped 11 attribute_name_escape". Their test names and scratch database names say 11. - The doc comment of catalog_json.rs names migration 11. - The upgrade manual lists migrations 1 to 11 and calls 1 to 7 and 9 to 11 breaking. Its step 4 paragraph calls the rewrite migration 11. - docs/differences-from-dynamodb.md names catalog migration 11. The step counts and the sample output now reflect 11 migrations: - MongoDB's migrations_locks.rs expects 12 steps, and migrations_released.rs expects 12 pending steps on a released catalog. - The sample output in docs/getting-started.md and manuals 04, 08 and 09 shows catalog migration 11. - The example in docs/manuals/05-admin-guide.md is a catalog at migration 10 that needs migration 11. Against main, the merged tree changes the same 44 files, with the same line counts, as this branch did against its merge base. Signed-off-by: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com>
Main took #955, which adds catalog migration 10, account_metrics, on every backend. This branch's migration, unique_access_key_ids, moves to id 11. The merge changes these to match: - The registry entry, the MongoDB code body (now m0011_unique_access_key_ids.rs), its fingerprint and its golden file. - The MongoDB test step lists, step counts and LATEST, and the ledger rows that stand for a later binary, now id 12. - The names and database tags of this migration's MongoDB tests. The two tests that stop just before this migration now migrate through migration 10. - The upgrade manual, the admin guide example and the sample output lines that name the latest migration. - CONTRIBUTING's worked example, which moves to migration 12. Signed-off-by: Lee Hannigan <29015211+LeeroyHannigan@users.noreply.github.com>
… main changed Main and this branch each changed interfaces the other side's code calls, in files the merge joined without a conflict. MetricsCollector::record takes the account on main (#955). The three bulk metrics pass the operation's account. The start handler reads it from the record, and record_finished_metrics takes it from the runner's record. DataEngine::put_item takes the row marker on this branch. Nine test calls on main pass None. They sit in the SQLite stream lifecycle tests, in three PostgreSQL stream and catalog tests, and in four Cassandra direct tests. The Scripted double of the batch write tests and the Fake of the backup tests take the marker in put_item. Both get put_items_batch, bulk_row_outcome and delete_bulk_row_outcomes through their unused() helper. OperationContext has item_authorizer from main and bulk, bulk_authorizer, bulk_principal and metrics from this branch. Five contexts on main set the four fields. They are the PartiQL test context and snapshot rebuild, the private modes test, the SQLite restore resume test and the PostgreSQL catalog NUL jobs test. The bulk handler and retention tests set item_authorizer. BackupCatalog, LegacyBackupReader and StorageEngine grew on main (#740, #825, #880, #900). BulkUnsupportedStorage and FaultingStorage, the two delegating doubles of the bulk tests, pass the new BackupCatalog and LegacyBackupReader methods to their inner engine. remove_backup_row passes its four parameters. They implement RestoreEngine the same way. check_user_authorization takes the action string on this branch. The Arn value test on main passes dynamodb:GetItem. AuthorizationStore::fetch_user_group_policies returns group and document pairs on main (#692). The two bulk authorization doubles return that type. The bulk authorization AppState sets request_timeout (#355) to the 30 second default. The PutItem comment names validate_put_payload, which replaced validate_put_item on this branch. rustfmt formats the banner tests and the new test code.
MetricsCollector::record takes the account since #955. record_partial_batch_throttle now takes the account of the request and records both metrics under it, as the throttle records of the bucket do. Its tests query the metrics by that account. The storage traits changed on feat/throttling-reasons. BackupEngine is gone, and StorageEngine requires BackupCatalog, LegacyBackupReader, RestoreEngine and SnapshotEngine. get_stream_records takes the stream ARN. The test double of crates/engine/tests/batch_partial.rs implements the four traits with stubs that the tests never reach, as it did for BackupEngine. It also takes the new parameter. OperationContext has a backup runtime and an item authorizer, and the test context sets a runtime with one job slot and no authorizer. In crates/engine/src/backup.rs the merge put the service_error_tests module after the modules that feat/throttling-reasons added. rustfmt orders that list by name, so the commit moves the module into its place.
…etric table feat/console-tabs brings three changes from main that the moved throttle segment and its tests did not build against. MetricsCollector::record takes the account since #955. Since #922 the throttle metrics use the metric table name. That name reduces an ARN to its table name and leaves out a name that fails the table name rules. GsiDescription has the warm_throughput and warm_throughput_record fields. throttle_segment::check now takes the metric table and records ReadThrottleEvents, WriteThrottleEvents and ThrottledRequests under the account and that table, as the segment did before the move. The index dimension of the throttle events stays as this branch made it. The index read wire test expects the account dimension that every record carries now. The GsiDescription of the helper tests sets both warm throughput fields to None.
The server design doc said that the server records ThrottledRequests per table and operation only. Since #955, every metric also carries the account. The sentence now says that ThrottledRequests carries no index dimension, as the service publishes it per table and operation.
… once The deployment guide gave about 190 bytes per request for every release through 1.0.0. That is the 0.1.12 and 0.1.13 figure. 0.1.15 added the account id to each segment record (#955). The harness on the merge-base measured 248 bytes per point and 252 per later request. The guide now gives 190 bytes through 0.1.14 and 250 from 0.1.15 on, and the sizing rule takes the figure of the release that runs. The design doc's 340 bytes per pair for keys and map entries counted the pair's two 64-byte buckets twice. The keys and entries take about 210 bytes. The guide also states that the segments grow with the request rate up to one request a second per operation. It says that the throttle manager keeps a read and a write bucket for each partition key that a GetItem, PutItem, UpdateItem or DeleteItem names.
… buckets (ExtendDB#398) * fix(metrics): sum latency segments into fixed time buckets instead of keeping one point per request MetricsCollector kept a SegmentPoint (112 bytes plus two heap strings) for every data-plane request for 24 hours. At 274 requests per second that is 23.7 million points a day and about 4.3 GiB of anonymous memory (issue ExtendDB#397); measured here, the 0.1.13 binary grows by 193.5 bytes per GetItem. The console only reads per-operation counts and mean segments over a window, so the points are summed at record time instead. Each operation now owns two fixed rings of 64-byte buckets: 301 one-second buckets serving LastMinute and Last5Minutes, and 1441 one-minute buckets serving LastHour, LastDay and AllTime. A record is one hash lookup and two bucket updates under the write lock; the rings are allocated once per operation. Memory is at most operations * 111,488 bytes, and the server only records the 37 operations in the dispatch table, so under 4 MiB per process. A window of W seconds covers at least the last W seconds and at most W plus one bucket width. The clock is read under the lock on both the record and the query path, so a stored record is never ahead of a query that follows it. prune() no longer touches segments. record_segments(operation, &LatencySegments) no longer takes the table name: a per-table dimension would multiply the bound by the table count, which clients control, and nothing read it. The one caller is updated. Docs: the design doc states the bucket widths and what each window returns; the deployment guide gains a Process Memory subsection with the growth law for releases through 0.1.13; the todo-index entry for the table field is removed. Tests: boundedness over five million synthetic requests, a naive-reference comparison on a random workload, continuous load across three laps of the coarse ring against a closed-form reference, window filters at second and minute boundaries, ring wrap and stale-slot exclusion, and an ignored timing comparison of the old push against the new record. * test(metrics): check the segment store's account key Main filters the latency segments by account, so the bucket store has two keys: the account, then the operation. The bound test records under three accounts and expects accounts x operations x 1,742 buckets. The random workload test gives each point an account. It checks the answer without a filter against every account's points, and the answer with each account's filter against that account's points. The sort test checks that an account that sent nothing reads empty. * docs(metrics): state the latency segment bound per account Main filters the latency segments by account, so the bucket store has two keys, the account and the operation, and its bound is per account. The metrics section of the server design doc and the process memory section of the deployment guide now give the bound. It is accounts x operations x 111,488 bytes. With the 40 operations the server dispatches that is 4,459,520 bytes (4.25 MiB) for each account that sends a request. The bound grows with the accounts that send requests and not with the request rate, the table count or uptime. The metrics module doc names the account key. * fix(metrics): drop the segment rings of an account idle for a day The segment store allocated the rings of an account's operation on its first request and kept them until restart. An account that stopped sending requests, or that an operator deleted, held 111,488 bytes per operation for the life of the process. Main's prune dropped such an account's segment points after a day. The metrics prune runs every five minutes. It now drops the rings of an account's operation once the coarse ring's whole-ring window holds no bucket of theirs. It drops the account once it holds no operation. The check reuses the ring's first slot and bucket sum. The fine ring's windows lie inside the coarse ring's, so no query answer changes. The bound in the module doc, the server design doc and the deployment guide counts the accounts that sent a request in the last day. A new store test records under two accounts and prunes at 1440 and 1441 minutes. The idle account goes at 1441 minutes with its two operations. The active account keeps its ring and its data. The idle account's next request allocates its rings again. * refactor(metrics): apply the empty account rule in the segment store query_segments turned an empty account filter into no filter before it read the store, and its test twin query_segments_at did not. The rule now lives in SegmentStore::query, so both readers share one copy and answer alike. * test(metrics): name the accounts in the bound test's comment The bound test records under three accounts and five operations and asserts the bucket count of every pair. Its comment named the operations only. * test(metrics): trim the segment store tests The bound test asserted the number of ring pairs through a test-only accessor and then asserted the exact bucket count. Each pair holds exactly 1,742 buckets, so the bucket count fixes the pair count. The accessor and its assertion go. The random workload test described a point with a four-field struct. It is a four-tuple again, destructured as the three-tuple was before the account joined it. The single-account constant equalled the first entry of the account list and goes. Every assertion keeps its meaning. * test(metrics): label the segment reference check with the filter index The reference check in segments_tests.rs put the account id of its filter into the label of every assertion message. Code scanning reads an account id written to a message as cleartext logging of sensitive data, and reported two alerts on the check. The ids are test constants. The label now names the filter's index in ACCOUNTS instead, and the parameter's name is filter. No assertion changes. * fix(metrics): hold only the segment buckets that had a request A ring now holds only the buckets of the slots that had a request, in slot order. A record first drops the buckets outside the ring's window, then adds its own. The deque grows by doubling up to the ring length and no further. So a pair that sends a request every second still holds at most 1,742 buckets, 111,488 bytes. A pair with one request a day holds two buckets. Before this change the first request of an (account, operation) pair allocated both rings in full. On a release build with a counting allocator, 1,000 accounts x 40 operations with one request each held 4,464,933,520 bytes. Main holds 9,922,080 bytes for the same requests. With this change the same store holds 13,605,520 bytes, 340 per pair. On that store the unfiltered Last5Minutes query held the read lock between 76.7 and 80.5 milliseconds. The prune held the write lock between 187.9 and 201.3 milliseconds. Both read every slot of every ring. The query now finds the window's first slot with a binary search and reads from there (5.2 to 12.2 milliseconds). The filtered query looks the account up instead of scanning the map. The prune compares one slot per pair (0.27 to 1.19 milliseconds). The collector's prune is now `prune_at(now)` behind `prune()`. The record and query paths take their clock through `record_segments_with` and `query_segments_with`. Tests can therefore run the production prune at a chosen time and check that the clock runs inside the lock. Before this change, a no-op segment prune and a clock read before the lock both passed every test. * docs(metrics): state the segment memory per bucket held and the release range The deployment guide and the design doc gave the memory per (account, operation) pair as a fixed 111,488 bytes. A pair now holds a bucket only for each second and minute with a request, so the texts give 111,488 bytes as the ceiling. A pair with one request a day costs 340 bytes with its keys and map entries (counting allocator), and the texts give that too. The guide said resident memory does not grow with requests. Wrong with `throttling_enabled = true`: the throttle manager keeps a bucket per partition key it saw and never drops one. The first sentence now covers the metrics only, and the throttle growth has a sentence of its own. The guide also said the prune frees an idle account's memory. The buckets return to the allocator. The resident size can stay at its high-water mark. The text now says both. "Releases through 0.1.13" was wrong. v0.1.14, v0.1.15 and v1.0.0 all ship `segments: RwLock<Vec<SegmentPoint>>`. The range is now every release through 1.0.0, plus any later one before the release with this change. The design doc said the server records segments only for authenticated requests. A request refused by authorization, throttling or the point-in-time recovery check also returns before the record, and the text now names the dispatch instead. The prune runs every five minutes, so an idle account's buckets go 1,440 to about 1,446 minutes after its last request. The doc gives that range. * test(metrics): query through the clock seam in the collector tests `query_segments_at(window, account, now)` only wrapped `query_segments_with(window, account, || now)`. The two tests that used it now call the seam, and the wrapper is gone. * test(metrics): move the segment bound and prune tests to their own file `segments_tests.rs` was 708 lines long. The bound, prune and memory tests and the timing comparison move unchanged to `segments_bound_tests.rs`, and the five helpers they share with the window tests become `pub(super)`. * docs(metrics): give the segment memory per release and count the keys once The deployment guide gave about 190 bytes per request for every release through 1.0.0. That is the 0.1.12 and 0.1.13 figure. 0.1.15 added the account id to each segment record (ExtendDB#955). The harness on the merge-base measured 248 bytes per point and 252 per later request. The guide now gives 190 bytes through 0.1.14 and 250 from 0.1.15 on, and the sizing rule takes the figure of the release that runs. The design doc's 340 bytes per pair for keys and map entries counted the pair's two 64-byte buckets twice. The keys and entries take about 210 bytes. The guide also states that the segments grow with the request rate up to one request a second per operation. It says that the throttle manager keeps a read and a write bucket for each partition key that a GetItem, PutItem, UpdateItem or DeleteItem names. * refactor(metrics): compare the newest bucket in the prune itself SegmentStore::prune was the only caller of Ring::holds_from, a one-line comparison of the newest bucket's slot with the first slot of the window. The comparison now sits in the prune's retain closure. * test(metrics): pin the drop of every stale bucket in a record A record at a new slot pops each bucket outside the ring with a `while` loop. No test counted the buckets after a record with more than one stale bucket to drop. So the loop changed to an `if` passed every metrics test. The new row of `bucket_memory_follows_the_requests_up_to_the_ring_length` records six consecutive seconds, then one request a ring later. That record drops all six fine buckets. The pair holds 2 buckets in a capacity of 9. With the `if`, the fine ring keeps five stale buckets and the row fails with 7 buckets held. * refactor(metrics): add a request to a bucket through add_bucket `Bucket::add` and `Bucket::add_bucket` held the same sum over the count and the six segment fields. `Bucket::new` now builds a bucket that holds one request. A record adds that bucket to the newest one with `add_bucket`, or pushes it. So only `add_bucket` holds the sum. The metrics tests pass unchanged. * test(metrics): drop the ignored timing comparison of the old push `bench_old_push_vs_new_record` ran only by hand and timed a point with two strings. The point on the base had three: 0.1.15 added the account id. The PR body keeps the numbers it gave. The test file loses 85 lines. * test(metrics): count held and allocated buckets in one helper `SegmentStore::bucket_count` and `bucket_capacity` were the same walk over the rings, one summing `len` and one `capacity`. `SegmentStore::buckets` returns both. The tests read it and assert the same numbers as before. * docs(metrics): state the prune lag and the kept allocation in comments The module doc of `segments.rs` counted the accounts that sent a request in the last 1,440 to 1,441 minutes. The prune runs every five minutes, so an account stays for up to about 1,446 minutes. The doc also said that only a pair with a request in every second and every minute reaches the bound. That holds for the buckets held. A ring's allocation does not shrink, so a pair keeps the largest allocation it reached until the prune drops its rings. The doc now says both. `record_segments` said that the memory does not grow with the request count. It grows up to the ring lengths. The comments also drop the issue number, and with it the reference to `SegmentPoint`, a type the PR removes. * docs(metrics): give the pair memory per account shape and an upgrade entry The deployment guide and the design doc gave about 340 bytes for a pair with one request a day. That holds when the account sends many operations. An account that sends one operation takes about 810 bytes for it, because its account key and its map of operations serve that one pair. Both docs now give the two figures, measured on a release build with a counting allocator. They also say that a ring's allocation does not shrink. A pair keeps the largest allocation it reached until a day passes with no request for it. The guide said that a GetItem adds six counter points. It adds five, or seven when it returns an item. The guide also said that earlier releases kept a segment record per data-plane request. They kept one per request that reaches dispatch, control-plane requests included. The upgrade manual gains a v1.1.0 entry for the `segments` of `/metrics` and `/console/metrics-data`: the wider windows, `AllTime`, the sort order and the bounded memory. The guide's Process Memory section links to it. * test(metrics): clear the two pedantic lints in the segment prune test `cargo clippy -W clippy::pedantic` warned on two lines that the PR adds to `prune_keeps_recent_segments_and_drops_them_a_day_later`: 1,441 minutes as `Duration::from_secs(1441 * 60)`, and `map` then `unwrap_or` on the lock result. The test now uses `Duration::from_mins(1441)` and `map_or`. * docs(metrics): give the measured cost range of a pair and the throttle bucket key The deployment guide said the throttle manager keeps a bucket for each partition key that a GetItem, PutItem, UpdateItem or DeleteItem names. extract_partition_value in crates/server/src/throttle_helpers.rs takes the first attribute of Key or Item as the parsed map gives it. That is name order, or the request's order on a build with the MongoDB backend. So the bucket can belong to the sort key value. The sentence now says so. The guide and the server design doc gave about 340 bytes for a pair with one request a day when its account sends many operations. On a release build with a counting allocator and 1,000 accounts, every count from 1 to 40 operations was measured on 24 November 2026. A pair costs 286 to 429 bytes with 3 to 40 operations, 475 bytes with 2, and 810 bytes with 1. The cost steps up each time the account's map of operations grows. Both docs now give the range.
What
Metrics are kept per account. Two accounts that each have a table of the same name now get their own metrics rows.
Collector and flush.
MetricKey,FlushBucketandMetricsRowcarry the account a point was recorded for.MetricsCollector::recordtakes anaccount_id, and the table-scopedrecord_*methods take one too (latency, capacity, the error metrics, throttles, returned items and bytes, request count, segments, and the TTL metrics). The request handler passes the account the request was authenticated for, and each backend's TTL worker passes the table's account. Metrics of the whole deployment (pool, worker, storage query, backup and restore jobs,TtlRepairMarkerCount) have no account.Migration 10,
account_metrics, on every backend. It createsaccount_metrics, whose key is(bucket, account_id, metric, table_name, index_name, operation), and dropsmetricswith its rows.account_idis the empty string on a metric of the whole deployment on SQLite, PostgreSQL and Cassandra; on MongoDB such a document has noaccount_idfield.CREATE TABLE IF NOT EXISTS account_metrics, thenDROP TABLE IF EXISTS metrics. The primary key starts withbucket, so its index serves the range reads and the prune.{bucket: 1}index and dropsmetricswhen the catalog lists it.The table is new rather than altered: a Cassandra partition key cannot be changed and a table cannot be renamed, and SQLite cannot alter a primary key. A new name also keeps the bodies safe to run again: on a catalog that has the migration, both statements do nothing. The old rows are dropped, not copied, because they carry no account, and the server keeps metrics for a day. The migration is
Kind::Breakingandconvergent: true. The registry entry says that no later migration may create a table namedmetrics:--reconvergeruns migration 1, which creates it, and then this drop again.MetricsStore.query_metrics(start, end, &MetricsFilter)replaces the two positional filters. The filter has an account, a table name and a metric, and an empty string reads as no filter. With an account set, the store returns that account's rows only, never a row of the whole deployment. All four stores read and writeaccount_metrics./metrics. Each row has anAccountIddimension, besideTableName,GlobalSecondaryIndexNameandOperation, andaggregate_rowskeys on the account, so two accounts' same-named tables are two rows in the snapshots and in every bucket. Theaccount_idquery parameter returns one account's rows. The filter also applies to the latencysegments./console/metrics-datareturns the same payload, so it carriesAccountIdtoo.Console. The dashboard is still admin-only. Its raw metrics table has an Account column, and its charts add the accounts together.
Docs.
MetricsStoretable, and a line of the security model.docs/schema/*.txt, and the "catalog is at migration 10" sample output lines.This is the second part of #728. #922 was the first.
Why
Part of #728.
The
metricstable had no account column on any backend, so two accounts with a table of the same name wrote to one row. The counts and latencies an admin read for that name were the two tables' added together.To reproduce on
main(9c3fbfb):dynamodb:*./metrics?window=LastHourhas oneConsumedWriteCapacityUnitsPutItem row for that name, summing 4.Testing done
extenddb_storage::metrics_conformance(new, featuretest-util). It writes rows for two accounts with a table of the same name, plus a row of the whole deployment, then checks:Each backend runs it against a migrated catalog:
migrations::released_tests::the_metrics_store_keeps_two_accounts_aparttests/metrics_store.rstests/metrics_store.rs, throughMongoCatalogStore::on_database_for_teststests/direct/metrics_store.rsOn SQLite the check fails with the account filter removed, the table filter removed, the metric filter removed, the upsert setting the sum instead of adding to it, or the prune deleting nothing.
Migration 10. On SQLite, PostgreSQL and MongoDB, a catalog with
metricsrows migrates to an emptyaccount_metricswithoutmetrics, and a second run of the body keeps the rows written since. On MongoDB the second run is through--reconverge, after migration 1 recreatedmetrics.Existing migration tests, updated for the dropped table and the new one:
DROPPED_TABLES.expected_catalog()plus a0010_account_metrics.expected.jsonfixture, and the step lists inmigrations_fresh,migrations_locksandmigrations_released.expected_definitions()plus a fixture, andkeyspace_migrations'CATALOG.tablesandDROPPED.tests/test_resource_tag_migration.py:_as_released_catalogremovesaccount_metrics.Unit tests.
record_*methods keeping its account, and the latency segments filtered by account.aggregate_rows: two accounts with the same table name stay two groups, andAccountIdis retained.record_error_metrics:UserErrorscarries the account and no table name;SystemErrors,ConditionalCheckFailedRequestsandTransactionConflictcarry the account.tests/test_metrics_accounts.py(new,slow): two accounts, the same table name with TTL on, one expired item in each. Each account sends one PutItem (1 write capacity unit in the first, 3 in the second), a GetItem, a Query, a DeleteItem whose condition fails and a GetItem on a missing table; the second also sends a Scan. Once the flush has written every row read below, with the PutItem sums at their final values, and two reads 5 s apart agree:{first: 1.0, second: 3.0};UserErrors,RequestCountand the PutItem latency count each have a row for each account;WriteThrottleEventsandThrottledRequestshave a row for each account, under a table of one write capacity unit that each account writes to until a PutItem is throttled;TimeToLiveDeletedItemCountis 1 for each account;account_id=<second>returns only rows whoseAccountIdis the second account;Against rebuilt servers on fresh databases, the fixture fails with the account dropped at flush (
{None: 4.0}), with the handler recording read capacity, a throttle event or a throttled request without the account, and with the SQLite TTL worker recording deletions without it.Against a SQLite release server built from this branch, on a fresh database:
test_metrics_accounts.py,test_metrics_table_names.py,test_metrics.py,test_console_metrics_admin_only.py,test_cross_account_isolation.pyandtest_resource_tag_migration.pypass.cargo test --lockedforextenddb-core,-storage,-server,-storage-sqlite,-appandextenddbpasses, as doextenddb-storage-cassandra --libandextenddb-storage-mongodb --lib. The one MongoDB library failure isa_standalone_server_is_unsupported, which needsEXTENDDB_TEST_MONGODB_STANDALONE_URI, not set here.PostgreSQL
tests/metrics_store.rsandmigrations_{crash,fresh,golden,guards,owners,released,runs,serving,tag_blobs}pass against a local server. The exception ismigrations_guards::a_role_that_does_not_own_the_tables_is_told_what_to_run, which also fails locally onmain: the local superuser owns the tables.MongoDB
tests/metrics_store.rsandmigrations_{fresh,guards,locks,released}pass against a local replica set.Cassandra:
--liband compile checks only. Themigrations,migrations_stoppedanddirect_integrationsuites, including the new test and the updated schema lists, run first in CI.Schema docs.
docs/schema/sqlite.txtanddocs/schema/postgres.txtaredevtools/schema-dumpof fresh installs from this branch, and match exactly.mongodb.txtandcassandra.txtare edited by hand, because their dumps need Docker; the integration jobs compare them.Lint.
cargo fmt --all -- --checkis clean, and both CI clippy commands on 1.97.0 are clean with-D warnings. Locally they also needed-A unused-variables, for the existingline_lenincrates/core/tests/data_file_decode_peak.rs, which is used on Linux only.cargo +1.88.0 check --workspace --all-targetspasses.Checklist
cargo test --workspace)cargo fmt --check)cargo clippy -- -W clippy::pedantic)Storagetrait, auth model, on-diskformat, or public CLI surface, an RFC has been accepted or is linked
below. Otherwise, an ADR captures the decision (link below).
cargo testran for the crates listed above, not the whole workspace. Clippy ran with-D warnings, as CI does, without the pedantic group.ADR / RFC: the catalog change is a numbered migration under ADR-0023.
MetricsStore::query_metricschanges signature: the trait is internal to the workspace, and every implementation is in this PR.Migration number: #934, #833 and #823 also add migration 10. Whichever merges later renumbers.
Overlap with #923:
MongoCatalogStore::on_database_for_testsis added with the same text as in #923.Breaking changes
serverefuses a catalog at migration 9. A build that reads the migration ledger and lacks migration 10 refuses a catalog at migration 10 (exit 4); a 0.1.x release must not be run against a migrated catalog at all. Rolling back means restoring the backup taken beforemigrate --yes. Stop every server of an earlier release before migrating: such a server writes tometrics, which no longer exists./metricsand/console/metrics-data:AccountIddimension, so a reader that groups rows by dimensions gets one row per account where it got one per table name;/metricstakesaccount_id.MetricsStore::query_metricstakes a&MetricsFilter, andMetricsCollector::recordand the table-scopedrecord_*methods take an account.By submitting this pull request, I confirm that my contribution is made under
the terms of the Apache License 2.0 and I agree to the Developer Certificate of
Origin (DCO). See CONTRIBUTING.md for details.