Optimize clean up apple profiles query (#36405)

<!-- Add the related story/sub-task/bug number, like Resolves #123, or
remove if NA -->
**Related issue:** Resolves #35601 

# Checklist for submitter

If some of the following don't apply, delete the relevant line.

- [x] Changes file added for user-visible changes in `changes/`,
`orbit/changes/` or `ee/fleetd-chrome/changes`.
See [Changes
files](https://github.com/fleetdm/fleet/blob/main/docs/Contributing/guides/committing-changes.md#changes-files)
for more information.

## Testing

- [x] QA'd all new/changed functionality manually
This commit is contained in:
Magnus Jensen 2025-11-27 17:02:57 -03:00 committed by GitHub
parent 8a14f7c066
commit 06761243d7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 18 additions and 7 deletions

View file

@ -0,0 +1 @@
* Optimized the cleanup Apple host profiles query to reduce probability of DB locking.

View file

@ -6754,13 +6754,23 @@ func (ds *Datastore) CleanupHostMDMAppleProfiles(ctx context.Context) error {
// This could also occur due to errors (i.e., large server/DB load) or server being stopped while processing the profiles.
// After the entry is deleted, the mdm_apple_profile_manager job will try to requeue the profile.
stmt := fmt.Sprintf(`
DELETE hmap FROM host_mdm_apple_profiles AS hmap
-- ANTIJOIN: Delete rows that don't have a corresponding entry in nano_enrollment_queue
-- Note that a given host may have multiple nano_enrollments(device and user) and thus we
-- need to account for the use of either of them in the join
LEFT JOIN (nano_enrollment_queue neq INNER JOIN nano_enrollments ne ON neq.id = ne.id AND ne.enabled = 1)
ON ne.device_id = hmap.host_uuid AND hmap.command_uuid = neq.command_uuid AND neq.active = 1
WHERE neq.id IS NULL AND (hmap.status IS NULL OR hmap.status = '%s') AND hmap.updated_at < NOW() - INTERVAL 1 HOUR`,
DELETE hmap FROM host_mdm_apple_profiles AS hmap
WHERE (
hmap.status IS NULL
OR hmap.status = '%s'
)
AND hmap.updated_at < NOW() - INTERVAL 1 HOUR
AND NOT EXISTS (
SELECT 1
FROM
nano_enrollments ne
STRAIGHT_JOIN nano_enrollment_queue neq ON neq.id = ne.id
AND neq.command_uuid = hmap.command_uuid
AND neq.active = 1
WHERE
ne.device_id = hmap.host_uuid
AND ne.enabled = 1
);`,
fleet.MDMDeliveryPending)
if _, err := ds.writer(ctx).ExecContext(ctx, stmt); err != nil {
return ctxerr.Wrap(ctx, err, "delete from host_mdm_apple_profiles")