Limit the number of notes in a single thread
What does this MR do and why?
Replies to a thread fail once it holds 500 notes, behind the limit_notes_per_discussion flag. Today the only limit is 5,000 notes per issue or merge request, so one thread can reach 5,000 notes, and resolving or rendering it touches every one. Product agreed to 500. No thread that got a reply on 2026-11-16 had more than 500 notes.
The check runs in Notes::BuildService and only for replies, so starting a new thread costs no extra query.
Query plans
Each reply runs one new count, capped at 500 rows (Notes::BuildService#notes_limit_reached?). Times below are total time (planning plus execution) on a gitlab-production-main clone. Planning took 17-29 ms on every run.
SELECT COUNT(*) FROM (
SELECT 1 AS one FROM "notes"
WHERE "notes"."project_id" = <project_id> AND "notes"."discussion_id" = '<discussion_id>'
LIMIT 500
) subquery_for_count- Typical thread (8 notes on a
gitlab-org/gitlabmerge request): index scan onindex_notes_on_discussion_id, 13 buffers. Cold 37.7 ms (plan), warm 17.1 ms (plan). - Most common
discussion_idinpg_stats(about 36,000 notes, one per project): BitmapAnd ofindex_notes_on_project_id_and_noteable_typeandindex_notes_on_discussion_id, 48 buffers. Cold 42.8 ms (plan), warm 27.5 ms (plan). - Full thread: no thread on the clone has 500 notes, so this stand-in counts the second most common
discussion_idwith("notes"."project_id" + 0) > 0in place of the project filter. Every row matches and is read from the table, like a real full thread. Index scan, 506 buffers. Cold 843 ms with 505 pages read from disk (plan), warm 30.1 ms (plan).
Personal snippets have no project, so their count drops the project_id filter:
SELECT COUNT(*) FROM (
SELECT 1 AS one FROM "notes" WHERE "notes"."discussion_id" = '<discussion_id>' LIMIT 500
) subquery_for_count- Most common
discussion_id: index-only scan onindex_notes_on_discussion_id, stops at 500 rows, 166 buffers. Cold 38.9 ms (plan), warm 24.5 ms (plan).
References
- #639787
- Data and agreement: #639787 (comment 4260344689) and #639787 (comment 4268229280)
Screenshots or screen recordings
No UI changes.
How to set up and validate locally
-
In a Rails console, enable the flag and lower the limit for this console session:
Feature.enable(:limit_notes_per_discussion) Discussion.send(:remove_const, :MAX_NOTES_LIMIT) Discussion.const_set(:MAX_NOTES_LIMIT, 2) -
Start a thread on any merge request and reply to it twice:
mr = MergeRequest.last user = mr.author first = Notes::CreateService.new(mr.project, user, noteable: mr, note: 'first', type: 'DiscussionNote').execute reply = ->(text) { Notes::CreateService.new(mr.project, user, noteable: mr, note: text, in_reply_to_discussion_id: first.discussion_id).execute } reply.call('second').persisted? # => true reply.call('third').errors.full_messages # => ["Maximum number of comments in this thread exceeded"]
MR acceptance checklist
Evaluate this MR against the MR acceptance checklist. It helps you analyze changes to reduce risks in quality, performance, reliability, security, and maintainability.
Detailed context for AI agents
Where the check lives
Notes::BuildService#execute, in thein_reply_to_discussion_idbranch, right aftersystem_note_reply_error. It returns aNote.newwith a:baseerror, the same shape asdiscussion_not_foundandsystem_note_reply_error, whichNotes::CreateServicealready handles.- Every user reply path goes through that branch: REST
POST .../discussions/:id/notes(lib/api/discussions.rb), the work items discussion notes API (lib/api/helpers/work_items/note_creation.rb), GraphQLcreateNotewithdiscussionId, the web notes and Rapid Diffs controllers, email replies (SentNotificationsetsin_reply_to_discussion_id), draft note publish (DraftNote#publish_params), and the Duo and flow trigger services in EE. SentNotification#note_validbuilds a dry-run reply throughNotes::BuildServicebefore a notification is saved. It passesskip_notes_limit: true. Without that, the email for the note that fills a thread had no savedSentNotification, so its reply address and unsubscribe link pointed at nothing. A real email reply goes throughNotes::CreateServiceand is still rejected.- Not a
Notemodel validation, unlikedoes_not_exceed_notes_limit?. A validation would also run for every note that starts a new thread, and it can't tell a reply from a first note without extra state. System notes, imports andNotes::CopyService(issue move and clone) create notes directly, not throughBuildService, so they are not limited. That keeps moves of old threads with more than 500 notes working. - The check runs before
convert_to_discussion!, so a rejected reply doesn't convert an individual note. An individual note is a one-note thread, so it can't be at the limit anyway.
Query
notes_scopeisproject.notes, the same scopefind_discussionuses. For personal snippets it isNote, so theproject_idfilter drops out.- The
project_idfilter matters:discussion_idis not unique across projects. The most common value in the clone'spg_statsfornotes.discussion_idis on about 36,000 notes, one per project, all on issues. Without the project scope, a reply in one of those threads would count notes from other projects. - Personal snippets: the count has no project scope. A new
discussion_idincludesSecureRandom.hex(Discussion.build_discussion_id), and every note on the most common shared id is on an issue, so a snippet thread is not expected to share an id.LIMIT 500bounds the read either way. This is the plan the automated database review asked for (P1), and the database reviewer ran it too (https://console.postgres.ai/gitlab/projects/gitlab-production-main/sessions/99231/commands/204697). - For a normal thread the planner uses
index_notes_on_discussion_idwith aproject_idfilter. For the shared ids, it does a BitmapAnd withindex_notes_on_project_id_and_noteable_type. - Full thread cost: the stand-in reads 500 heap pages because the 500 notes sit in 500 different projects. Notes in a real 500-note thread are written over time, so they are likely spread out the same way. Cold, that is 843 ms total on the clone, 824 ms of it execution. Warm, it is 30.1 ms, 1.2 ms of it execution. The stand-in's id was not touched before the cold run. An earlier count on the most common id had cached its pages, so its first run is not used as a cold number. Only near-full threads pay this. Threads near 500 notes are rare (data in #639787 (comment 4260344689)). A reply usually comes right after the thread was rendered, which loads the same rows.
Note#does_not_exceed_notes_limit?already runs an uncappednoteable.notes.counton every user note create. - Plans came from
joe explainon agitlab-production-mainthin clone (session 100129), each run twice (cold, then warm). Literals are replaced with placeholders in the SQL above.
Behaviour
- The limit counts every note in the thread: the first note, replies and system notes. That matches the per-noteable limit and how the data in the issue was counted.
- Threads already above 500 keep their notes. They only stop accepting replies.
- Drafts:
DraftNotes::PublishServicekeeps drafts whose note fails to save and returns the error, so a review that replies to a full thread keeps that draft. Checking the limit when the draft is created is follow-up #642251. - Quick-action-only replies in a full thread are rejected too, because the check runs before quick actions. The per-noteable limit skips them because it runs on save. With 500 notes in a thread, this should not matter.
- Two concurrent replies can both pass at 499 and leave the thread a few notes over. It is a soft cap, like the per-noteable limit.
- With
reply_build_service_loads_first_noteoff,find_discussionhas already loaded every note in the thread. The count still runs as its own query to keep one code path.
Feature flag
limit_notes_per_discussion,gitlab_com_derisk, default off, project actor (nil for personal snippets, group work items and epics, which fall back to the global state, so they get the limit only at the global enable).- Rollout issue: #641130
- No changelog trailer, because the flag is off by default.
Specs
spec/services/notes/build_service_spec.rb: at the limit (first note plus a system note, limit stubbed to 2) returns the error and runs the count exactly once, the same thread with the flag off builds the reply and runs no count, a thread below the limit builds the reply, a note in another project with the samediscussion_idis not counted, and a personal snippet thread at the limit returns the error. Withskip_notes_limit: true, a thread at the limit builds the reply.spec/models/sent_notification_spec.rb: on a full thread,record_notesaves the notification andcreate_replyreturns the limit error. It fails without the dry-run skip (the notification is not saved).- Mutation check: dropping the project scope (counting
Noteinstead ofnotes_scope) or running the count before the flag check makes the matching new example fail. - The existing example "does not query the rest of the thread when the first note is unresolved" now anchors its regex at the start. The new
COUNT(*)wrapper containsSELECT 1 AS one FROM "notes", and the example guards theexists?queries inNotes::Discussion#discussion_resolved?, which still start with that text. - Verified locally in an rspec slot:
spec/services/notes/build_service_spec.rb(49 examples) and, before the spec additions,spec/services/notes/create_service_spec.rb(79 examples), 0 failures. After the dry-run fix (b215311a):spec/models/sent_notification_spec.rb,spec/services/notes/build_service_spec.rbandspec/lib/gitlab/email/handler/create_note_handler_spec.rb, 174 examples, 0 failures. The console steps above were not run on GDK.
Out of scope
- Hiding the reply box on full threads. The existing error path shows the message.
- Making the limit an application setting.
- The per-thread resolved-state work in the same issue (draft !271652 (merged)).