discourse/discourse · error · RuntimeError

Query returned a non-existent post ID: #

Error message

Query returned a non-existent post ID:
#{result.post_id}

What it means

Runtime check while sampling badge preview rows for post-targeted badges: the returned post_id must correspond to an existing Post. Guards against queries that yield stale or fabricated post ids (e.g. from deleted posts or wrong joins).

Solutions

  1. Join posts properly and filter deleted rows if appropriate
  2. Ensure the post_id expression points at posts.id rather than another table's id column
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at app/services/badge_granter.rb:381 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of discourse/discourse@1b2d7253e8 (2026-08-26). Data as JSON: /api/errors/a58e6b9b07b4a176. Report an issue: GitHub.

Appendix: source

Thrown at app/services/badge_granter.rb:381

    query_plan = nil
    # HACK: active record sanitization too flexible, force it to go down the sanitization path that cares not for % stuff
    # note mini_sql uses AR sanitizer at the moment (review if changed)
    query_plan = DB.query_hash("EXPLAIN #{sql} /*:backfill*/", params) if opts[:explain]

    sample = DB.query(grants_sql, params)

    sample.each do |result|
      unless User.exists?(id: result.id)
        raise "Query returned a non-existent user ID:\n#{result.id}"
      end
      unless result.granted_at
        raise "Query did not return a badge grant time\n(Try using 'current_timestamp granted_at')"
      end
      if opts[:target_posts]
        raise "Query did not return a post ID" unless result.post_id
        if Post.exists?(result.post_id).blank?
          raise "Query returned a non-existent post ID:\n#{result.post_id}"
        end
      end
    end

    { grant_count: grant_count, sample: sample, query_plan: query_plan }
  rescue => e
    { errors: e.message }
  end

  MAX_ITEMS_FOR_DELTA = 200
  def self.backfill(badge, opts = nil)
    return unless SiteSetting.enable_badges
    return unless badge.enabled
    return if badge.query.blank?

    post_ids = user_ids = nil
    post_ids = opts[:post_ids] if opts
    user_ids = opts[:user_ids] if opts

View on GitHub (pinned to 1b2d7253e8)