Skip to content

CSV#shift causes unbounded memory growth since v3.3.6 #378

Closed
scudco/finesse.chat
#65

Description

@sswander

Description

Since csv 3.3.6, reading a file with CSV#shift (and its aliases gets / readline) causes linear unbounded memory growth. It looks like there are unreleased objects that is not garbage collected. Version 3.3.5 is unaffected. CSV#each is not affected.

Steps to reproduce

# repro.rb 
gem "csv", ENV.fetch("CSV_VERSION")
require "csv"
require "tmpdir"

path = File.join(Dir.tmpdir, "repro.csv")
File.write(path, "a,b\n" * 1_000_000)

GC.start
before = GC.stat(:heap_live_slots)

csv = CSV.new(File.open(path))
nil while csv.gets

GC.start(full_mark: true, immediate_sweep: true)
puts "csv #{CSV::VERSION}: retained after full GC = #{GC.stat(:heap_live_slots) - before}"
CSV_VERSION=3.3.5 ruby repro.rb
CSV_VERSION=3.3.6 ruby repro.rb

Expected behavior

Memory does not grow with row count. With CSV_VERSION=3.3.5:

csv 3.3.5: retained after full GC = 186

Actual behavior

With CSV_VERSION=3.3.6:

csv 3.3.6: retained after full GC = 3983794

Upon checking, the retained objects are the parser's bookmark stack. Appending the repro.rb with:

keeps = csv.instance_variable_get(:@parser)
           .instance_variable_get(:@scanner)
           .instance_variable_get(:@keeps)
puts "csv #{CSV::VERSION}: @keeps = #{keeps.size}"

gives @keeps = 0 on 3.3.5 and @keeps = 1000000 on 3.3.6 — exactly one entry per row, each pinning a StringScanner and its chunk string.

System configuration

Ruby version: 3.3.9
CSV version: 3.3.6 (3.3.5 unaffected)

Additional information

Possible cause: change to CSV#shift in lib/csv.rb:

# 3.3.5 — parse() entered once, paused and resumed via an Enumerator
def shift
  parser_enumerator.next
end
def parser_enumerator
  @parser_enumerator ||= parser.parse
end

# 3.3.6 — parse() re-entered and abandoned on every call
def shift
  parser.parse do |row|
    return row
  end
  nil
end

Activity

  1. added a commit that references this issue on Oct 28, 2026
    c85db27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions