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/gitlab merge request): index scan on index_notes_on_discussion_id, 13 buffers. Cold 37.7 ms (plan), warm 17.1 ms (plan).
  • Most common discussion_id in pg_stats (about 36,000 notes, one per project): BitmapAnd of index_notes_on_project_id_and_noteable_type and index_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_id with ("notes"."project_id" + 0) > 0 in 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 on index_notes_on_discussion_id, stops at 500 rows, 166 buffers. Cold 38.9 ms (plan), warm 24.5 ms (plan).

References

Screenshots or screen recordings

No UI changes.

How to set up and validate locally

  1. 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)
  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 the in_reply_to_discussion_id branch, right after system_note_reply_error. It returns a Note.new with a :base error, the same shape as discussion_not_found and system_note_reply_error, which Notes::CreateService already 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), GraphQL createNote with discussionId, the web notes and Rapid Diffs controllers, email replies (SentNotification sets in_reply_to_discussion_id), draft note publish (DraftNote#publish_params), and the Duo and flow trigger services in EE.
  • SentNotification#note_valid builds a dry-run reply through Notes::BuildService before a notification is saved. It passes skip_notes_limit: true. Without that, the email for the note that fills a thread had no saved SentNotification, so its reply address and unsubscribe link pointed at nothing. A real email reply goes through Notes::CreateService and is still rejected.
  • Not a Note model validation, unlike does_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 and Notes::CopyService (issue move and clone) create notes directly, not through BuildService, 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_scope is project.notes, the same scope find_discussion uses. For personal snippets it is Note, so the project_id filter drops out.
  • The project_id filter matters: discussion_id is not unique across projects. The most common value in the clone's pg_stats for notes.discussion_id is 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_id includes SecureRandom.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 500 bounds 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_id with a project_id filter. For the shared ids, it does a BitmapAnd with index_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 uncapped noteable.notes.count on every user note create.
  • Plans came from joe explain on a gitlab-production-main thin 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::PublishService keeps 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_note off, find_discussion has 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 same discussion_id is not counted, and a personal snippet thread at the limit returns the error. With skip_notes_limit: true, a thread at the limit builds the reply.
  • spec/models/sent_notification_spec.rb: on a full thread, record_note saves the notification and create_reply returns the limit error. It fails without the dry-run skip (the notification is not saved).
  • Mutation check: dropping the project scope (counting Note instead of notes_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 contains SELECT 1 AS one FROM "notes", and the example guards the exists? queries in Notes::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.rb and spec/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)).
Edited by Marc Shaw

Merge request reports

Loading
Loading