diff --git a/server/datastore/mysql/apple_mdm.go b/server/datastore/mysql/apple_mdm.go index edb395872f..7a9a7a0ab1 100644 --- a/server/datastore/mysql/apple_mdm.go +++ b/server/datastore/mysql/apple_mdm.go @@ -5714,11 +5714,13 @@ func (ds *Datastore) CleanupHostMDMCommands(ctx context.Context) error { func (ds *Datastore) CleanupHostMDMAppleProfiles(ctx context.Context) error { // Delete pending commands that don't have a corresponding entry in nano_enrollment_queue. - // This could occur due to errors (i.e., large server/DB load) or server being stopped while processing the profiles. + // This could occur when the host re-enrolls in MDM with outstanding Pending commands. + // 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 - LEFT JOIN nano_enrollment_queue neq ON hmap.host_uuid = neq.id AND hmap.command_uuid = neq.command_uuid + -- ANTIJOIN: Delete rows that don't have a corresponding entry in nano_enrollment_queue + LEFT JOIN nano_enrollment_queue neq ON hmap.host_uuid = neq.id 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`, fleet.MDMDeliveryPending) if _, err := ds.writer(ctx).ExecContext(ctx, stmt); err != nil {