Mon parcours dans un énorme travail de rebake de posts

Je poursuis cette conversation depuis ‘Rebuild HTML for entire topic’ car mes expériences prennent une direction tout à fait différente et je pense qu’il pourrait être utile de partager mes réflexions et résultats au fur et à mesure.

Ma situation est la suivante : nous sommes sur le point de lancer un nouveau forum migré contenant plus de 4 millions de messages. Ceux-ci nécessiteront un rebaking lorsque nous passerons au domaine final, et les messages devront également être traités pour s’assurer que les images sont correctement intégrées, etc.

Mes préoccupations sont les suivantes :

  • Le rebaking n’est pas un processus rapide. J’ai optimisé notre serveur de 16 Go/6 cœurs, mais je ne parviens pas à aller plus vite que 2-3 messages/seconde, ce qui signifie que le rebaking complet prendra plus de 20 jours.
  • Le rebaking commence par les messages les plus anciens ; je préférerais commencer par les plus récents pour offrir à notre communauté la meilleure expérience possible (en supposant que les nouveaux messages recevront le plus de trafic).
  • Il n’y a aucun moyen de ‘reprendre’ le processus là où il s’est arrêté, et j’ai des raisons de suspecter que je devrai reconstruire au moins une fois au cours des 20 prochains jours.
  • Les tâches de rebaking sont placées dans la file d’attente Sidekiq par défaut, et je crains que cela ne crée d’énormes retards pour les tâches de traitement régulières.

Jusqu’à présent, j’ai fait ce qui suit : après avoir fouillé dans le code et obtenu l’aide du personnel ici, j’ai modifié le fichier lib/tasks/posts.rake pour :

  • Travailler dans l’ordre chronologique inverse, en commençant par les messages les plus récents.
  • Ignorer les messages privés - je veux prioriser les sujets publics en premier.
  • Afficher l’ID actuel du message/sujet afin que je puisse facilement ajouter une clause WHERE à ma requête pour reprendre le traitement à un autre numéro de message.

Voici mon code :

def rebake_posts(opts = {})
  puts "Nouveau rebaking du markdown des messages pour '#{RailsMultisite::ConnectionManagement.current_db}'"

  disable_edit_notifications = SiteSetting.disable_edit_notifications
  SiteSetting.disable_edit_notifications = true

  total = Post.count
  rebaked = 0

    ordered_post_ids = Post.joins(:topic)
      .select('posts.id')
      .where('topics.archetype' => Archetype.default)
      .order("posts.id DESC")
      .pluck(:id)

    ordered_post_ids.in_groups_of(1000).each do |post_ids|
    posts = Post.order(created_at: :desc).where(id:post_ids)
    posts.each do |post|
      rebake_post(post, opts)
      print_status(rebaked += 1, total)
      puts " > rebaking post id #{post.id} pour topic id #{post.topic_id}"
    end
  end

  SiteSetting.disable_edit_notifications = disable_edit_notifications

  puts "", "#{rebaked} messages traités !", "-" * 50
end

Prochaine étape : je cherche à savoir comment créer ces tâches dans la file d’attente à faible priorité. Toute suggestion serait la bienvenue :slight_smile:

11 « J'aime »

Now I’ve started my first large test, I noticed that the jobs processing has made several huge ‘steps’ in speed. I suspect this may have to do with a large number of my attached images having been moved to the tombstone - this is another ongoing project.

1 « J'aime »

This sounds like an improvement. Perhaps submit a PR.

And it may make sense to do something such that you don’t have to rebske and un-tombstone.

The recover_from_tombstone script is a bit problematic - I’ve discovered several issues with it. I’ll report on those later.

3 « J'aime »

Yes this is very dumb, however it appears Rails / ActiveRecord has no concept of descending ID order when iterating through records, apparently.

Yes I learned that too :slight_smile: With the help of your team I figured out how to work around it though. I’m not sure this is a smart or even fast way of doing it, but it works for me.

1 « J'aime »

Next issue: our new site will already go live while the posts:rebake job is running. Will having a large number of jobs in the default queue slow down regular site processes, and should I try to have posts:rebake start its jobs in the low priority queue instead? Or is this automatically handled?

So far, it seems that the queue that a job will be created in is a property of the job’s class, I’m not sure I could influence this in some way from within the posts.rake script?

If not, I’ll throttle the creation of new jobs to make sure the queue isn’t filling up.

I think there’s also a ‘version’ column on the posts table that you can null out to cause gradual rebaking, too. I think it does 100 posts every time the job triggers.

4 « J'aime »

Does that version rebake task go in newest posts first order @sam?

Yes it does, changed that a while back:

Limit is still 100 @riking but can be configured per:

3 « J'aime »

So rather than running rake posts:rebake, one should instead do Posts.all.update_all('baked_version: null') and all posts will be rebaked in batches according to rebake_old_posts_count?

3 « J'aime »

We should normalize the rake task to go in descending ID order as well @techapj. Unless this is super hard, many hours of work, or something?

1 « J'aime »

Agree, but it is a bit tricky cause we would need to carry a big list of ids in memory. I wonder if we should amend it so the rake task is resumable?

Have rake posts:rebake reset version and just work through old posts using calls to rebake_old

And add rake posts:rebake:resume that simply resumes an interrupted rebake.

Downside here is that posts:rebake would unconditionally cause posts to rebake at some point in time even if the task is interrupted, but this may not matter.

3 « J'aime »

Is carrying a list of integer IDs in memory really that expensive?

1 « J'aime »

we can probably live with it to be honest … that retains the tasks working exactly as they do today (in reverse order). Though something in me wants these tasks to be resumable cause if you are working through 20 million posts this can take many hours and if it breaks half way through it can be very frustrating to start from scratch.

5 « J'aime »

Maybe V1 can be the simple version with a comment

// TODO: make this resumable because carrying around 20 million ids in memory is not a great idea long term

6 « J'aime »

Done via:

4 « J'aime »

I’ve used a script that was resumable at the topic level by using the custom fields. Here’s one that skips private messages (since my import had a LOT of them and they weren’t a priority):

Topic.includes(:_custom_fields).where(archetype: Archetype.default).find_each do |t|
  unless t.custom_fields["import_rebake"].present?
    t.posts.select(:id).find_each do |post|
      Jobs.enqueue(:process_post, {post_id: post.id, bypass_bump: true, cook: true})
    end
    t.custom_fields["import_rebake"] = Time.zone.now
    t.save
  end
end

(This filled up Sidekiq’s default queue, so it’s not useful if you want to launch your site before the rebakes are completed.)

After they’re all done, all the TopicCustomField records with name “import_rebake” can be deleted.

6 « J'aime »

Yes, and @bartv would be able to get his “rebuild for just one topic” by doing:

Posts.where(topic_id: 1234).update_all('baked_version = NULL')
4 « J'aime »

What’s the frequency of these new batches, and how can you monitor the progress?

2 « J'aime »