Requests are answered from stale document data following a `didChange`

Open
#4,279 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
45/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
ruby
Domain
devtools

Research direction

Start with the reader loop in lib/ruby_lsp/base_server.rb (L46-L83) and the queueing of text-sync notifications at L100, then read Document#push_edits in lib/ruby_lsp/document.rb and the semantic-tokens handler at lib/ruby_lsp/server.rb L549. Run the standalone ruby_lsp_ordering_repro.rb script to see the stale results deterministically, then make a request arriving after a didChange wait for that change to be applied. Done means all three scenarios return fresh results and a regression test covers the ordering.

Written by the indexing model from the issue text.

Description

bug
Description
Ruby LSP Information
  • Ruby LSP 0.26.11. The code involved is unchanged on main (checked at ad2996afdf).
  • Ruby 3.2.2 (rbenv), macOS 26.7.2, Apple silicon.
  • Editor: first seen in BBEdit. The reproduction below doesn't use an editor; it's a standalone stdio client.
Description

If a textDocument/didChange and a request for the same document reach the server together, the
request is answered from the document as it was before the change. That holds for any request
that arrives before the worker thread has applied the change. The server reports no error; the
answer just describes the previous text.

The reproduction shows it for three requests:

Request Effect
textDocument/semanticTokens/full tokens on the wrong lines (drawn in the middle of other words)
textDocument/documentSymbol symbols on the wrong lines
textDocument/completion the item's textEdit range is measured on the pre-change text; after a Backspace the range is one character too long, so accepting the completion deletes the character after it (here, the line break)

LSP allows a server to handle messages concurrently only when that doesn't change the results
(spec section "Request, Notification and Response Ordering"). These results depend on the
didChange the client sent before the request.

Who hits it. A client that sends each keystroke's didChange at once rarely sees this. A
client that batches edits and sends them just before its next request sees it nearly every time,
because the change and the request then arrive together.

Cause
  • The reader thread parses a request's document as soon as the request arrives:
    base_server.rb L46-L83,
    document.parse! at L61.
  • Text synchronization notifications are queued for the worker
    (L100) and
    applied later. Document#push_edits only sets @needs_parsing = true
    (document.rb L93-L106).
  • Handlers use the existing parse result without parsing again, e.g. dispatcher.visit(document.ast)
    in text_document_semantic_tokens_full
    (server.rb L549).
  • So when the reader parses a request before the worker has applied a preceding didChange, the
    worker handles the request with the old parse.

It depends on thread timing:

  • If both messages are read from stdin in one go, the reader always parses first. The reproduction
    sends them in one write to make this deterministic.
  • On an idle server, a few milliseconds between the two messages usually avoids it.
  • When the worker is busy, a pause doesn't help. With one ~18 ms semantic-tokens request queued
    ahead, a 5 ms pause still gave stale tokens 2 of 2 times; with ten requests queued ahead, a 50 ms
    pause gave stale tokens 1 time in 2.
Reproduction steps
  1. Save the script below as ruby_lsp_ordering_repro.rb (Ruby standard library only).
  2. Run ruby ruby_lsp_ordering_repro.rb. It starts ruby-lsp in a temporary directory; set
    RUBY_LSP_COMMAND to use a different command.
  3. Each scenario runs twice: didChange and request sent together, then 100 ms apart. Output with 0.26.11:
Server: Ruby LSP 0.26.11  Ruby 3.2.2  arm64-darwin22

semanticTokens  didChange + request back to back  STALE  tokens are 3 line(s) off: they describe the text before the didChange
semanticTokens  didChange + request 100 ms apart  OK     tokens match a fresh open of the edited text
documentSymbol  didChange + request back to back  STALE  greet reported on line 2; it is on line 5
documentSymbol  didChange + request 100 ms apart  OK     greet reported on line 5; it is on line 5
completion      didChange + request back to back  STALE  textEdit range (6,0)-(6,6); applying it gives "Greeterputs(\"done\")\n"
completion      didChange + request 100 ms apart  OK     textEdit range (6,0)-(6,5); applying it gives "Greeter\n"

Reproduced: 3 request(s) answered from the text before the didChange.
ruby_lsp_ordering_repro.rb
#!/usr/bin/env ruby
# frozen_string_literal: true

# Reproduction: Ruby LSP answers a request using the document as it was BEFORE a
# textDocument/didChange that it received ahead of the request.
#
# The didChange and the request are sent back to back (in one write, which makes the race
# deterministic; a client that sends them in quick succession hits it too). Each scenario is
# then repeated with a 100 ms pause between the two messages, which gives the correct answer.
#
# Usage:
#   ruby ruby_lsp_ordering_repro.rb [workspace_dir]
#
# The server command defaults to `ruby-lsp`; override with RUBY_LSP_COMMAND, e.g.
#   RUBY_LSP_COMMAND="bundle exec ruby-lsp" ruby ruby_lsp_ordering_repro.rb
# With no workspace_dir, a temporary directory is used (Ruby LSP may set up its composed
# bundle there on first launch).
#
# Only the Ruby standard library is used.

require "json"
require "open3"
require "tmpdir"

class Client
  attr_reader :server_info

  def initialize(command, workspace)
    @stdin, @stdout, @stderr, @wait = Open3.popen3(*command, chdir: workspace)
    @write_lock = Mutex.new
    @lock = Mutex.new
    @arrived = ConditionVariable.new
    @responses = {}
    @next_id = 0
    Thread.new { @stderr.each_line { |_| } } # keep stderr drained
    Thread.new { read_loop }
  end

  def next_id
    @next_id += 1
  end

  def request(method, params)
    { jsonrpc: "2.0", id: next_id, method: method, params: params }
  end

  def notification(method, params)
    { jsonrpc: "2.0", method: method, params: params }
  end

  # Writes every message in ONE write, so they reach the server together.
  def send_together(*messages)
    @write_lock.synchronize do
      @stdin.write(messages.map { |m| frame(m) }.join)
      @stdin.flush
    end
  end

  def send_separated(*messages, pause:)
    messages.each_with_index do |m, i|
      sleep(pause) if i.positive?
      send_together(m)
    end
  end

  def result_of(message, timeout: 60)
    deadline = Time.now + timeout
    @lock.synchronize do
      until @responses.key?(message[:id])
        remaining = deadline - Time.now
        raise "timed out waiting for #{message[:method]}" if remaining <= 0

        @arrived.wait(@lock, remaining)
      end
      response = @responses.delete(message[:id])
      raise "#{message[:method]} failed: #{response["error"]}" if response["error"]

      response["result"]
    end
  end

  def call(method, params)
    message = request(method, params)
    send_together(message)
    result_of(message)
  end

  def start(workspace)
    result = call("initialize", {
      processId: Process.pid,
      rootUri: "file://#{workspace}",
      capabilities: {
        textDocument: {
          semanticTokens: { requests: { full: true }, tokenTypes: [], tokenModifiers: [], formats: ["relative"] },
          completion: { completionItem: { snippetSupport: false } },
          documentSymbol: { hierarchicalDocumentSymbolSupport: true },
        },
      },
    })
    @server_info = result["serverInfo"]
    send_together(notification("initialized", {}))
  end

  def open(uri, text)
    send_together(notification("textDocument/didOpen", {
      textDocument: { uri: uri, languageId: "ruby", version: 1, text: text },
    }))
  end

  def stop
    call("shutdown", nil)
    send_together(notification("exit", nil))
  rescue StandardError
    nil
  end

  private

  def frame(message)
    body = JSON.generate(message)
    "Content-Length: #{body.bytesize}\r\n\r\n#{body}"
  end

  def read_loop
    loop do
      headers = {}
      while (line = @stdout.gets)
        line = line.strip
        break if line.empty?

        name, value = line.split(":", 2)
        headers[name.downcase] = value.strip
      end
      break if headers.empty?

      message = JSON.parse(@stdout.read(Integer(headers["content-length"])))
      if message.key?("id") && !message.key?("method")
        @lock.synchronize do
          @responses[message["id"]] = message
          @arrived.broadcast
        end
      elsif message.key?("id")
        # a request from the server (e.g. window/workDoneProgress/create): answer it
        send_together({ jsonrpc: "2.0", id: message["id"], result: nil })
      end
    end
  end
end

SOURCE = <<~RUBY
  class Greeter
    def greet(name)
      puts("Hello, \#{name}")
    end
  end

  Greete
  puts("done")
RUBY

ADDED_LINES = "# one\n# two\n# three\n"
COMPLETION_LINE = SOURCE.lines.index("Greete\n")

def decode_tokens(result)
  data = result ? result["data"] : []
  line = 0
  column = 0
  data.each_slice(5).map do |delta_line, delta_start, length, type, _modifiers|
    if delta_line.zero?
      column += delta_start
    else
      line += delta_line
      column = delta_start
    end
    [line, column, length, type]
  end
end

def symbol_line(result, name)
  pending = Array(result).dup
  until pending.empty?
    symbol = pending.shift
    return symbol.dig("range", "start", "line") + 1 if symbol["name"] == name

    pending.concat(Array(symbol["children"]))
  end
  nil
end

def greeter_item(result)
  items = result.is_a?(Hash) ? result["items"] : Array(result)
  items.find { |item| item["label"] == "Greeter" }
end

def apply_text_edit(text, edit)
  lines = text.lines
  offset = ->(position) { lines[0...position["line"]].sum(&:length) + position["character"] }
  range = edit["range"]
  text[0...offset.(range["start"])] + edit["newText"] + text[offset.(range["end"])..]
end

def run_scenario(client, workspace, tag, separated)
  uri = "file://#{workspace}/repro_#{tag}_#{separated ? "separated" : "together"}.rb"
  send_pair = lambda do |change, request|
    separated ? client.send_separated(change, request, pause: 0.1) : client.send_together(change, request)
    client.result_of(request)
  end

  case tag
  when "semanticTokens"
    # Insert three comment lines at the top, then ask for semantic tokens.
    reference = "#{uri}.reference.rb"
    client.open(uri, SOURCE)
    client.open(reference, ADDED_LINES + SOURCE)
    client.call("textDocument/semanticTokens/full", { textDocument: { uri: uri } })
    expected = decode_tokens(client.call("textDocument/semanticTokens/full", { textDocument: { uri: reference } }))
    change = client.notification("textDocument/didChange", {
      textDocument: { uri: uri, version: 2 },
      contentChanges: [{ range: { start: { line: 0, character: 0 }, end: { line: 0, character: 0 } }, text: ADDED_LINES }],
    })
    request = client.request("textDocument/semanticTokens/full", { textDocument: { uri: uri } })
    actual = decode_tokens(send_pair.(change, request))
    if actual == expected
      [true, "tokens match a fresh open of the edited text"]
    else
      shift = expected.first[0] - actual.first[0]
      [false, "tokens are #{shift} line(s) off: they describe the text before the didChange"]
    end

  when "documentSymbol"
    # Insert three comment lines at the top, then ask where `greet` is.
    client.open(uri, SOURCE)
    client.call("textDocument/documentSymbol", { textDocument: { uri: uri } })
    change = client.notification("textDocument/didChange", {
      textDocument: { uri: uri, version: 2 },
      contentChanges: [{ range: { start: { line: 0, character: 0 }, end: { line: 0, character: 0 } }, text: ADDED_LINES }],
    })
    request = client.request("textDocument/documentSymbol", { textDocument: { uri: uri } })
    actual = symbol_line(send_pair.(change, request), "greet")
    expected = (ADDED_LINES + SOURCE).lines.index { |l| l.include?("def greet") } + 1
    [actual == expected, "greet reported on line #{actual}; it is on line #{expected}"]

  when "completion"
    # "Greete" -> Backspace -> "Greet", then complete at the caret.
    reference = "#{uri}.reference.rb"
    edited = SOURCE.sub("Greete\n", "Greet\n")
    client.open(uri, SOURCE)
    client.open(reference, edited)
    position = { line: COMPLETION_LINE, character: 5 }
    expected = nil
    60.times do # wait for indexing, until the reference document gets the item
      expected = greeter_item(client.call("textDocument/completion", { textDocument: { uri: reference }, position: position }))
      break if expected

      sleep(1)
    end
    raise "no completion item for Greeter; is indexing finished?" unless expected

    client.call("textDocument/documentSymbol", { textDocument: { uri: uri } })
    change = client.notification("textDocument/didChange", {
      textDocument: { uri: uri, version: 2 },
      contentChanges: [{ range: { start: { line: COMPLETION_LINE, character: 5 }, end: { line: COMPLETION_LINE, character: 6 } }, text: "" }],
    })
    request = client.request("textDocument/completion", { textDocument: { uri: uri }, position: position })
    actual = greeter_item(send_pair.(change, request))
    return [false, "no completion item for Greeter"] unless actual

    range = actual.dig("textEdit", "range")
    result_line = apply_text_edit(edited, actual["textEdit"]).lines[COMPLETION_LINE]
    detail = "textEdit range (#{range.dig("start", "line")},#{range.dig("start", "character")})-" \
      "(#{range.dig("end", "line")},#{range.dig("end", "character")}); " \
      "applying it gives #{result_line.inspect}"
    [actual["textEdit"] == expected["textEdit"], detail]
  end
end

workspace = File.realpath(ARGV[0] || Dir.mktmpdir("ruby-lsp-ordering"))
command = ENV.fetch("RUBY_LSP_COMMAND", "ruby-lsp").split
client = Client.new(command, workspace)
client.start(workspace)
puts "Server: #{client.server_info&.values&.join(" ")}  Ruby #{RUBY_VERSION}  #{RUBY_PLATFORM}"
puts

failures = 0
["semanticTokens", "documentSymbol", "completion"].each do |tag|
  [false, true].each do |separated|
    ok, detail = run_scenario(client, workspace, tag, separated)
    failures += 1 unless ok
    how = separated ? "100 ms apart" : "back to back"
    puts format("%-15s didChange + request %-13s %s  %s", tag, how, ok ? "OK   " : "STALE", detail)
  end
end
client.stop

puts
puts failures.zero? ? "Not reproduced." : "Reproduced: #{failures} request(s) answered from the text before the didChange."
Possible fix

Parse again on the worker just before handling a document request. By then the worker has already
processed every earlier message, including the didChange, because it handles its queue in order.
parse! returns at once when nothing has changed, so the common case costs nothing.

With the module below loaded into the server (RUBYOPT="-r./ruby_lsp_ordering_patch.rb" ruby-lsp),
every scenario in the reproduction passes, including the back-to-back ones:

# frozen_string_literal: true

# Candidate fix for the ordering bug, for testing with ruby_lsp_ordering_repro.rb.
# Load it into the server process, e.g.:
#   RUBYOPT="-r/path/to/ruby_lsp_ordering_patch.rb" ruby-lsp
#
# The reader thread parses a request's document as soon as the request arrives, but
# textDocument/didChange is applied later, on the worker thread. A request that arrives with
# (or right behind) a didChange is therefore handled with a parse of the text before that change:
# push_edits marks the document as needing a parse, but nothing parses it again before the
# request is handled. This re-parses on the worker, just before a document request is handled.
# By then every earlier message, including the didChange, has been processed, because the worker
# handles its queue in order. parse! returns at once when nothing has changed, so in the usual
# case this costs nothing.

require "ruby_lsp/internal"

module RubyLspOrderingPatch
  def handle_incoming_message(message)
    method = message[:method]
    uri = message.dig(:params, :textDocument, :uri)

    if message.key?(:id) && uri && method && !method.start_with?("textDocument/did")
      @global_state.synchronize do
        @store.get(uri).parse!
      rescue RubyLsp::Store::NonExistingDocumentError
        nil
      end
    end

    super
  end
end

RubyLsp::BaseServer.prepend(RubyLspOrderingPatch)

An alternative is to apply textDocument/did* notifications on the reader thread, under the same
lock, before the pre-parse. That would keep all document state changes in arrival order.

Dominant language
Ruby
Stars
2k
Forks
300
Avg merge
2h 54m
Merged PRs (30d)
9

Getting set up

Open in Codespaces

Starts the project's dev container in your browser, under your own GitHub account.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from Shopify/ruby-lsp

All issues in Shopify/ruby-lsp

Similar issues

More Ruby issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.