Realign policy indexes when approval policies are reordered

What does this MR do and why?

Reordering approval policies now realigns the policy indexes stored in their projects. This stops Security::SyncProjectPolicyWorker from failing with ActiveRecord::RecordInvalid: Validation failed: Rule idx has already been taken.

Symptom

On GitLab.com this worker failed about 5.3k times in 7 days. It is the second most common failure in security policy management Sidekiq jobs. The failures come in bursts after policy changes are merged. They concentrate in a few projects. On RecordInvalid the worker discards the job and enqueues one resync of the same policy for the project. That resync fails the same way, so the policy is never applied to the project.

Root cause

Reordering policies in the policy YAML only updates security_policies.policy_index (PersistPolicyService#update_rearranged_policies). Examples are inserting a new approval policy above existing ones, or deleting one from the middle.

Scan result policy reads (scan_result_policies) and approval project and MR rules each store their own orchestration_policy_idx. Nothing rewrote them:

  • PolicyComparer reported policy_index as changed from nil on every update. The YAML policy hash carries policy_index and the stored policy hash does not. So the diff gave no real "moved" signal.
  • Diff#needs_refresh? and #needs_rules_refresh? ignore policy_index. SyncPolicyWorker never synced projects for a moved policy.
  • The new policy gets the freed index. Creating its read collides with the old policy's stale read on the unique (configuration, project, orchestration_policy_idx, rule_idx, action_idx) key. This fails in ApprovalRules::CreateService#create_scan_result_policy.

Fix

  • PolicyComparer captures the policy's stored policy_index when it is built and diffs against it. So policy_index shows up only on a real move.
  • Diff#policy_index_changed? is new.
  • SyncPolicyWorker syncs projects when an approval policy's index changed. Other policy types don't store the index per project.
  • New Security::ScanResultPolicies::RealignPolicyIndexesService. For one project and policy configuration, it finds the scan result policy reads whose orchestration_policy_idx differs from their policy's current policy_index.
    • It also updates orchestration_policy_idx on the matching project approval rules and on approval rules of open merge requests, the same set SyncMergeRequestsService syncs. Closed and merged merge requests keep their rules unchanged.
    • The unique indexes on reads and on merge request approval rules both include the index, so rows are first shifted to temporary indexes, then set to their final ones, so swaps and rotations converge.
    • Every statement is bounded. Open merge request rules are realigned in batches of 20 open merge requests (project.merge_requests.opened.each_batch). Each batch is one short transaction that locks the rule ids (FOR NO KEY UPDATE), then shifts and moves exactly those ids. The unique index on merge request rules starts with merge_request_id, so batches cannot collide. A merge request merged mid-way cannot keep the temporary index.
    • Reads move last, in a short transaction of their own. A realign that stops midway leaves the reads stale, so the next one picks the same rules up again.
    • The exclusive lease is renewed before every UPDATE. More than 500 stale reads (20 policies * 5 rules * 5 actions) raises instead of running unbounded.
  • The realign runs in BaseProjectPolicyService#link_policy before the policy's rules are created. That covers new links, resync and converge events. It also runs in sync_approval_policy_diff when the index changed.
  • The new policy's own link now realigns first. It no longer depends on the moved policy's job running before it.
  • Projects already in the broken state heal on their next resync, including the resync the worker enqueues after a RecordInvalid.

Limitations

  • Realign touches only reads that belong to an approval policy rule. Legacy reads without approval_policy_rule_id aren't moved.

Tests

  • policy_comparer_spec: diffs against the original index, and no policy_index diff when unmoved.
  • diff_spec: #policy_index_changed?.
  • sync_policy_worker_spec: fans out for approval policies, not for pipeline execution schedule policies.
  • realign_policy_indexes_service_spec: swap with same-named merge request rules, 3-way rotation, deleted policy, closed merge request rules untouched, other project untouched, and no updates when reads are aligned.
  • sync_project_service_spec: index-only change, swap, and linking at an index held by a stale read.

Rollout

  • One extra SELECT per approval policy link, scoped to the project and configuration.
  • No database migrations.
  • No feature flag.
  • No UI or documentation changes.

References

No linked issue.

Screenshots or screen recordings

No UI changes. See the before/after table in the validation steps below.

How to set up and validate locally

  1. Create a security policy project whose .gitlab/security-policies/policy.yml has one approval policy, "Policy A". Use an any_merge_request rule and a require_approval action with role_approvers: [maintainer]. Link it to a project.
  2. Commit a change that inserts a second approval policy, "Policy B", above Policy A. To sync right away, run this in the Rails console:
    Security::SyncScanPoliciesWorker.perform_async(<configuration_id>)
  3. Check log/sidekiq.log, then run this in the Rails console:
    Security::ScanResultPolicyRead.where(project_id: <id>).pluck(:approval_policy_rule_id, :orchestration_policy_idx)
Before After
SyncProjectPolicyWorker for Policy B Fails with "Rule idx has already been taken" Succeeds
SyncProjectPolicyWorker for Policy A Not enqueued Succeeds
Policy A read and approval rule index Read stays at 0 1
Policy B read and approval rule index Not created 0

Swap

  1. Commit a change that reverses the order of the two policies and sync again.
  2. Run the pluck above. Both reads swap indexes, and both SyncProjectPolicyWorker jobs succeed.

Heal

  1. On a project already in the broken state (a stale read, and the new policy not linked), run this in the Rails console:
    Security::SyncProjectPolicyWorker.perform_async(project_id, policy_id, {}, { 'event' => { 'event_type' => Security::PolicyResyncEvent.to_param, 'data' => { 'security_policy_id' => policy_id } } })
  2. Check that the job succeeds and the reads end up at the right indexes.

Database

Plans come from the gitlab-production-main thin clone (postgresai joe explain, EXPLAIN (ANALYZE, BUFFERS)), with no local GDK data. For the UPDATEs the clone is safe to write to. All of these queries run once per policy reorder (not per request). Statements 4 and 7 were replaced by the batched statements 8 to 10 after review; the plans for them are kept below for reference. Statements 3 and 5 now run in a short transaction of their own. Writes use the same ids as in the update_all calls; the move target 500 stands in for the policy's current_policy_index, chosen so it does not hit the unique index on the clone. Long id IN (...) lists in the plans are abbreviated.

Parameter choices: the largest project-level configuration by number of reads (security_orchestration_policy_configuration_id = 10889, project_id = 43546313, 282 reads); one configuration where reads link to policy rules (3174787 / 83016983); and the configuration with the most open-MR rules (14525 / 42311480: 152 reads, 135 open-MR rules, 6 project rules) for the writes.

Read: with_stale_policy_index

Both plans use the (security_orchestration_policy_configuration_id, project_id, ...) prefix of index_scan_result_policies_on_configuration_action_and_rule_idx, then primary-key lookups for the joins. No sequential scans.

1. Security::ScanResultPolicyRead...with_stale_policy_index, largest configuration (282 reads)

project.scan_result_policy_reads.for_policy_configuration(config).with_stale_policy_index. These 282 reads have no approval_policy_rule_id, so the inner join drops them.

SELECT scan_result_policies.*, security_policies.policy_index AS current_policy_index FROM "scan_result_policies" INNER JOIN "approval_policy_rules" ON "approval_policy_rules"."id" = "scan_result_policies"."approval_policy_rule_id" INNER JOIN "security_policies" ON "security_policies"."id" = "approval_policy_rules"."security_policy_id" WHERE "scan_result_policies"."project_id" = 43546313 AND "scan_result_policies"."security_orchestration_policy_configuration_id" = 10889 AND (scan_result_policies.orchestration_policy_idx <> security_policies.policy_index)

Execution 0.44 ms (total 2.9 ms with planning), shared hit=158, 0 rows returned.

Plan
Nested Loop  (cost=1.26..7.69 rows=1 width=435) (actual time=0.347..0.348 rows=0 loops=1)
  Join Filter: (scan_result_policies.orchestration_policy_idx <> security_policies.policy_index)
  Buffers: shared hit=158
  I/O Timings: read=0.000 write=0.000
  ->  Nested Loop  (cost=0.84..6.88 rows=1 width=441) (actual time=0.346..0.347 rows=0 loops=1)
        Buffers: shared hit=158
        I/O Timings: read=0.000 write=0.000
        ->  Index Scan using index_scan_result_policies_on_configuration_action_and_rule_idx on public.scan_result_policies  (cost=0.43..3.45 rows=1 width=433) (actual time=0.043..0.287 rows=282 loops=1)
              Index Cond: ((scan_result_policies.security_orchestration_policy_configuration_id = 10889) AND (scan_result_policies.project_id = 43546313))
              Buffers: shared hit=158
              I/O Timings: read=0.000 write=0.000
        ->  Index Scan using approval_policy_rules_pkey on public.approval_policy_rules  (cost=0.42..3.44 rows=1 width=16) (actual time=0.000..0.000 rows=0 loops=282)
              Index Cond: (approval_policy_rules.id = scan_result_policies.approval_policy_rule_id)
              I/O Timings: read=0.000 write=0.000
  ->  Index Scan using security_policies_pkey on public.security_policies  (cost=0.42..0.80 rows=1 width=10) (never executed)
        Index Cond: (security_policies.id = approval_policy_rules.security_policy_id)
        I/O Timings: read=0.000 write=0.000

2. with_stale_policy_index, configuration with linked policy rules (9 reads)

Same scope, where the join to approval_policy_rules and security_policies matches and all 9 rows are stale.

SELECT scan_result_policies.*, security_policies.policy_index AS current_policy_index FROM "scan_result_policies" INNER JOIN "approval_policy_rules" ON "approval_policy_rules"."id" = "scan_result_policies"."approval_policy_rule_id" INNER JOIN "security_policies" ON "security_policies"."id" = "approval_policy_rules"."security_policy_id" WHERE "scan_result_policies"."project_id" = 83016983 AND "scan_result_policies"."security_orchestration_policy_configuration_id" = 3174787 AND (scan_result_policies.orchestration_policy_idx <> security_policies.policy_index)

Execution 9.5 ms on a cold cache (total 12.1 ms with planning), shared hit=74 read=13, 9 rows returned.

Plan
Nested Loop  (cost=1.26..7.69 rows=1 width=435) (actual time=4.575..9.449 rows=9 loops=1)
  Join Filter: (scan_result_policies.orchestration_policy_idx <> security_policies.policy_index)
  Buffers: shared hit=74 read=13
  I/O Timings: read=9.052 write=0.000
  ->  Nested Loop  (cost=0.84..6.88 rows=1 width=441) (actual time=2.092..5.607 rows=9 loops=1)
        Buffers: shared hit=43 read=8
        I/O Timings: read=5.311 write=0.000
        ->  Index Scan using index_scan_result_policies_on_configuration_action_and_rule_idx on public.scan_result_policies  (cost=0.43..3.45 rows=1 width=433) (actual time=0.066..0.190 rows=9 loops=1)
              Index Cond: ((scan_result_policies.security_orchestration_policy_configuration_id = 3174787) AND (scan_result_policies.project_id = 83016983))
              Buffers: shared hit=15
              I/O Timings: read=0.000 write=0.000
        ->  Index Scan using approval_policy_rules_pkey on public.approval_policy_rules  (cost=0.42..3.44 rows=1 width=16) (actual time=0.600..0.600 rows=1 loops=9)
              Index Cond: (approval_policy_rules.id = scan_result_policies.approval_policy_rule_id)
              Buffers: shared hit=28 read=8
              I/O Timings: read=5.311 write=0.000
  ->  Index Scan using security_policies_pkey on public.security_policies  (cost=0.42..0.80 rows=1 width=10) (actual time=0.425..0.425 rows=1 loops=9)
        Index Cond: (security_policies.id = approval_policy_rules.security_policy_id)
        Buffers: shared hit=31 read=5
        I/O Timings: read=3.741 write=0.000

Writes: shift to temporary index (shift_to_temporary_index)

3. update_all on scan_result_policies (shift)

Security::ScanResultPolicyRead.id_in(reads.map(&:id)).update_all(shift), 152 ids.

UPDATE "scan_result_policies" SET orchestration_policy_idx = orchestration_policy_idx - 16000 WHERE "scan_result_policies"."id" IN (362016,362017,362018,362019,362020,362021,362022,362023,362024,362025,362026,362027,362028,362029,362030,362031,362032,362033,362034,362035,362036,362037,362038,362039,362040,362041,362043,362044,362045,362046,362047,362048,362064,362065,362066,362067,362068,362069,423722,423723,423724,423725,423726,423727,423736,423737,423738,423739,423740,423741,926771,926772,926773,926774,926775,926776,1415551,1415552,1415553,1415554,1415555,1415556,1436493,1436494,1436495,1436496,1436497,1436498,1507817,1507818,1507819,1507820,1507821,1507822,1507823,1507824,1507825,1507826,1507827,1507828,1561169,1561170,1561171,1561172,1561173,1561174,1561177,1561178,1561179,1561180,1561181,1561182,1561213,1561214,1561215,1561216,1561217,1561218,1562568,1562569,1562570,1562571,1562572,1562573,1562579,1562580,1562581,1562582,1562583,1562584,1562585,1562586,1562587,1562588,1562589,1562590,1586701,1586702,1586703,1586704,1586705,1586706,1639501,1639502,1639517,1639518,1639519,1639520,1639521,1639522,1639523,1639524,1639525,1639526,1725234,1725235,1725236,1725237,1725238,1725239,1814097,1814098,1814099,1814100,1814101,1814102,21562504,21562506,21562507,21562508,21562509,21562510)

Execution 49.1 ms cold (5.7 ms on a warm re-run), shared hit=3833 read=56 dirtied=157, 152 rows updated, primary key index scan.

Plan
Update on public.scan_result_policies  (cost=0.43..480.22 rows=0 width=0) (actual time=49.003..49.003 rows=0 loops=1)
  Buffers: shared hit=3833 read=56 dirtied=157
  WAL: records=1341 fpi=156 bytes=1071898
  I/O Timings: read=43.057 write=0.000
  ->  Index Scan using scan_result_policies_pkey on public.scan_result_policies  (cost=0.43..480.22 rows=152 width=8) (actual time=1.459..16.098 rows=152 loops=1)
        Index Cond: (scan_result_policies.id = ANY ('{362016,...,21562510}'::bigint[]))
        Buffers: shared hit=76 read=20
        I/O Timings: read=15.742 write=0.000
Trigger trigger_4c320a13bc8d: time=0.397 calls=152
Trigger trigger_b83b7e51e2f5: time=0.192 calls=152

4. (superseded by 8 to 10) update_all on approval_merge_request_rules (shift)

ApprovalMergeRequestRule.for_opened_merge_requests.for_scan_result_policy_read(reads).update_all(shift), 135 open-MR rules.

UPDATE "approval_merge_request_rules" SET orchestration_policy_idx = orchestration_policy_idx - 16000 WHERE ("approval_merge_request_rules"."id") IN (SELECT "approval_merge_request_rules"."id" FROM "approval_merge_request_rules" INNER JOIN "merge_requests" ON "merge_requests"."id" = "approval_merge_request_rules"."merge_request_id" WHERE "merge_requests"."state_id" = 1 AND "approval_merge_request_rules"."scan_result_policy_id" IN (362016,362017,362018,362019,362020,362021,362022,362023,362024,362025,362026,362027,362028,362029,362030,362031,362032,362033,362034,362035,362036,362037,362038,362039,362040,362041,362043,362044,362045,362046,362047,362048,362064,362065,362066,362067,362068,362069,423722,423723,423724,423725,423726,423727,423736,423737,423738,423739,423740,423741,926771,926772,926773,926774,926775,926776,1415551,1415552,1415553,1415554,1415555,1415556,1436493,1436494,1436495,1436496,1436497,1436498,1507817,1507818,1507819,1507820,1507821,1507822,1507823,1507824,1507825,1507826,1507827,1507828,1561169,1561170,1561171,1561172,1561173,1561174,1561177,1561178,1561179,1561180,1561181,1561182,1561213,1561214,1561215,1561216,1561217,1561218,1562568,1562569,1562570,1562571,1562572,1562573,1562579,1562580,1562581,1562582,1562583,1562584,1562585,1562586,1562587,1562588,1562589,1562590,1586701,1586702,1586703,1586704,1586705,1586706,1639501,1639502,1639517,1639518,1639519,1639520,1639521,1639522,1639523,1639524,1639525,1639526,1725234,1725235,1725236,1725237,1725238,1725239,1814097,1814098,1814099,1814100,1814101,1814102,21562504,21562506,21562507,21562508,21562509,21562510))

Execution 157-270 ms across three runs (262 ms in the plan below), shared hit=7740 read=320 dirtied=209, 135 rows updated. Index scans only (idx_approval_merge_request_rules_on_scan_result_policy_id, then idx_merge_requests_on_unmerged_state_id). Time is dominated by per-row index maintenance on a very large table and cold reads, not by finding the rows. This is above 100 ms, but it is a one-off per reorder for a configuration with 135 open-MR rules, and the typical project has far fewer.

Plan
Update on public.approval_merge_request_rules  (cost=177821.67..181780.05 rows=0 width=0) (actual time=262.320..262.322 rows=0 loops=1)
  Buffers: shared hit=7740 read=320 dirtied=209 written=8
  WAL: records=1798 fpi=199 bytes=1684339
  I/O Timings: read=248.467 write=0.562
  ->  Nested Loop  (cost=177821.67..181780.05 rows=1108 width=20) (actual time=24.724..30.425 rows=135 loops=1)
        Buffers: shared hit=1478 read=28
        I/O Timings: read=28.775 write=0.000
        ->  HashAggregate  (cost=177821.09..177832.17 rows=1108 width=20) (actual time=19.149..19.246 rows=135 loops=1)
              Group Key: approval_merge_request_rules_1.id
              Batches: 1  Memory Usage: 81kB
              Buffers: shared hit=810 read=21
              I/O Timings: read=18.215 write=0.000
              ->  Nested Loop  (cost=1.14..177818.32 rows=1108 width=20) (actual time=2.465..19.081 rows=135 loops=1)
                    Buffers: shared hit=810 read=21
                    I/O Timings: read=18.215 write=0.000
                    ->  Index Scan using idx_approval_merge_request_rules_on_scan_result_policy_id on public.approval_merge_request_rules approval_merge_request_rules_1  (cost=0.57..40518.96 rows=39969 width=18) (actual time=0.042..0.199 rows=141 loops=1)
                          Index Cond: (approval_merge_request_rules_1.scan_result_policy_id = ANY ('{362016,...,21562510}'::bigint[]))
                          Buffers: shared hit=123
                          I/O Timings: read=0.000 write=0.000
                    ->  Index Scan using idx_merge_requests_on_unmerged_state_id on public.merge_requests  (cost=0.56..3.44 rows=1 width=14) (actual time=0.133..0.133 rows=1 loops=141)
                          Index Cond: (merge_requests.id = approval_merge_request_rules_1.merge_request_id)
                          Filter: (merge_requests.state_id = 1)
                          Buffers: shared hit=687 read=21
                          I/O Timings: read=18.215 write=0.000
        ->  Index Scan using approval_merge_request_rules_pkey on public.approval_merge_request_rules  (cost=0.57..3.56 rows=1 width=16) (actual time=0.082..0.082 rows=1 loops=135)
              Index Cond: (approval_merge_request_rules.id = approval_merge_request_rules_1.id)
              Buffers: shared hit=668 read=7
              I/O Timings: read=10.560 write=0.000
Trigger trigger_01b3fc052119: time=0.645 calls=135

Writes: move to final policy index (move_to_policy_index, once per policy)

The reads of one policy share current_policy_index, so the service groups them with reads.group_by(&:current_policy_index) and runs these three statements once per group instead of once per read. The plans below use the 46 reads at orchestration_policy_idx = 1 of configuration 14525 / 42311480, moved together to 500, as a stand-in for the reads of one policy.

5. update_all on scan_result_policies (move)

Security::ScanResultPolicyRead.id_in(reads.map(&:id)).update_all(orchestration_policy_idx: ...), 46 ids.

UPDATE "scan_result_policies" SET "orchestration_policy_idx" = 500 WHERE "scan_result_policies"."id" IN (21562509,21562510,362028,423726,423727,423740,423741,1561173,...)

Execution 93 ms on a cold cache, shared hit=1229 read=101 dirtied=94, 46 rows updated, primary key index scan (id = ANY).

Plan
Update on public.scan_result_policies  (cost=0.43..144.53 rows=0 width=0) (actual time=93.243..93.243 rows=0 loops=1)
  Buffers: shared hit=1229 read=101 dirtied=94
  WAL: records=400 fpi=93 bytes=523949
  I/O Timings: read=90.325 write=0.000
  ->  Index Scan using scan_result_policies_pkey on public.scan_result_policies  (cost=0.43..144.53 rows=46 width=8) (actual time=2.653..22.622 rows=46 loops=1)
        Index Cond: (scan_result_policies.id = ANY ('{21562509,21562510,362028,423726,423727,423740,423741,1561173,...}'::bigint[]))
        Buffers: shared hit=45 read=22
        I/O Timings: read=22.425 write=0.000
Trigger trigger_4c320a13bc8d: time=0.298 calls=46
Trigger trigger_b83b7e51e2f5: time=0.088 calls=46

6. update_all on approval_project_rules (move)

ApprovalProjectRule.for_scan_result_policy_read(reads).update_all(orchestration_policy_idx: ...), 46 ids.

UPDATE "approval_project_rules" SET "orchestration_policy_idx" = 500 WHERE "approval_project_rules"."scan_result_policy_id" IN (21562509,21562510,362028,423726,423727,423740,423741,1561173,...)

Execution 98 ms on a cold cache (96 ms of it I/O read), 2 rows updated, idx_approval_project_rules_on_scan_result_policy_id.

Plan
Update on public.approval_project_rules  (cost=0.43..128.72 rows=0 width=0) (actual time=97.673..97.674 rows=0 loops=1)
  Buffers: shared hit=169 read=133 dirtied=23
  WAL: records=29 fpi=21 bytes=116705
  I/O Timings: read=96.511 write=0.000
  ->  Index Scan using idx_approval_project_rules_on_scan_result_policy_id on public.approval_project_rules  (cost=0.43..128.72 rows=46 width=8) (actual time=3.952..4.469 rows=2 loops=1)
        Index Cond: (approval_project_rules.scan_result_policy_id = ANY ('{21562509,21562510,362028,423726,423727,423740,423741,1561173,...}'::bigint[]))
        Buffers: shared hit=1 read=7
        I/O Timings: read=4.405 write=0.000

7. (superseded by 8 to 10) update_all on approval_merge_request_rules (move)

ApprovalMergeRequestRule.for_opened_merge_requests.for_scan_result_policy_read(reads).update_all(orchestration_policy_idx: ...), 46 ids, 45 open-MR rules.

UPDATE "approval_merge_request_rules" SET "orchestration_policy_idx" = 500 WHERE ("approval_merge_request_rules"."id") IN (SELECT "approval_merge_request_rules"."id" FROM "approval_merge_request_rules" INNER JOIN "merge_requests" ON "merge_requests"."id" = "approval_merge_request_rules"."merge_request_id" WHERE "merge_requests"."state_id" = 1 AND "approval_merge_request_rules"."scan_result_policy_id" IN (21562509,21562510,362028,423726,423727,423740,423741,1561173,...))

Execution 256 ms on a cold cache (247 ms of it I/O read), shared hit=2472 read=221 dirtied=104, 45 rows updated, same index scans as the shift. Statement count for the final move is now 3 per policy instead of 3 per read.

Plan
Update on public.approval_merge_request_rules  (cost=57942.05..59208.66 rows=0 width=0) (actual time=256.289..256.292 rows=0 loops=1)
  Buffers: shared hit=2472 read=221 dirtied=104 written=2
  WAL: records=598 fpi=101 bytes=809100
  I/O Timings: read=247.241 write=0.167
  ->  Nested Loop  (cost=57942.05..59208.66 rows=353 width=20) (actual time=101.017..104.922 rows=45 loops=1)
        Buffers: shared hit=420 read=87
        I/O Timings: read=103.993 write=0.000
        ->  HashAggregate  (cost=57941.48..57945.01 rows=353 width=20) (actual time=94.591..94.637 rows=45 loops=1)
              Group Key: approval_merge_request_rules_1.id
              Batches: 1  Memory Usage: 37kB
              Buffers: shared hit=202 read=80
              I/O Timings: read=94.032 write=0.000
              ->  Nested Loop  (cost=1.14..57940.59 rows=353 width=20) (actual time=12.625..94.549 rows=45 loops=1)
                    Buffers: shared hit=202 read=80
                    I/O Timings: read=94.032 write=0.000
                    ->  Index Scan using idx_approval_merge_request_rules_on_scan_result_policy_id on public.approval_merge_request_rules approval_merge_request_rules_1  (cost=0.57..12945.21 rows=12728 width=18) (actual time=7.638..32.560 rows=47 loops=1)
                          Index Cond: (approval_merge_request_rules_1.scan_result_policy_id = ANY ('{21562509,21562510,362028,423726,423727,423740,423741,1561173,...}'::bigint[]))
                          Buffers: shared hit=11 read=33
                          I/O Timings: read=32.418 write=0.000
                    ->  Index Scan using idx_merge_requests_on_unmerged_state_id on public.merge_requests  (cost=0.56..3.54 rows=1 width=14) (actual time=1.318..1.318 rows=1 loops=47)
                          Index Cond: (merge_requests.id = approval_merge_request_rules_1.merge_request_id)
                          Filter: (merge_requests.state_id = 1)
                          Buffers: shared hit=191 read=47
                          I/O Timings: read=61.615 write=0.000
        ->  Index Scan using approval_merge_request_rules_pkey on public.approval_merge_request_rules  (cost=0.57..3.58 rows=1 width=14) (actual time=0.227..0.227 rows=1 loops=45)
              Index Cond: (approval_merge_request_rules.id = approval_merge_request_rules_1.id)
              Buffers: shared hit=218 read=7
              I/O Timings: read=9.961 write=0.000
Trigger trigger_01b3fc052119: time=0.446 calls=45

Writes after review: batched merge request rules

Per batch of at most 20 open merge requests (each_batch boundaries id >= <first> AND id < <next>, the last batch has no upper bound), one short transaction runs: a locking select, one shift by id, one move by id per policy index. Plans use target_project_id = 42311480, configuration 14525 and the same 152 read ids as above; that project has 23 open merge requests, so one batch.

8. Batch boundary

SELECT "merge_requests"."id" FROM "merge_requests" WHERE "merge_requests"."target_project_id" = 42311480 AND "merge_requests"."state_id" = 1 ORDER BY "merge_requests"."id" ASC LIMIT 1 OFFSET 20

Index-only scan on idx_mrs_on_target_id_and_created_at_and_state_id plus a sort of the 23 matching rows. 20 ms cold, shared hit=11 read=21. The plan was captured with OFFSET 50, which gives the same plan shape.

9. Lock and collect the rule ids of one batch

ApprovalMergeRequestRule.for_merge_requests(batch).for_policy_configuration(config).for_scan_result_policy_read(reads).lock_ids_by_scan_result_policy_read. The batch is a subquery, written here with a scalar lower bound as a stand-in for the batch boundary.

SELECT "approval_merge_request_rules"."scan_result_policy_id", "approval_merge_request_rules"."id" FROM "approval_merge_request_rules" WHERE "approval_merge_request_rules"."merge_request_id" IN (SELECT "merge_requests"."id" FROM "merge_requests" WHERE "merge_requests"."target_project_id" = 42311480 AND "merge_requests"."state_id" = 1 AND "merge_requests"."id" >= <batch_first_id>) AND "approval_merge_request_rules"."security_orchestration_policy_configuration_id" = 14525 AND "approval_merge_request_rules"."scan_result_policy_id" IN (362016,362017,...,21562510) FOR NO KEY UPDATE

Execution 124 ms on a cold cache (123 ms of it I/O read), shared hit=415 read=103 dirtied=50, 135 rows locked. It drives from the 23 merge requests and probes idx_approval_merge_request_rules_on_mr_id_config_id_and_id once per merge request (about 6 rules each), with the read ids as a filter. No sequential scans.

Plan
LockRows  (cost=5.67..49.05 rows=1 width=28) (actual time=8.462..124.377 rows=135 loops=1)
  Buffers: shared hit=415 read=103 dirtied=50
  ->  Nested Loop  (cost=1.52..44.90 rows=1 width=28) (actual time=7.573..122.433 rows=135 loops=1)
        ->  Index Scan using idx_mrs_on_target_id_and_created_at_and_state_id on public.merge_requests  (cost=0.57..13.00 rows=8 width=14) (actual time=2.796..57.925 rows=23 loops=1)
              Index Cond: ((target_project_id = 42311480) AND (state_id = 1) AND (id >= (InitPlan 1).col1))
        ->  Index Scan using idx_approval_merge_request_rules_on_mr_id_config_id_and_id on public.approval_merge_request_rules  (cost=0.95..3.98 rows=1 width=26) (actual time=1.738..2.802 rows=6 loops=23)
              Index Cond: ((merge_request_id = merge_requests.id) AND (security_orchestration_policy_configuration_id = 14525))
              Filter: (scan_result_policy_id = ANY ('{362016,...,21562510}'::bigint[]))

10. Shift and move by explicit id

UPDATE "approval_merge_request_rules" SET orchestration_policy_idx = orchestration_policy_idx - 16000 WHERE "approval_merge_request_rules"."id" IN (<ids from 9>)
UPDATE "approval_merge_request_rules" SET "orchestration_policy_idx" = 1 WHERE "approval_merge_request_rules"."id" IN (<ids of one policy from 9>)

Primary key scan (approval_merge_request_rules_pkey, id = ANY), checked with joe plan on a placeholder id list. The row count is the number locked in 9 (135 here); the earlier cold-cache cost of updating that many rows (157-270 ms, statement 4) is unchanged, but it is now spread over per-batch statements of at most 20 merge requests.

11. Lock the reads before moving them (locked_for_realign)

Security::ScanResultPolicyRead.id_in(ids).locked_for_realign, run at the start of the reads transaction so the shift and the moves in statements 3 and 5 cannot interleave with another realign. NO KEY UPDATE does not block the foreign key checks of MR syncs inserting rules for these reads. The plan uses the same 152 read ids as above, taken from an ARRAY(subquery) stand-in for the id list.

SELECT "scan_result_policies".* FROM "scan_result_policies" WHERE "scan_result_policies"."id" IN (<read ids>) FOR NO KEY UPDATE OF scan_result_policies

Primary key scan (scan_result_policies_pkey, id = ANY) under LockRows, 152 rows locked. Execution 32 ms on a cold cache, shared hit=94 read=76 for the lock scan.

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.

Edited by Alan (Maciej) Paruszewski

Merge request reports

Loading
Loading