InvalidEncodingError reports line 1 when the invalid byte is in the row separator detection sample (File/IO input)
まだ誰も着手していません。
評価
調査の方向性
Start in lib/csv/parser.rb at resolve_row_separator and build_scanner, then trace how sampled input reaches InputsScanner and raises InvalidEncodingError. Add a regression test for invalid bytes on a later line in File input, comparing its reported line number with String input. Done when both report the correct line and the relevant CSV tests pass.
索引モデルが issue の本文から書いたものです。
説明
When the input is a File (or another IO) and an invalid byte sequence appears inside the sample read for row separator detection, CSV::InvalidEncodingError always reports line 1, even if the bad byte is on a later line. The same data given as a String or StringIO reports the correct line.
Reproduce
require "csv"
require "tempfile"
def try(label)
yield
rescue CSV::MalformedCSVError => e
puts "#{label}: #{e.class}: #{e.message} (line_number=#{e.line_number})"
end
small = "a,b\n\xFF,1\n".b
large = ("a,b\n\x80,1\n" + "x,y\n" * 16384).b # 64 KiB, no 0xFF byte
[["small", small], ["large", large]].each do |name, data|
Tempfile.create(["t", ".csv"]) do |f|
f.binmode
f.write(data)
f.close
try("#{name} String") { CSV.parse(data.dup.force_encoding("UTF-8")) }
try("#{name} File ") { CSV.read(f.path, encoding: "UTF-8") }
end
end
Actual
csv 3.3.7 (Ruby 4.1.0dev) and current main:
small String: CSV::InvalidEncodingError: Invalid byte sequence in UTF-8 in line 2. (line_number=2)
small File : CSV::InvalidEncodingError: Invalid byte sequence in UTF-8 in line 1. (line_number=1)
large String: CSV::InvalidEncodingError: Invalid byte sequence in UTF-8 in line 2. (line_number=2)
large File : CSV::InvalidEncodingError: Invalid byte sequence in UTF-8 in line 1. (line_number=1)
CSV.foreach(path), CSV.new(File.open(path)) and CSV.new(io) for a pipe give the same result. I see the same with csv 3.1.9 (Ruby 3.0.0, MalformedCSVError), 3.2.8 (Ruby 3.3.0) and 3.3.5 (Ruby 4.0.0). If the bad byte is on line 3, the file case still says line 1.
Expected
line 2. / line_number=2 for the file input too, as for String/StringIO.
Cause
With row_sep: :auto, resolve_row_separator reads a sample with @input.gets(nil, chunk_size) (32 KiB for File, 1 KiB for other IOs):
https://github.com/ruby/csv/blob/v3.3.7/lib/csv/parser.rb#L703-L713
build_scanner computes the line number of an invalid byte only when the sample is the whole input:
https://github.com/ruby/csv/blob/v3.3.7/lib/csv/parser.rb#L886-L901
Otherwise the sample is wrapped in a StringIO for InputsScanner, whose constructor calls read_chunk, which raises InvalidEncoding for the whole sample before any row is parsed:
https://github.com/ruby/csv/blob/v3.3.7/lib/csv/parser.rb#L313-L316
@scanner is still nil at that point, so parse reports @lineno + 1, i.e. 1:
https://github.com/ruby/csv/blob/v3.3.7/lib/csv/parser.rb#L426-L433
So the line is wrong whenever the bad byte is in a sample that doesn't reach EOF (the "large" case above).
The "small" case hits this too, because IO#gets(nil, limit) stops right after a 0xFF byte. For rs = nil, rb_io_getline_0 passes newline = -1 to appendline, and search_delim does memchr(p, -1, len), which matches 0xFF. So the sample is only "a,b\n\xFF", not the whole file:
https://github.com/ruby/ruby/blob/v4.0.0/io.c#L4200
https://github.com/ruby/ruby/blob/v4.0.0/io.c#L3885
File.binwrite("t", "ab\xFFcd")
File.open("t", "rb") { |f| f.gets(nil, 100) } #=> "ab\xFF"
That part looks like a Ruby core issue (I can report it separately), but csv would still report the wrong line for large inputs even after it is fixed.
Possible fix
Run the same per-line check as the "whole input" branch on the samples before building InputsScanner:
if string
- unless string.valid_encoding?
- index = string.lines(@row_separator).index do |line|
- !line.valid_encoding?
- end
- if index
- raise InvalidEncodingError.new(@encoding, @lineno + index + 1)
- end
- end
+ check_sample_encoding(string)
Scanner.new(string)
else
+ check_sample_encoding(@samples.join(""))
inputs = @samples.collect do |sample|
StringIO.new(sample)
end
@@
+ def check_sample_encoding(sample)
+ return if sample.valid_encoding?
+ index = sample.lines(@row_separator).index do |line|
+ !line.valid_encoding?
+ end
+ if index
+ raise InvalidEncodingError.new(@encoding, @lineno + index + 1)
+ end
+ end
With this change both cases above report line 2, and the test suite passes with and without CSV_PARSER_SCANNER_TEST=yes. Like the existing string branch, it raises before yielding the rows that come before the bad line in the sample, which is what happens today anyway. I can open a PR with a test if this direction is OK.
🤖 Generated with Claude Code
- 主要言語
- Ruby
- スター
- 220
- フォーク
- 139
- 平均マージ
- 1日 1時間
- マージ済み PR(30日)
- 2
環境構築
このプロジェクトには開発コンテナ、Dockerfile、コントリビューションガイドがありません。まず README を読み、一般的な手順ははじめてのコントリビューションガイドを参照してください。
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
ruby/csv のほかの issue
-
Unknown converter name is silently accepted and later fails with "undefined method 'arity' for nil"オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 57/100
-
Timeout on Windows再び着手できるかも @kou が 406 日前に担当しましたが、オープン中のプルリクエストはありません。 オープン
-
難易度 4/5 3〜5日 初心者へのやさしさ 35/100
-
難易度 4/5 3〜5日 初心者へのやさしさ 25/100
-
難易度 5/5 1週間以上 初心者へのやさしさ 15/100
似ている issue
-
🐛 bug 👩💻 équipe CE 🧑🏭 entreprises
難易度 2/5 1〜3時間 初心者へのやさしさ 76/100
betagouv/conseillers-entreprises#4808 ·
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 76/100
yosiat/panko_serializer#250 ·
-
難易度 1/5 1時間未満 初心者へのやさしさ 75/100
cline/mcp-marketplace#3886 ·
-
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100