Store the latest metric value per ML run and metric name
What does this MR do and why?
This MR adds the ml_candidate_latest_metrics table, with one row per run and metric name, and fills it when MLflow clients log metrics, behind the write_ml_candidate_latest_metrics flag (default off).
Every latest-value read today (runs/get, runs/search, the experiment page and CSV, ordering by a metric) reads the whole metric history of each run, and later MRs switch those reads to this table.
The metric insert and the upsert are one SQL statement, so a request stores both or neither. The statement locks the run row FOR KEY SHARE, so it waits for a promotion of the same run. Two concurrent writes wait for each other only when they store the same metric name of the same run.
MR plan and design notes
MR plan
- This MR: the table, the model, and the dual write on
log-metricandlog-batchbehindwrite_ml_candidate_latest_metrics. - A batched background migration keyed on
ml_candidates.idfills the table for existing runs. It runs only after the write flag is at 100%, and it skipsNULLvalues with the samevalue IS NOT NULLfilter as the dual write. The same MR removes the write flag: agitlab_com_deriskflag lives at most 2 months, anddefault_enabled: truehas no effect for that type, so self-managed instances keep the write off until the flag is removed. Removing it with the backfill means that no instance fills a table that nothing keeps current. - One read flag switches every reader (MLflow API, experiment page, CSV, GraphQL) to the table. To order by a metric, MR 3 uses
ORDER BY value DESC, candidate_id DESCorORDER BY value ASC, candidate_id ASC, with noNULLSclause, and a keyset order whosevaluecolumn is not nullable. That is the only shape the experiment index serves. Today'sorder_by_metricaddsNULLS LASTand always sortsid DESC: with that shape, PostgreSQL sorts every row of the experiment and name (205 to 231 ms against 0.8 ms on the largest experiment). Changing the shape later needs a new index. - Delete the
DISTINCT ONfallback,LATERAL_METRIC_ORDER_MAX_CANDIDATES, the LATERAL branch, and the read flag.
The statement
Ml::CandidateLatestMetric.insert_metrics runs one data-modifying CTE: it inserts the metric rows into ml_candidate_metrics, then upserts one row per name into ml_candidate_latest_metrics.
- "Latest" is the row with the highest
ml_candidate_metrics.idfor a(candidate_id, name)pair. This is the rule ofMl::CandidateMetric.latesttoday (ORDER BY candidate_id, name, id DESC). The upsert encodes it inWHERE excluded.metric_id > ml_candidate_latest_metrics.metric_id, so concurrent batches and the later backfill give the same result in any order. DISTINCT ON (candidate_id, name)keeps one row per name inside a batch. Without it,ON CONFLICT DO UPDATEraises "cannot affect row a second time" when a batch logs a name twice. TheORDER BYalso makes two concurrent batches for the same run lock the rows in the same order.valueisNOT NULLso that the order index can serve both directions. NaN is stored as float NaN. The API already rejectsNaNandInfinitywith 400.- The MLflow API accepts
"value": nulland stores it in the history asNULL, but the upsert skips it. When the last row of a name isNULL, this table keeps the previous value, while today'slatestscope returns theNULLrow. metric_idhas no foreign key: it is only the high-water mark of the upsert condition, nothing reads through it, and the candidate foreign key removes the rows with their run.experiment_idis copied from the run. With it, ordering an experiment by a metric reads one page ofindex_ml_candidate_latest_metrics_on_experiment_name_value((experiment_id, name, value DESC, candidate_id DESC)), whatever the experiment size.- A run changes experiment when it is promoted to a model version:
Ml::CreateModelVersionServicemoves it to the default experiment of the model. The same transaction runsMl::CandidateLatestMetric.sync_experiment, oneUPDATEof at most one row per metric name of the run, whatever the state of the flag. The upsert reads the experiment of the run fromml_candidateswithFOR KEY SHAREand sets it on conflict. A promotion changesexperiment_id, which is in a unique index, so its update takesFOR UPDATE. A write and a promotion of the same run therefore wait for each other, and neither can leave the old experiment in a row. The lock is the one that the metric foreign key check already takes on the run row, so other updates of the run, such asruns/update, do not wait for the write. - The flagged path passes
project_idfrom Rails, so the sharding key trigger onml_candidate_metricsskips itsml_candidateslookup for each row. log-metrickeeps its model validation: it validates anMl::CandidateMetricbefore the statement, so a missing name still raisesActiveRecord::RecordInvalid.
Flag and rollback
The write has its own gitlab_com_derisk flag because a failing upsert fails the whole log-batch request, and MLflow training loops then get an error.
Rollback before the backfill (MR 2): disable the write flag. The rows written while it was on stay, and the backfill corrects them with the same rule.
After the backfill, the write flag is gone and the rollback is the read flag only. Disabling the write at that point would leave the table stale.
Deletes
The three foreign keys (candidate, experiment, project) cascade.
Projects::DestroyService deletes the rows itself: the model is the first leaf table in ML_DELETE_BATCH_SIZES (batches of 5,000), and the service declares handles_removal_of :ml_candidate_latest_metrics.
Ml::DeleteExperimentRunsService deletes the rows of each batch of 100 runs first, in statements of at most 10,000 rows, like the other children of a run, and Ml::DestroyExperimentWorker defers on the database health of the table. The worker only gets experiments that ml_delete_experiments_in_batches marks for deletion. Query plan 6 has the explicit delete for the densest batch in production (23,176 latest rows, three statements).
Sibling MRs
- !270044 (merged) edits
lib/api/ml/mlflow/runs.rbandspec/requests/api/ml/mlflow/runs_spec.rb. This MR changes neither file: the write lives inMl::ExperimentTracking::CandidateRepository. - !269564 (merged) (
app/finders/projects/ml/candidate_finder.rb) and !269544 (app/graphql/types/ml/candidate_type.rb) touch none of the files in this MR.
The MRs can merge in any order.
References
- Related to https://gitlab.com/gitlab-org/gitlab/-/work_items/635217
- Rollout issue: https://gitlab.com/gitlab-org/gitlab/-/work_items/640098
Screenshots or screen recordings
No UI change.
How to set up and validate locally
-
Run the migrations:
bin/rails db:migrate. -
In the Rails console, enable the flag:
Feature.enable(:write_ml_candidate_latest_metrics). -
Create a personal access token with the
apiscope, and pick a project you own. SetPROJECT_IDandTOKENin your shell. -
Create an experiment and a run:
API="http://gdk.test:3000/api/v4/projects/$PROJECT_ID/ml/mlflow/api/2.0/mlflow" EXP=$(curl -s -X POST -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' "$API/experiments/create" -d '{"name":"latest-metrics"}' | jq -r .experiment_id) RUN=$(curl -s -X POST -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' "$API/runs/create" -d "{\"experiment_id\":\"$EXP\"}" | jq -r .run.info.run_id) -
Log a batch that logs
losstwice:curl -s -X POST -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' "$API/runs/log-batch" \ -d "{\"run_id\":\"$RUN\",\"metrics\":[{\"key\":\"loss\",\"value\":0.5,\"timestamp\":1,\"step\":0},{\"key\":\"acc\",\"value\":0.9,\"timestamp\":1,\"step\":0},{\"key\":\"loss\",\"value\":0.25,\"timestamp\":2,\"step\":1}]}" -
In the Rails console, read the latest rows of the run:
Ml::CandidateLatestMetric.where(candidate: Ml::Candidate.find_by(eid: '<run id>')).pluck(:name, :value, :step)Expect:
[["acc", 0.9, 0], ["loss", 0.25, 1]]in any order, and three rows inMl::Candidate.find_by(eid: '<run id>').metrics.
More cases
log-metricwith{"run_id":"<run id>","key":"loss","value":0.1,"timestamp":3,"step":2}updates thelossrow to0.1.- A metric with
"value": nullis stored in the history and creates or changes no latest row. - With
Feature.disable(:write_ml_candidate_latest_metrics),log-batchandlog-metricstore metrics as before and do not changeml_candidate_latest_metrics.
Database
New table ml_candidate_latest_metrics (gitlab_main_org, sharding key project_id), written by log-metric and log-batch when the flag is on. No reads in this MR.
db:gitlabcom-database-testing on 9497cfeb: the three migrations pass on GitLab.com data in 3.7 to 3.8 s each (!270985 (comment 4285782788)).
Table, size and access patterns
Columns: id, created_at, updated_at, candidate_id, project_id, experiment_id, metric_id, tracked_at, value (double precision NOT NULL), step, name (text, at most 250 characters, like ml_candidate_metrics.name).
Indexes:
index_ml_candidate_latest_metrics_on_candidate_id_and_name(unique): the upsert conflict target, the candidate foreign key, and the preload of the latest metrics of a page of runs (MR 3).index_ml_candidate_latest_metrics_on_experiment_name_valueon(experiment_id, name, value DESC, candidate_id DESC): ordering the runs of an experiment by a metric (MR 3), and the experiment foreign key.index_ml_candidate_latest_metrics_on_project_id: the batched deletes ofProjects::DestroyServiceand the cascade of the project foreign key.
Foreign keys, all ON DELETE CASCADE: candidate_id to ml_candidates (in CREATE TABLE), then project_id to projects and experiment_id to ml_experiments, one per migration (three migrations in total). metric_id has no foreign key and is in ignored_fk_columns_map of spec/db/schema_spec.rb.
Size: about 7.6 M rows and 2.3 GB with all indexes when the backfill (MR 2) completes. On Database Lab, a slice of production metrics (4.4 M rows) loaded with the backfill query took 303 bytes per row: heap 133, (candidate_id, name) 54, the experiment index 87, the primary key 22, project_id 7.
Growth: at the rate of runs created in the last 3 months, the table grows by about 1.3 GB in 3 months, 2.5 GB in 6 months and 5.1 GB in 12 months. Metric history (ml_candidate_metrics) grows faster, because a row here replaces every earlier value of its name.
Access patterns:
- Writes: one upsert of k rows per
log-batch(k is the number of distinct names in the batch, usually 1 to 25, at most 1,000 whenmlflow_enforce_request_limitsis on), and one row perlog-metric. Each is in the same statement as the metric insert. In production the p99 of distinct metric names per run is 179, and fewer than 0.002 % of runs have more than 1,000 names. - Deletes: batches of 5,000 in
Projects::DestroyServiceand of 10,000 inMl::DeleteExperimentRunsService, otherwise the cascade from runs, experiments and projects. - Reads (MR 3): one index range per run by
(candidate_id, name), and one page of the experiment index for ordering.
Query plans (Database Lab, gitlab-production-main)
The plans use generate_series in place of the 1,000-row VALUES list that Rails sends, because the CLI cannot take a statement that long. The rows and the work for each row are the same.
joe explain rolls back, so for the update path one batch was first stored with joe exec, and the same statement was then explained.
The table was created on the clone with the indexes and foreign keys of this MR and filled from the production metrics of a range of recent runs, with the backfill query. The database review rebuilt it the same way for the update-path re-run, the delete plan and the order comparison.
Plans 6 and 7 and the like-for-like runs of plan 2 (2026-11-20) used a table of 577,745 rows built the same way, inserted in random order, so the rows of one run sit on different heap pages (the worst case for reads). Cold there means after an index scan of ml_candidate_metrics pushed the table out of the clone's 1 GB of shared buffers.
1. log-batch of 1,000 metrics today (insert_all, before this MR)
INSERT INTO ml_candidate_metrics (candidate_id, name, value, step, tracked_at, created_at, updated_at)
VALUES (<candidate_id>, 'metric_1', 0.5, 1, 1700000000001, '<now>', '<now>'), ... -- 1,000 rows- Cold: https://console.postgres.ai/gitlab/projects/gitlab-production-main/sessions/92932/commands/199107 (171.8 ms, buffers 14,394 hit / 87 read)
- Warm: https://console.postgres.ai/gitlab/projects/gitlab-production-main/sessions/92932/commands/199116 (42.9 ms, buffers 14,457 hit / 0 read)
The sharding key trigger looks up ml_candidates for each of the 1,000 rows.
2. log-batch with this MR (flag on)
WITH inserted_metrics AS (
INSERT INTO ml_candidate_metrics
(candidate_id, project_id, name, value, step, tracked_at, created_at, updated_at)
VALUES (<candidate_id>, <project_id>, 'metric_1', 0.5, 1, 1700000000001, '<now>', '<now>'), ... -- 1,000 rows
RETURNING id, candidate_id, project_id, name, value, step, tracked_at, created_at, updated_at
)
INSERT INTO ml_candidate_latest_metrics
(candidate_id, project_id, experiment_id, metric_id, name, value, step, tracked_at, created_at, updated_at)
SELECT DISTINCT ON (candidate_id, name)
candidate_id, project_id,
(SELECT experiment_id FROM ml_candidates WHERE id = <candidate_id> FOR KEY SHARE),
id, name, value, step, tracked_at, created_at, updated_at
FROM inserted_metrics
WHERE value IS NOT NULL
ORDER BY candidate_id, name, id DESC
ON CONFLICT (candidate_id, name) DO UPDATE SET
experiment_id = excluded.experiment_id,
metric_id = excluded.metric_id,
value = excluded.value,
step = excluded.step,
tracked_at = excluded.tracked_at,
updated_at = excluded.updated_at
WHERE excluded.metric_id > ml_candidate_latest_metrics.metric_idThese plans ran with FOR SHARE, the lock before the database review. FOR KEY SHARE is the lock that the foreign key check takes on the same row, so the buffers and WAL records stay the same. To stay under the CLI's length limit they use RETURNING * in the CTE, which also returns the unused is_nan column.
1,000 metrics with 25 names (the usual shape):
- New names (25 inserts), first run: https://console.postgres.ai/gitlab/projects/gitlab-production-main/sessions/93193/commands/199413 (830.5 ms, buffers 11,664 hit / 847 read, 812 full-page images). The time goes to reading and writing
ml_candidate_metricspages for the first time after a checkpoint on the clone. Today's insert writes the same metric rows. - Names already stored (25 updates), first run: https://console.postgres.ai/gitlab/projects/gitlab-production-main/sessions/93193/commands/199415 (462.0 ms, buffers 11,609 hit / 610 read, 612 full-page images); warm: https://console.postgres.ai/gitlab/projects/gitlab-production-main/sessions/93193/commands/199417 (24.4 ms, buffers 10,387 hit / 0 read, 4,096 WAL records).
- The same update without the run lock, warm: https://console.postgres.ai/gitlab/projects/gitlab-production-main/sessions/93193/commands/199416 (28.1 ms, buffers 10,384 hit / 0 read, 4,104 WAL records). The lock adds no buffers and no WAL records: the foreign key check of the metric rows already locks the same
ml_candidatesrow in every write statement, and the run lock takes that lock first.
1,000 metrics with 1,000 names (the largest batch the API accepts when mlflow_enforce_request_limits is on):
- New names (1,000 inserts): https://console.postgres.ai/gitlab/projects/gitlab-production-main/sessions/93193/commands/199418 (131.9 ms, buffers 25,453 hit / 0 read)
- Names already stored (1,000 updates): https://console.postgres.ai/gitlab/projects/gitlab-production-main/sessions/93193/commands/199420 (40.6 ms, buffers 31,904 hit / 0 read). The database review's re-runs of this case took 39.1 to 45.1 ms.
With 25 names the statement reads fewer buffers than today's insert, because the trigger lookups are skipped. With 1,000 names it reads about twice today's buffers: three foreign key checks for each new latest row, and four index entries for each inserted or updated one.
Like-for-like runs on one clone state (2026-11-20). Each cold run used its own run right after the eviction, the real 1,000-row VALUES list (built on the server) and the RETURNING list of the code. The plans were raised as errors to roll back the writes, so the console lists them as failed commands in https://console.postgres.ai/gitlab/projects/gitlab-production-main/sessions/100333.
| 1,000 rows | Cold | Warm |
|---|---|---|
Today, flag off (insert_all) |
84.0 ms (30 read, 35 full-page images); 24.9 ms in a second pair | 26.3 ms |
| Flag on, 25 new names | 59.9 ms (74 read, 39 full-page images); 20.2 ms in a second pair, run before the flag-off one | 38.7 ms |
| Flag on, 25 stored names | 76.6 ms (106 read, 76 full-page images) | 19.1 ms |
| Flag on, 1,000 new names | 64.3 ms (84 read) | 48.3 ms |
| Flag on, 1,000 stored names | 1,078 ms (1,784 read from disk, 998 ms of I/O, 1,639 full-page images) | 67.2 ms |
Planning took 1.2 to 3.8 ms in every run. With 25 names, the statement costs the same as today's insert, cold and warm. The 830.5 ms and 462.0 ms above were the first writes after a checkpoint on that clone. The slow case is 1,000 stored names with a cold cache: the 1,000 updates read 1,764 pages of latest rows and their index leaves from disk. 19 runs in production (0.0016 %) have more than 1,000 names.
Plan text: today's insert, cold
Insert on ml_candidate_metrics (cost=0.00..15.00 rows=0 width=0) (actual time=55.962..55.963 rows=0 loops=1)
Conflict Resolution: NOTHING
Tuples Inserted: 1000
Conflicting Tuples: 0
Buffers: shared hit=19102 read=30 dirtied=50 written=14
I/O Timings: shared read=24.392 write=1.453
WAL: records=5048 fpi=35 bytes=616972
-> Values Scan on "*VALUES*" (cost=0.00..15.00 rows=1000 width=124) (actual time=5.625..7.886 rows=1000 loops=1)
Buffers: shared hit=1004 read=9 dirtied=1
I/O Timings: shared read=5.490
WAL: records=31 bytes=3069
Planning Time: 2.954 ms
Trigger for constraint fk_e2684c8ffc: time=15.992 calls=1000
Trigger for constraint fk_ml_candidate_metrics_on_candidate_id: time=11.782 calls=1000
Trigger trigger_979e7f45114f: time=12.621 calls=1000
Execution Time: 83.955 msPlan text: flag on, 25 new names, cold
Insert on ml_candidate_latest_metrics (cost=88.28..108.28 rows=0 width=0) (actual time=41.483..41.486 rows=0 loops=1)
Conflict Resolution: UPDATE
Conflict Arbiter Indexes: index_ml_candidate_latest_metrics_on_candidate_id_and_name
Conflict Filter: (excluded.metric_id > ml_candidate_latest_metrics.metric_id)
Tuples Inserted: 25
Conflicting Tuples: 0
Buffers: shared hit=10474 read=74 dirtied=71 written=17
I/O Timings: shared read=31.826 write=0.635
WAL: records=4217 fpi=39 bytes=649701
CTE inserted_metrics
-> Insert on ml_candidate_metrics (cost=0.00..15.00 rows=1000 width=124) (actual time=2.106..10.668 rows=1000 loops=1)
Buffers: shared hit=10030 read=20 dirtied=28 written=17
I/O Timings: shared read=3.748 write=0.635
WAL: records=4060 fpi=3 bytes=355745
-> Values Scan on "*VALUES*" (cost=0.00..15.00 rows=1000 width=124) (actual time=0.042..1.351 rows=1000 loops=1)
Buffers: shared hit=999 read=1 dirtied=1
I/O Timings: shared read=0.031
WAL: records=30 bytes=2970
-> Subquery Scan on "*SELECT*" (cost=73.28..93.28 rows=1000 width=108) (actual time=12.213..12.459 rows=25 loops=1)
Buffers: shared hit=10059 read=22 dirtied=31 written=17
I/O Timings: shared read=3.779 write=0.635
WAL: records=4062 fpi=4 bytes=364007
-> Unique (cost=73.28..80.78 rows=1000 width=100) (actual time=12.187..12.372 rows=25 loops=1)
Buffers: shared hit=10035 read=21 dirtied=30 written=17
I/O Timings: shared read=3.761 write=0.635
WAL: records=4061 fpi=4 bytes=363908
InitPlan 2
-> LockRows (cost=0.43..3.46 rows=1 width=14) (actual time=0.035..0.037 rows=1 loops=1)
Buffers: shared hit=5 read=1 dirtied=2
I/O Timings: shared read=0.013
WAL: records=1 fpi=1 bytes=8163
-> Index Scan using ml_candidates_pkey on ml_candidates (cost=0.43..3.45 rows=1 width=14) (actual time=0.012..0.013 rows=1 loops=1)
Index Cond: (id = <candidate_id>)
Buffers: shared hit=4
-> Sort (cost=69.83..72.33 rows=1000 width=100) (actual time=12.186..12.248 rows=1000 loops=1)
Sort Key: inserted_metrics.candidate_id, inserted_metrics.name, inserted_metrics.id DESC
Sort Method: quicksort Memory: 126kB
Buffers: shared hit=10035 read=21 dirtied=30 written=17
I/O Timings: shared read=3.761 write=0.635
WAL: records=4061 fpi=4 bytes=363908
-> CTE Scan on inserted_metrics (cost=0.00..20.00 rows=1000 width=100) (actual time=2.148..11.223 rows=1000 loops=1)
Filter: (value IS NOT NULL)
Buffers: shared hit=10035 read=21 dirtied=30 written=17
I/O Timings: shared read=3.761 write=0.635
WAL: records=4061 fpi=4 bytes=363908
Planning Time: 2.637 ms
Trigger for constraint fk_e2684c8ffc on ml_candidate_metrics: time=8.041 calls=1000
Trigger for constraint fk_ml_candidate_metrics_on_candidate_id on ml_candidate_metrics: time=5.316 calls=1000
Trigger trigger_979e7f45114f on ml_candidate_metrics: time=0.708 calls=1000
Trigger for constraint fk_5d974accd8 on ml_candidate_latest_metrics: time=0.176 calls=25
Trigger for constraint fk_77edf21d43 on ml_candidate_latest_metrics: time=4.431 calls=25
Trigger for constraint fk_rails_3e574fa3d1 on ml_candidate_latest_metrics: time=0.158 calls=25
Execution Time: 59.856 ms3. log-metric with this MR (flag on)
The same statement with one row: https://console.postgres.ai/gitlab/projects/gitlab-production-main/sessions/93193/commands/199421 (6.5 ms, buffers 154 hit / 0 read, update path).
4. Order by a metric (MR 3, to show the experiment index)
SELECT ml_candidates.*, latest.value AS metric_value
FROM ml_candidate_latest_metrics latest
INNER JOIN ml_candidates ON ml_candidates.id = latest.candidate_id
WHERE latest.experiment_id = <experiment_id> AND latest.name = '<metric_name>'
ORDER BY latest.value DESC, latest.candidate_id DESC
LIMIT 31https://console.postgres.ai/gitlab/projects/gitlab-production-main/sessions/92932/commands/199118 (Index Only Scan on index_ml_candidate_latest_metrics_on_experiment_name_value, 31 rows of an experiment with 32 k runs for that metric, 3.6 ms, buffers 132 hit / 0 read)
On the largest experiment (911 k runs for one metric), the same index returns a page in 0.8 ms (https://console.postgres.ai/gitlab/projects/gitlab-production-main/sessions/93193/commands/199322). Today's order shape, ORDER BY value DESC NULLS LAST, candidate_id DESC, sorts all 911 k rows instead: 205 ms (https://console.postgres.ai/gitlab/projects/gitlab-production-main/sessions/93193/commands/199321).
5. Projects::DestroyService: batched delete of the project's latest metric rows
DELETE FROM "ml_candidate_latest_metrics" WHERE ("ml_candidate_latest_metrics"."id") IN (SELECT "ml_candidate_latest_metrics"."id" FROM "ml_candidate_latest_metrics" WHERE "ml_candidate_latest_metrics"."project_id" = <project_id> LIMIT 5000)https://console.postgres.ai/gitlab/projects/gitlab-production-main/sessions/93193/commands/199305 (Index Scan on index_ml_candidate_latest_metrics_on_project_id, then ml_candidate_latest_metrics_pkey, 5,000 rows of the project with the most rows, 22.2 ms warm, buffers 25,171 hit, 270 kB of WAL per batch)
6. Ml::DeleteExperimentRunsService: delete of the latest metric rows of a batch of runs
DELETE FROM "ml_candidate_latest_metrics" WHERE ("ml_candidate_latest_metrics"."id") IN (SELECT "ml_candidate_latest_metrics"."id" FROM "ml_candidate_latest_metrics" WHERE "ml_candidate_latest_metrics"."candidate_id" IN (SELECT "ml_candidates"."id" FROM "ml_candidates" WHERE "ml_candidates"."experiment_id" = <experiment_id> AND "ml_candidates"."eid" >= '<first_eid>') LIMIT 10000)The densest batch in production: one experiment of 87 runs with 23,176 latest rows, so the service runs this statement three times (10,000, 10,000 and 3,176 rows).
Index Scan on index_ml_candidates_on_experiment_id_and_eid, then index_ml_candidate_latest_metrics_on_candidate_id_and_name, then ml_candidate_latest_metrics_pkey.
| Statement | Cold | Warm |
|---|---|---|
| 1st, 10,000 rows | 148.8 ms, planning 17.8 ms, 6,209 buffers read (94 ms) | 70.0 ms, planning 1.7 ms, 60,237 hit, 540 kB of WAL |
| 2nd, 10,000 rows, after the 1st committed | 79.9 ms, planning 1.7 ms, 72,640 hit | |
| 3rd, 3,176 rows | 56.2 ms, planning 2.4 ms, 29,981 hit | |
Existing ml_candidate_metrics delete, same batch |
58.7 ms, planning 7.7 ms |
The 2nd and 3rd statements also walk the index entries of the rows the earlier statements deleted, so they read more buffers per row. After the explicit deletes, the cascade of ml_candidates.delete_all finds no rows here.
7. Ml::CreateModelVersionService: move the latest metric rows of a promoted run (sync_experiment)
UPDATE "ml_candidate_latest_metrics" SET "experiment_id" = <new_experiment_id> WHERE "ml_candidate_latest_metrics"."candidate_id" = <candidate_id> AND "ml_candidate_latest_metrics"."experiment_id" != <new_experiment_id>It runs after candidate.update! in the model version transaction, so the run row stays locked while it runs. Index Scan on index_ml_candidate_latest_metrics_on_candidate_id_and_name in every case.
| Run | Experiment | Cold | Warm |
|---|---|---|---|
| Most names in production (2,641 rows) | changes | 134.0 ms, 3,732 read, 1.7 MB of WAL | 73.0 ms |
| Most names in production (2,641 rows) | stays the same | 39.3 ms, 0 rows updated | 4.4 ms |
| p99 of names per run (198 rows) | changes | 17.3 ms | 8.1 ms |
| p99 of names per run (198 rows) | stays the same | 4.5 ms, 0 rows updated | 0.5 ms |
Planning took 1.9 to 2.1 ms cold and 0.6 to 0.7 ms warm. Without the experiment_id != condition, an unchanged experiment rewrote all 2,641 rows: 219.1 ms cold, 63.9 ms warm.
The first update of the 2,641 rows on this clone read its pages from disk and took 1.6 s (3,625 reads, 1.45 s of I/O). Fewer than 0.002 % of runs have more than 1,000 names.
Migration output
Up:
main: == 20261113151633 CreateMlCandidateLatestMetrics: migrating ===================
main: -- create_table(:ml_candidate_latest_metrics)
main: -- quote_column_name(:name)
main: -> 0.0000s
main: -> 0.1195s
main: == 20261113151633 CreateMlCandidateLatestMetrics: migrated (0.1253s) ==========
main: == 20261113151634 AddProjectForeignKeyToMlCandidateLatestMetrics: migrating ===
main: -- transaction_open?(nil)
main: -> 0.0000s
main: -- transaction_open?(nil)
main: -> 0.0000s
main: -- execute("LOCK TABLE projects, ml_candidate_latest_metrics IN SHARE ROW EXCLUSIVE MODE")
main: -> 0.0004s
main: -- execute("ALTER TABLE ml_candidate_latest_metrics ADD CONSTRAINT fk_5d974accd8 FOREIGN KEY (project_id) REFERENCES projects (id) ON DELETE CASCADE NOT VALID;")
main: -> 0.0022s
main: -- execute("ALTER TABLE ml_candidate_latest_metrics VALIDATE CONSTRAINT fk_5d974accd8;")
main: -> 0.0147s
main: == 20261113151634 AddProjectForeignKeyToMlCandidateLatestMetrics: migrated (0.0347s)
main: == 20261113151635 AddExperimentForeignKeyToMlCandidateLatestMetrics: migrating
main: -- transaction_open?(nil)
main: -> 0.0000s
main: -- transaction_open?(nil)
main: -> 0.0000s
main: -- execute("LOCK TABLE ml_experiments, ml_candidate_latest_metrics IN SHARE ROW EXCLUSIVE MODE")
main: -> 0.0003s
main: -- execute("ALTER TABLE ml_candidate_latest_metrics ADD CONSTRAINT fk_77edf21d43 FOREIGN KEY (experiment_id) REFERENCES ml_experiments (id) ON DELETE CASCADE NOT VALID;")
main: -> 0.0004s
main: -- execute("ALTER TABLE ml_candidate_latest_metrics VALIDATE CONSTRAINT fk_77edf21d43;")
main: -> 0.0033s
main: == 20261113151635 AddExperimentForeignKeyToMlCandidateLatestMetrics: migrated (0.0144s) Down:
main: == 20261113151635 AddExperimentForeignKeyToMlCandidateLatestMetrics: reverting
main: -- transaction_open?(nil)
main: -> 0.0000s
main: -- remove_foreign_key(:ml_candidate_latest_metrics, {column: :experiment_id})
main: -> 0.0112s
main: == 20261113151635 AddExperimentForeignKeyToMlCandidateLatestMetrics: reverted (0.1234s)
main: == 20261113151634 AddProjectForeignKeyToMlCandidateLatestMetrics: reverting ===
main: -- transaction_open?(nil)
main: -> 0.0000s
main: -- remove_foreign_key(:ml_candidate_latest_metrics, {column: :project_id})
main: -> 0.0028s
main: == 20261113151634 AddProjectForeignKeyToMlCandidateLatestMetrics: reverted (0.1014s)
main: == 20261113151633 CreateMlCandidateLatestMetrics: reverting ===================
main: -- drop_table(:ml_candidate_latest_metrics)
main: -> 0.0765s
main: == 20261113151633 CreateMlCandidateLatestMetrics: reverted (0.0822s) ==========db/structure.sql is identical after down and up.
MR acceptance checklist
Evaluate this MR against the MR acceptance checklist. It helps you analyze changes to reduce risks in quality, performance, reliability, security, and maintainability.