You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
    Metadata details:
    filename: persist.go
    path of file: ./repos/grafana/pkg/services/ngalert/migration
    
    the code of the file until where you have to start completion: package migration

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"sort"

	"github.com/grafana/grafana/pkg/infra/log"
	"github.com/grafana/grafana/pkg/services/accesscontrol"
	legacymodels "github.com/grafana/grafana/pkg/services/alerting/models"
	"github.com/grafana/grafana/pkg/services/folder"
	apiModels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions"
    
func (sync *sync) deduplicateTitles(ctx context.Context, pairs []*migmodels.AlertPair) error {
	// First pass to find namespaces.
	seen := make(map[string]struct{})
	namespaces := make([]string, 0)
	for _, pair := range pairs {
		if _, ok := seen[pair.Rule.NamespaceUID]; !ok {
			namespaces = append(namespaces, pair.Rule.NamespaceUID)
			seen[pair.Rule.NamespaceUID] = struct{}{}
		}
	}

	// Populate deduplicators from database.
	titles, err := sync.migrationStore.GetAlertRuleTitles(ctx, sync.orgID, namespaces...)
	if err != nil {
		sync.log.FromContext(ctx).Warn("Failed to get alert rule titles for title deduplication", "error", err)
	}

	titleDedups := make(map[string]*migmodels.Deduplicator, len(namespaces))
	for _, ns := range namespaces {
		titleDedups[ns] = migmodels.NewDeduplicator(sync.migrationStore.CaseInsensitive(), store.AlertDefinitionMaxTitleLength, titles[ns]...)
	}

	for _, pair := range pairs {
		l := sync.log.FromContext(ctx).New("legacyRuleId", pair.LegacyRule.ID, "ruleUid", pair.Rule.UID)

		// Here we ensure that the alert rule title is unique within the folder.
		titleDeduplicator := titleDedups[pair.Rule.NamespaceUID]
		name, err := titleDeduplicator.Deduplicate(pair.Rule.Title)
		if err != nil {
			return err
		}
		if name != pair.Rule.Title {
			l.Info("Alert rule title modified to be unique within folder", "old", pair.Rule.Title, "new", name)
			pair.Rule.Title = name
		}
	}

	return nil
}