From 618f31e1015004a11518c62fa7b66de0696ff827 Mon Sep 17 00:00:00 2001 From: Pablo Monfort Date: Thu, 21 May 2026 22:24:21 -0300 Subject: [PATCH] AO3-6272 Fix chapter count caching 0 after posting draft --- app/controllers/works_controller.rb | 2 ++ spec/controllers/works/drafts_spec.rb | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/app/controllers/works_controller.rb b/app/controllers/works_controller.rb index 61e6ad43a0..4d8a537ec6 100755 --- a/app/controllers/works_controller.rb +++ b/app/controllers/works_controller.rb @@ -614,6 +614,8 @@ def post_draft # Instead, as the work in this context is reduced its first chapter, we copy the value directly @work.word_count = @work.first_chapter.word_count @work.save + # AO3-6272: write chapter count to cache after save to avoid stale replica data + Rails.cache.write(@work.key_for_chapter_posted_counting(@work), 1) if !@collection.nil? && @collection.moderated? redirect_to work_path(@work), notice: ts('Work was submitted to a moderated collection. It will show up in the collection once approved.') diff --git a/spec/controllers/works/drafts_spec.rb b/spec/controllers/works/drafts_spec.rb index 81a9a51473..6502e4c747 100644 --- a/spec/controllers/works/drafts_spec.rb +++ b/spec/controllers/works/drafts_spec.rb @@ -132,6 +132,31 @@ ) end + # AO3-6272: In production, a read replica may return stale data + # right after posting, causing the chapter count to cache as 0. + it "should show the correct chapter count after posting the draft" do + draft = create(:draft, authors: [drafts_user.default_pseud]) + + original_cache = Rails.cache + Rails.cache = ActiveSupport::Cache::MemoryStore.new + + begin + put :post_draft, params: { id: draft.id } + + draft.reload + expect(draft.first_chapter.posted).to be true + + # Simulate a stale read replica returning 0 posted chapters. + # The cache should already hold the correct value from post_draft. + stale_relation = double(count: 0) + allow(draft).to receive(:chapters).and_return(double(posted: stale_relation)) + + expect(draft.number_of_posted_chapters).to eq(1) + ensure + Rails.cache = original_cache + end + end + it "should only count the words of the first, published, chapter after posting the draft" do draft = create(:draft, authors: [drafts_user.default_pseud]) create(:chapter, :draft, work: draft)