Repository navigation
Description
Branch Name
main
Commit ID
Other Environment Information
- Hardware parameters: Apple Silicon (arm64, macOS), unit test only
- OS type: darwin/arm64
- Go version: go1.27.1
- Reproduced as a Go unit test against
pkg/sql/colexec/externalin a workspace build of main; no server needed.
Actual Behavior
Strict-mode JSONLINE scan of a file whose last-but-one line is a genuinely truncated JSON object (e.g. {"a": 1) followed by a continuation line (e.g. , "s": "x"}) fails with:
invalid input: the line is not a well-formed json object
The message quotes text that does not exist anywhere in the file: the concatenated string is a mix of bytes from the continuation line (and stale bytes of the truncated line), produced by buffer aliasing inside the reader. An instrumented run (same package, driving the reader directly) shows it:
iter 1: raw={"a": 1 -> parse error (unexpected EOF) -> prevStr stored = {"a": 1
iter 2: raw=, "s": "x"} -> prevStr(before) = ", "s": " <- held text already overwritten
-> concat = ", "s": " + ", "s": "x"}"
-> invalid input: the line is not a well-formed json object
So the held-over text is corrupted by the next line's parse before the reader concatenates it. Whenever the overwritten prefix still happens to look like an open object, the run instead ends with incomplete json record at EOF. Either way the record can never complete — the continuation mechanism introduced by the holdover design never succeeds.
Expected Behavior
Per the holdover design in the reader, a genuinely truncated JSONLINE record is held for the next physical line and completed by concatenation:
pkg/sql/colexec/external/reader_csv.go:198-210:transJson2Lines holds the text over in prevStr only when the record is genuinely truncated/"unexpected EOF, wait for next batch"/// Held over for the next line.pkg/sql/colexec/external/reader_csv.go:315-318:if r.prevStr != "" { str = r.prevStr + str; r.prevStr = "" }— the completing concat.- The existing strict behavior at EOF (
incomplete json record,reader_csv.go:160-166, asserted inpkg/sql/colexec/external/jsonline_truncated_eof_test.go, issue [Bug]: Strict JSONLINE LOAD succeeds and silently drops malformed final records at EOF #29842) is the case where no continuation line follows — i.e. the design expects a following line to complete the record.
For the input
{"a": 111, "s": "pp"}
{"a": 1
, "s": "x"}
the strict scan should load two records: (a=111, s="pp") and (a=1, s="x"). Instead it fails with the spurious parse error above.
Steps to Reproduce
Add the file pkg/sql/colexec/external/loom_test_jsonline_continuation_test.go (it reuses the committed test helpers errorModeParam, readAllText, colLine from pkg/sql/colexec/external/error_mode_test.go):
package external
import (
"testing"
"github.com/matrixorigin/matrixone/pkg/sql/parsers/tree"
"github.com/stretchr/testify/require"
)
func TestLoomJSONLineTruncatedRecordContinuation(t *testing.T) {
t.Run("continuation fails with corrupted holdover", func(t *testing.T) {
param, proc, bat := errorModeParam(t, tree.JSONLINE, tree.OBJECT, colLine)
content := `{"a": 111, "s": "pp"}` + "\n" +
`{"a": 1` + "\n" +
`, "s": "x"}` + "\n"
err := readAllText(t, param, proc, bat, content)
if err != nil {
t.Logf("observed: load failed: %v", err)
require.Failf(t, "JSONLINE truncated-record continuation corrupted",
"expected the held-over record %q to complete with line %q and load; got load failure: %v",
`{"a": 1`, `, "s": "x"}`, err)
}
require.Equal(t, 2, bat.RowCount())
})
t.Run("truncated at EOF still fails", func(t *testing.T) {
param, proc, bat := errorModeParam(t, tree.JSONLINE, tree.OBJECT, colLine)
err := readAllText(t, param, proc, bat, `{"a": 111, "s": "pp"}`+"\n"+`{"a": 1`)
require.Error(t, err)
require.Contains(t, err.Error(), "incomplete json record")
})
}Run:
go test ./pkg/sql/colexec/external/ -run TestLoomJSONLineTruncatedRecordContinuation -count=1
The first subtest asserts the documented holdover semantics and fails on current main; the second is the already-tested EOF control and passes.
Additional information
Root cause—an unsynchronized alias across a buffer reuse:
csv_parser.go:323builds each row's field value withutil.UnsafeBytesToString(parser.recordBuffer), sorow[0].Valpoints directly at the parser'srecordBufferbacking array (no copy: JSONLINE setsfieldsEscapedBy = "", sounescapeStringdoes not copy either).reader_csv.go:319-324(transJsonObject2Lines, and the array twintransJsonArray2Linesatreader_csv.go:385-391) stores that alias inr.prevStron the genuinely-truncated path:if jsonLineTruncated(err, str, '{') { r.prevStr = str; return nil, err }.- The next
csvReader.Read()runsreadRecord, which resetsparser.recordBuffer = parser.recordBuffer[:0](csv_parser.go:617) and appends the next line into the SAME backing array. The first append already overwritesprevStr[0]; when the next line exceeds the leftover capacity the append reallocates mid-line and the visible mixture is from two different records. - Back in
transJsonObject2Lines,str = r.prevStr + str(reader_csv.go:315-316) now copies the overwritten bytes, so the completion text is garbage. Consequences observed: a file whose intended completion is valid fails withthe line is not a well-formed json object(comma-prefixed corruption) or degenerates intoincomplete json recordat EOF (when the overwritten prefix still looks like an open object).
The corruption is deterministic for any continuation line of length >= 1 (the first append into recordBuffer immediately clobbers the alias), including the "line longer than current capacity" case, because the append writes into the old array until it outgrows it.
Recommended fix: hold a private copy when the holdover engages, e.g. r.prevStr = strings.Clone(str) in both transJsonObject2Lines and transJsonArray2Lines (cost is only paid on genuinely truncated records). This preserves the documented continuation behavior and the existing EOF failure; no data format or existing-passing behavior changes.
Impact: any strict-mode JSONLINE LOAD/scan of a file containing a JSON record that spans more than one physical line — the case the holdover exists for — cannot load, and reports a parse error naming text that never existed in the file. Tolerant mode is unaffected (it clears prevStr and reports the truncated record as one failed row, reader_csv.go:214-225).
duplicates_checked: 29842, 29855, 12020, 7241 (none cover continuation corruption)
Full reproduction, exactly as Loom ran it
Test file: pkg/sql/colexec/external/loom_test_jsonline_continuation_test.go
(reuses committed helpers errorModeParam / readAllText / colLine from pkg/sql/colexec/external/error_mode_test.go in the same package)
```go
// Copyright 2026 Matrix Origin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package external
import (
"testing"
"github.com/matrixorigin/matrixone/pkg/sql/parsers/tree"
"github.com/stretchr/testify/require"
)
// Strict-mode JSONLINE: a genuinely truncated record must be completed by
// the next physical line per the holdover design (reader_csv.go:198-210,
// 315-318). The holdover stores a string that aliases the CSV parser's
// recordBuffer; the next Read() reuses the same backing array
// (csv_parser.go:617) and overwrites it before the concat.
func TestLoomJSONLineTruncatedRecordContinuation(t *testing.T) {
t.Run("continuation fails with corrupted holdover", func(t *testing.T) {
param, proc, bat := errorModeParam(t, tree.JSONLINE, tree.OBJECT, colLine)
// line 2 is a complete record; line 3+4 form one truncated record:
// {"a": 1 continued by ", "s": "x"} -> {"a": 1, "s": "x"}
content := `{"a": 111, "s": "pp"}` + "\n" +
`{"a": 1` + "\n" +
`, "s": "x"}` + "\n"
err := readAllText(t, param, proc, bat, content)
if err != nil {
t.Logf("observed: load failed: %v", err)
require.Failf(t, "JSONLINE truncated-record continuation corrupted",
"expected the held-over record %q to complete with line %q and load; got load failure: %v",
`{"a": 1`, `, "s": "x"}`, err)
}
require.Equal(t, 2, bat.RowCount())
})
t.Run("truncated at EOF still fails", func(t *testing.T) {
param, proc, bat := errorModeParam(t, tree.JSONLINE, tree.OBJECT, colLine)
err := readAllText(t, param, proc, bat, `{"a": 111, "s": "pp"}`+"\n"+`{"a": 1`)
require.Error(t, err)
require.Contains(t, err.Error(), "incomplete json record")
})
}
```
Run (from repo root, with the workspace cgo flags if building cgo from scratch):
go test ./pkg/sql/colexec/external/ -run TestLoomJSONLineTruncatedRecordContinuation -count=1
Expected on a fixed build: both subtests PASS.
Observed on 861a2c4cb6: the first subtest FAILS with
observed: load failed: invalid input: the line is not a well-formed json object
while the EOF control passes. Reproduced 3+ runs, also with -race; fully deterministic.Found by Loom bug hunt (module: custom-de41a00730; tests: unit, white-box, concurrency; severity: S1)
合并跟踪:JSONLINE续行reader正确性与资源边界
本项统一跟踪 #31280、#31850、#31304、#31851,唯一负责人:@iamlinjunhong。这是问题整理,不代表修复完成或验收通过;各来源的独立复现与验收仍须分别完成。以下证据为原报告/评论的记录,不是本轮重新实测。
独立验收与边界
- [Bug]: JSONLINE truncated-record holdover aliases a reused parser buffer, so record continuation never works #31280:[Bug]: JSONLINE truncated-record holdover aliases a reused parser buffer, so record continuation never works。逐项复现并验证下方该来源的 Expected Behavior/验收要求,不能以另一来源通过替代。
- [Bug]: JSONLINE truncated-record holdover aliases the reused parser buffer and silently inserts wrong values #31850:[Bug]: JSONLINE truncated-record holdover aliases the reused parser buffer and silently inserts wrong values。逐项复现并验证下方该来源的 Expected Behavior/验收要求,不能以另一来源通过替代。
- [Bug]: JSONLINE truncated-record holdover grows prevStr past LargestEntryLimit with no size bound #31304:[Bug]: JSONLINE truncated-record holdover grows prevStr past LargestEntryLimit with no size bound。逐项复现并验证下方该来源的 Expected Behavior/验收要求,不能以另一来源通过替代。
- [Bug]: JSONLINE truncation holdover re-parses the whole prefix every line and grows past LargestEntryLimit #31851:[Bug]: JSONLINE truncation holdover re-parses the whole prefix every line and grows past LargestEntryLimit。逐项复现并验证下方该来源的 Expected Behavior/验收要求,不能以另一来源通过替代。
- buffer持有拷贝;object/array、跨batch、成功LOAD错值和错误文本;累计record限额及O(n²)重解析分别验收,CSV限额对照。
范围边界:不得把所有权修复当资源限额通过;parse_jsonl TVF是另一入口,另批。
注意:#31850 评论提供了基于 a548509 的候选补丁及作者测试记录,尚不能据此宣称已合并或 SQL LOAD 已验收;它明确不解决 #31851 的资源边界。旧报告的默认限额数值因版本不同,须按目标提交的实际配置验证。
来源 #31850:原始报告完整保留
#31850 完整复现、版本、证据和预期
Branch Name
main
Commit ID
Other Environment Information
- Hardware: Apple Silicon (arm64, macOS 15)
- OS: darwin/arm64, Go 1.27.1
- Standalone
mo-servicelaunched frometc/launch(single launch.toml, CN port-base 38000, no non-default config except port offsets); reproduction is also a plain Go unit test againstpkg/sql/colexec/external
Actual Behavior
A JSONLINE (format=jsonline, jsondata=array) file whose single record is spread over several physical lines is silently loaded with values that do not exist in the file:
File jl_arr.jsonl:
[111,
[222,
333]
]
The physical-line concatenation of this file is the complete two-value array [111,[222,333]], whose first value is 111.
LOAD DATA INFILE {'filepath'='.../jl_arr.jsonl', 'format'='jsonline', 'jsondata'='array'} INTO TABLE jl2; succeeds and inserts the row a=222, s="[222 333]" (see evidence). The first value 111 vanishes and is replaced by bytes of the second line.
Root cause: CsvReader.prevStr in pkg/sql/colexec/external/reader_csv.go holds over the text of a genuinely truncated JSONLINE record across CSV records. csvparser.Read returns Field.Val values that are unsafe views over the parser's recordBuffer (pkg/sql/util/csvparser/csv_parser.go:347, util.UnsafeBytesToString(parser.recordBuffer)), and every record read resets that buffer in place (parser.recordBuffer = parser.recordBuffer[:0], pkg/sql/util/csvparser/csv_parser.go:733). When the JSONLINE translator stores the truncated record (r.prevStr = str, pkg/sql/colexec/external/reader_csv.go:395 for arrays, :328 for objects) it keeps a raw view of the reused buffer, so the next Read overwrites the held-over text before it is concatenated in transJsonObject2Lines/transJsonArray2Lines (reader_csv.go:320-322, 388-390).
Consequences (same root cause):
- Silent wrong values: whenever the overwritten prefix happens to still form parseable JSON with the appended tail, the load commits a row whose values are a byte mix of several lines (SQL repro above).
- Record continuation never succeeds: for the ordinary pretty-printed case the corrupted accumulation fails with a parse error quoting text that does not exist in the file (e.g.
[1,\n2]fails withinvalid input: the line is not a well-formed json array), even though the holdover design ("unexpected EOF, wait for next batch",reader_csv.go:203-214) intends to complete it. - In tolerant error mode,
__mo_error_textrows record the same corrupted concatenation (param.ErrorMode.RawText = r.prevStr + raw,reader_csv.go:199).
This is a reconfirmation and strengthening of open issue #31280 (which describes the aliasing and the failing continuation): this report adds that the bug is not limited to a failed load -- it silently persists wrong values through a successful LOAD DATA. Fix direction: make the holdover copy the truncated text (r.prevStr = strings.Clone(str), or have the translator copy row[0].Val before the next Read).
Expected Behavior
Per the holdover design in the reader (pkg/sql/colexec/external/reader_csv.go:203-214: "transJson2Lines holds the text over in prevStr only when the record is genuinely truncated"; reader_csv.go:320-322/388-390: the held text must be prepended to the next line unchanged), the record above must load as one row with a=111 (the 2nd JSON value [222,333] stringified into the varchar column), or -- if multi-line records are rejected by policy -- must fail with a clear error. It must never insert values that are not present in the file. Reference for the strict-EOF semantics: jsonline_truncated_eof_test.go and issue #29842 ("incomplete json record" at EOF when no continuation line follows).
Steps to Reproduce
A. SQL level (standalone mo-service, mysql client):
create database loom; use loom;
drop table if exists jl2;
create table jl2(a int, s varchar(64));
-- write file jl_arr.jsonl with exactly these 4 lines: "[111," / "[222," / "333]" / "]"
load data infile {'filepath'='/abs/path/jl_arr.jsonl', 'format'='jsonline', 'jsondata'='array'} into table jl2;
select * from jl2;
-- actual: 222 | "[222 333]" expected: 111 | "[222 333]"B. Go unit test (file pkg/sql/colexec/external/loom_test_jsonline_holdover_test.go; reuses committed helpers errorModeParam, colLine, colA, colS, numTestCols from error_mode_test.go):
package external
import (
"io"
"strings"
"testing"
"github.com/matrixorigin/matrixone/pkg/container/vector"
"github.com/matrixorigin/matrixone/pkg/sql/parsers/tree"
"github.com/stretchr/testify/require"
)
func loomDrain(t *testing.T, format, jsonData string, keep int, content string) (error, int, *CsvReader) {
param, proc, bat := errorModeParam(t, format, jsonData, keep)
t.Cleanup(func() { bat.Clean(proc.Mp()) })
r := &CsvReader{param: param}
r.reader = io.NopCloser(strings.NewReader(content))
parser, err := newCSVParserFromReader(param.Extern, r.reader)
require.NoError(t, err)
r.plh = &ParseLineHandler{csvReader: parser}
for {
finished, e := r.makeBatchRows(proc, bat)
if e != nil {
return e, bat.RowCount(), r
}
if finished {
return nil, bat.RowCount(), r
}
}
}
// The file's only record has first value 111; the load inserts 222.
func TestLoomJSONLineHoldoverSilentWrongValue(t *testing.T) {
err, rows, _ := loomDrain(t, tree.JSONLINE, tree.ARRAY, colLine, "[111,\n[222,\n333]\n]")
require.NoError(t, err)
require.Equal(t, 1, rows)
a := vector.GetFixedAtWithTypeCheck[int32](bat0.Vecs[colA], 0) // bat from loomDrain; see note
_ = a
}Test source as actually run (complete file, pkg/sql/colexec/external/loom_test_jsonline_truncation_budget_test.go) is embedded in the repro field of this report; run with:
export CGO_CFLAGS="-I<repo>/cgo -I<repo>/thirdparties/install/include"
export CGO_LDFLAGS="-L<repo>/thirdparties/install/lib -L<repo>/cgo"
go test ./pkg/sql/colexec/external/ -run 'TestLoomJSONLineSilentWrongRowFromAliasedPrevStr|TestLoomJSONLineTruncationHoldOverCorrupted|TestLoomJSONLineValidMultiLineRecordFails' -count=1 -v
Note: TestLoomJSONLineSilentWrongRowFromAliasedPrevStr asserts the EXPECTED value (a=111) and therefore FAILS on current main; that failure is the bug.
Additional information
- Alias proof (unit): hold over
[12,after a truncated read, then read the next record3;r.prevStr(viewed before any concat) reads"312,"-- byte 0 ([) was overwritten by the new record's3.pkg/sql/util/csvparser/csv_parser.go:347convertsrecordBufferto a string without copying;:733resets it to[:0]for every record. - The holdover assignment is
r.prevStr = strwherestris either the raw parameter (first holdover, alias into the live buffer) or a concat (safe). Only the first holdover aliases; that single overwrite is enough to corrupt every subsequent accumulation. - Existing tests did not cover a multi-line record with a second physical read after the holdover;
jsonline_truncated_eof_test.gostops at EOF. - Related open issues: [Bug]: JSONLINE truncated-record holdover aliases a reused parser buffer, so record continuation never works #31280 (same root cause, continuation-failure symptom), [Bug]: JSONLINE truncated-record holdover grows prevStr past LargestEntryLimit with no size bound #31304 (unbounded growth of the same holdover string).
Full reproduction, exactly as Loom ran it
// File: pkg/sql/colexec/external/loom_test_jsonline_holdover_test.go
// Run (after `make cgo-native-thirdparties-internal` so thirdparties/install exists):
// export CGO_CFLAGS="-I<repo>/cgo -I<repo>/thirdparties/install/include"
// export CGO_LDFLAGS="-L<repo>/thirdparties/install/lib -L<repo>/cgo"
// go test ./pkg/sql/colexec/external/ -run 'TestLoomJSONLineSilentWrongRowFromAliasedPrevStr|TestLoomJSONLineTruncationHoldOverCorrupted|TestLoomJSONLineValidMultiLineRecordFails' -count=1 -v
//
// Reuses committed test helpers from error_mode_test.go: errorModeParam, colA, colS, colLine, numTestCols.
// TestLoomJSONLineSilentWrongRowFromAliasedPrevStr asserts the CORRECT value (111) and FAILS on main = the bug.
package external
import (
"io"
"strings"
"testing"
"github.com/matrixorigin/matrixone/pkg/container/batch"
"github.com/matrixorigin/matrixone/pkg/container/vector"
"github.com/matrixorigin/matrixone/pkg/sql/parsers/tree"
"github.com/matrixorigin/matrixone/pkg/vm/process"
"github.com/stretchr/testify/require"
)
func loomDrainJSONLINE(t *testing.T, param *ExternalParam, proc *process.Process, r *CsvReader, bat *batch.Batch, content string) (error, int) {
t.Helper()
r.reader = io.NopCloser(strings.NewReader(content))
parser, perr := newCSVParserFromReader(param.Extern, r.reader)
require.NoError(t, perr)
r.plh = &ParseLineHandler{csvReader: parser}
for {
finished, e := r.makeBatchRows(proc, bat)
if e != nil {
return e, bat.RowCount()
}
if finished {
return nil, bat.RowCount()
}
}
}
// A JSONLINE array record whose physical-line concatenation is the complete
// two-value array "[111,[222,333]]" (first value 111) loads as a=222: the
// held-over text aliases the parser's reusable record buffer and line 2
// overwrites it in place.
func TestLoomJSONLineSilentWrongRowFromAliasedPrevStr(t *testing.T) {
param, proc, bat := errorModeParam(t, tree.JSONLINE, tree.ARRAY, colLine)
t.Cleanup(func() { bat.Clean(proc.Mp()) })
r := &CsvReader{param: param}
err, rows := loomDrainJSONLINE(t, param, proc, r, bat, "[111,\n[222,\n333]\n]")
t.Logf("err=%v rows=%d", err, rows)
require.NoError(t, err)
require.Equal(t, 1, bat.RowCount())
a := vector.GetFixedAtWithTypeCheck[int32](bat.Vecs[colA], 0)
s := string(bat.Vecs[colS].GetBytesAt(0))
t.Logf("row 0: a=%d s=%q", a, s)
require.Equal(t, int32(111), a, "first value of the record must be 111, not bytes of line 2")
}
// Byte-level proof that prevStr retains an alias into the parser's record
// buffer, which the next read overwrites in place.
func TestLoomJSONLineTruncationHoldOverCorrupted(t *testing.T) {
param, proc, bat := errorModeParam(t, tree.JSONLINE, tree.ARRAY, colLine)
t.Cleanup(func() { bat.Clean(proc.Mp()) })
r := &CsvReader{param: param}
r.reader = io.NopCloser(strings.NewReader("[12,\n3"))
parser, perr := newCSVParserFromReader(param.Extern, r.reader)
require.NoError(t, perr)
r.plh = &ParseLineHandler{csvReader: parser}
row, rerr := r.plh.csvReader.Read(nil)
require.NoError(t, rerr)
require.Equal(t, "[12,", row[0].Val)
_, terr := r.transJson2Lines(proc.Ctx, row[0].Val, param.Attrs, param.Cols, tree.ARRAY)
require.EqualError(t, terr, "unexpected EOF")
require.Equal(t, "[12,", r.prevStr, "prevStr held over")
// Reading the next record overwrites the buffer prevStr points into.
row2, rerr2 := r.plh.csvReader.Read(nil)
require.NoError(t, rerr2)
require.Equal(t, "3", row2[0].Val)
t.Logf("prevStr after next read: %q (want \"[12,\")", r.prevStr)
require.NotEqual(t, "[12,", r.prevStr, "held-over text was overwritten in place")
}
// Without the aliasing the holdover would complete a multi-line record; with
// the corrupted buffer it fails with an error that quotes nonexistent text.
func TestLoomJSONLineValidMultiLineRecordFails(t *testing.T) {
param, proc, bat := errorModeParam(t, tree.JSONLINE, tree.ARRAY, colLine)
t.Cleanup(func() { bat.Clean(proc.Mp()) })
r := &CsvReader{param: param}
err, rows := loomDrainJSONLINE(t, param, proc, r, bat, "[1,\n2]")
t.Logf("err=%v rows=%d", err, rows)
require.Error(t, err)
require.Contains(t, err.Error(), "json")
require.Equal(t, 0, bat.RowCount())
}Found by Loom bug hunt (module: custom-de41a00730; tests: unit, white-box, end-to-end, concurrency; severity: S0)
来源 #31850 的补充证据(2026-10-30T10:16:49Z,MatrixAdventurer)
原评论:#31850 (comment)
原评论完整保留(原作者记录,非本轮实测)
I reproduced the incorrect-value failure and prepared this patch against main at a54850983d9cddaacc97e38a84515ec724c937b7. It also addresses the same buffer-aliasing root cause described in #31280.
When an object or array is first held over, its CSV field string can point into the parser's reusable record buffer. Clone that initial incomplete string before retaining it. Subsequent continuations already concatenate the owned prefix with the next field, so they can retain that result without another clone.
Regression tests drive the production CSV/JSONLINE parser and check the final values for arrays and objects, multi-line continuations, a normal subsequent record, and a record spanning the output-batch boundary. Before the fix, the array case silently returned 222 instead of 111, including across a batch boundary; the object case returned a malformed-JSON error. The tests now pass, along with the existing strict incomplete-record-at-EOF control.
Validation on Linux/amd64 with Go 1.27.1:
go test -p 3 ./pkg/sql/colexec/external -count=1 -timeout=10m
go test -race -p 3 ./pkg/sql/colexec/external -run 'TestJSONLine' -count=1 -timeout=5mBoth passed. gofmt, git diff --check, and git apply --check --whitespace=error passed. The regression uses the real reader with in-memory input; it does not run a MatrixOne server or a SQL-level LOAD DATA.
The separate unbounded holdover / repeated parsing problem in #31851 is not addressed by this patch.
Save this complete diff as a .patch file and apply it with git apply:
diff --git a/pkg/sql/colexec/external/reader_csv.go b/pkg/sql/colexec/external/reader_csv.go
index 7cbb14a..02d44ad 100644
--- a/pkg/sql/colexec/external/reader_csv.go
+++ b/pkg/sql/colexec/external/reader_csv.go
@@ -317,7 +317,8 @@ func (r *CsvReader) transJsonObject2Lines(ctx context.Context, str string, attrs
}
}
res := make([]csvparser.Field, resultSize)
- if r.prevStr != "" {
+ continued := r.prevStr != ""
+ if continued {
str = r.prevStr + str
r.prevStr = ""
}
@@ -325,6 +326,10 @@ func (r *CsvReader) transJsonObject2Lines(ctx context.Context, str string, attrs
if err != nil {
logutil.Errorf("json unmarshal err:%v", err)
if jsonLineTruncated(err, str, '{') {
+ if !continued {
+ // The parser's field string aliases its reusable record buffer.
+ str = strings.Clone(str)
+ }
r.prevStr = str
return nil, err
}
@@ -385,13 +390,18 @@ func (r *CsvReader) transJsonArray2Lines(ctx context.Context, str string, attrs
err error
res = make([]csvparser.Field, 0, len(attrs))
)
- if r.prevStr != "" {
+ continued := r.prevStr != ""
+ if continued {
str = r.prevStr + str
r.prevStr = ""
}
jsonNode, err := bytejson.ParseNodeString(str)
if err != nil {
if jsonLineTruncated(err, str, '[') {
+ if !continued {
+ // The parser's field string aliases its reusable record buffer.
+ str = strings.Clone(str)
+ }
r.prevStr = str
return nil, err
}
diff --git a/pkg/sql/colexec/external/jsonline_holdover_ownership_test.go b/pkg/sql/colexec/external/jsonline_holdover_ownership_test.go
new file mode 100644
index 0000000..c057720
--- /dev/null
+++ b/pkg/sql/colexec/external/jsonline_holdover_ownership_test.go
@@ -0,0 +1,78 @@
+// Copyright 2026 Matrix Origin
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package external
+
+import (
+ "io"
+ "strings"
+ "testing"
+
+ "github.com/matrixorigin/matrixone/pkg/container/vector"
+ "github.com/matrixorigin/matrixone/pkg/sql/parsers/tree"
+ "github.com/stretchr/testify/require"
+)
+
+func TestJSONLineContinuationPreservesInput(t *testing.T) {
+ for _, tc := range []struct {
+ name, shape, input, firstString, secondString string
+ first, second int32
+ }{
+ {
+ name: "array with nested value", shape: tree.ARRAY,
+ input: "[111,\n[222,\n333]\n]\n[5,6]\n",
+ first: 111, firstString: "[222 333]", second: 5, secondString: "6",
+ },
+ {
+ name: "object across lines", shape: tree.OBJECT,
+ input: "{\"a\":111\n,\"s\":\n222}\n{\"a\":5,\"s\":\"ok\"}\n",
+ first: 111, firstString: "222", second: 5, secondString: "ok",
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ param, proc, bat := errorModeParam(t, tree.JSONLINE, tc.shape, colLine)
+ require.NoError(t, readAllText(t, param, proc, bat, tc.input))
+ require.Equal(t, 2, bat.RowCount())
+ require.Equal(t, tc.first, vector.GetFixedAtWithTypeCheck[int32](bat.Vecs[colA], 0))
+ require.Equal(t, tc.firstString, string(bat.Vecs[colS].GetBytesAt(0)))
+ require.Equal(t, tc.second, vector.GetFixedAtWithTypeCheck[int32](bat.Vecs[colA], 1))
+ require.Equal(t, tc.secondString, string(bat.Vecs[colS].GetBytesAt(1)))
+ })
+ }
+}
+
+func TestJSONLineContinuationAcrossBatchBoundary(t *testing.T) {
+ param, proc, bat := errorModeParam(t, tree.JSONLINE, tree.ARRAY, colLine)
+ content := strings.Repeat("[1,2]\n", OneBatchMaxRow-1) + "[111,\n[222,\n333]\n]\n"
+ r := &CsvReader{param: param, reader: io.NopCloser(strings.NewReader(content))}
+ t.Cleanup(func() { require.NoError(t, r.Close()) })
+ parser, err := newCSVParserFromReader(param.Extern, r.reader)
+ require.NoError(t, err)
+ r.plh = &ParseLineHandler{csvReader: parser}
+
+ finished, err := r.makeBatchRows(proc, bat)
+ require.NoError(t, err)
+ require.False(t, finished)
+ require.Equal(t, OneBatchMaxRow-1, bat.RowCount())
+ require.Equal(t, "[111,", r.prevStr)
+
+ bat.CleanOnlyData()
+ finished, err = r.makeBatchRows(proc, bat)
+ require.NoError(t, err)
+ require.True(t, finished)
+ require.Equal(t, 1, bat.RowCount())
+ require.Equal(t, int32(111), vector.GetFixedAtWithTypeCheck[int32](bat.Vecs[colA], 0))
+ require.Equal(t, "[222 333]", string(bat.Vecs[colS].GetBytesAt(0)))
+ require.Empty(t, r.prevStr)
+}来源 #31304:原始报告完整保留
#31304 完整复现、版本、证据和预期
Is there an existing issue for the same bug?
- I have searched. [Bug]: JSONLINE truncated-record holdover aliases a reused parser buffer, so record continuation never works #31280 reports a different defect in the same holdover mechanism (the held text aliases a reused parser buffer, so a continuation line never completes a record); it does not report the missing size bound on the accumulation — the root cause here. [Bug]: Strict JSONLINE LOAD succeeds and silently drops malformed final records at EOF #29842 (closed) was the silent drop of a malformed final record at EOF, already fixed by the
incomplete json recordcheck. [Bug]: mo-dump CSV reports success for valid 12 MiB row but generated LOAD DATA cannot restore it #30640 is about the limit value for legitimate large rows; [Bug]: JSONLINE OUTFILE silently drops a column when SELECT aliases are duplicated #30703 is about JSONLINE OUTFILE duplicate aliases; [Bug]: CSV row-size limit is per-token only; quoted records bypass the 10MB cap and amplify LOAD memory #31285 is the CSV parser per-token row-size bypass. No open PR touches the holdover size.
Branch Name
main
Commit ID
Other Environment Information
- Hardware parameters: Apple Silicon (arm64, macOS); Go unit test only, no server needed
- OS type: darwin/arm64, go1.27.1
- The test reuses the package's committed helpers
errorModeParamandnumTestColsfrompkg/sql/colexec/external/error_mode_test.go.
Actual Behavior
A strict JSONLINE scan of a file with a truncated JSON record holds the incomplete text over in CsvReader.prevStr and concatenates every following physical line onto it, with no size limit of any kind:
transJsonObject2Lines(pkg/sql/colexec/external/reader_csv.go:315-317):str = r.prevStr + str— the concatenation is never measured. When the parse reportsunexpected EOFand the text still opens an object (jsonLineTruncated, reader_csv.go:262-266), the whole accumulated text is stored back as the new holdover (:322-323). The array varianttransJsonArray2Lineshas the identical unbounded accumulation (:383-385, :389-390).- The caller
makeBatchRowsfeeds the growing holdover line after line: on a truncated record it logsunexpected EOF, wait for next batchand continues with the next record (reader_csv.go:201-206), so each incoming line is appended toprevStrand the entire accumulation is re-parsed (allocate + scan) again. - Each raw line alone IS bounded: the CSV parser rejects a single line larger than
config.LargestEntryLimit(10MB) withsize of row cannot exceed the max value of txn-entry-size-limit(pkg/sql/util/csvparser/csv_parser.go:588), precisely so one record cannot exhaust parse memory. The holdover concatenation escapes that cap entirely: a record assembled from N lines can be ~N×10MB of held text with zero checks — memory grows up to (rest of) file size, and the full growing buffer is re-parsed on every new line, O(n²) work. - The scan only errors at EOF with
incomplete json record(reader_csv.go:160-166), after the whole file has been absorbed intoprevStr.
Measured (unit test below, default LargestEntryLimit = 10485760): after a 6-byte opening [{"a":[] and 10 × 1MB still-unterminated lines, prevStr holds 10,485,766 bytes — already past the 10MB row cap — with no error; the re-parses are visible as 11 repeated json unmarshal err:unexpected EOF logs. A truncated or partially-uploaded JSONLINE file therefore makes the CN buffer the remainder of the file in one Go-heap string (invisible to mpool caps) and burn quadratic parse CPU before finally failing — the LOAD DATA memory-exhaustion class this cap exists to prevent.
Expected Behavior
The held-over record is one row of the load. When a record exceeds config.LargestEntryLimit as a single line, the reader already rejects it. The same per-row cap must apply to the assembled record: once the concatenation at reader_csv.go:316 (and :384) would grow past config.LargestEntryLimit, transJsonObject2Lines/transJsonArray2Lines must fail the record immediately with an invalid-input error (and must NOT hold it over for further accumulation) — mirroring the single-line behavior and the documented meaning of the limit (pkg/config/configuration.go:203-204: // largestEntryLimit is the max size for reading file to csv buf).
Steps to Reproduce
Save the test below into the package directory as e.g. loom_test_jsonline_holdover_test.go and run from the repo root:
CGO_CFLAGS="-I$(pwd)/cgo -I$(pwd)/thirdparties/install/include" \
CGO_LDFLAGS="-L$(pwd)/cgo -L$(pwd)/thirdparties/install/lib" \
go test ./pkg/sql/colexec/external -run TestLoomJSONLineHoldoverUnbounded -count=1 -v// Copyright 2026 Matrix One
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package external
import (
"io"
"strings"
"testing"
"github.com/matrixorigin/matrixone/pkg/config"
"github.com/matrixorigin/matrixone/pkg/sql/parsers/tree"
"github.com/stretchr/testify/require"
)
// TestLoomJSONLineHoldoverUnbounded: a truncated JSONLINE record is held over
// in prevStr across lines until a completing line arrives. Each incoming line
// is at most LargestEntryLimit bytes (the csv parser rejects a longer span),
// but the concatenation in prevStr is never measured: a file that opens a
// value and then keeps feeding still-unterminated lines grows the held-over
// record past LargestEntryLimit without any error, keeping the whole thing --
// and re-parsing all of it on every new line -- in memory until EOF.
func TestLoomJSONLineHoldoverUnbounded(t *testing.T) {
param, proc, _ := errorModeParam(t, tree.JSONLINE, tree.OBJECT, numTestCols)
r := &CsvReader{param: param}
// an opening that stays unterminated
_, err := r.transJsonObject2Lines(proc.Ctx, `{"a":[`, param.Attrs, param.Cols)
require.ErrorIs(t, err, io.ErrUnexpectedEOF, "a truncated object must hold over")
require.Equal(t, `{"a":[`, r.prevStr)
// every line keeps the record unterminated, so it keeps growing
chunk := strings.Repeat("1,", 512*1024) // 1MB of still-open content
for range 16 {
_, err = r.transJsonObject2Lines(proc.Ctx, chunk, param.Attrs, param.Cols)
require.ErrorIs(t, err, io.ErrUnexpectedEOF)
require.LessOrEqual(t, len(r.prevStr), config.LargestEntryLimit,
"a held-over record past LargestEntryLimit must be rejected, not accumulated")
}
}Additional information
- Suggested fix: after the concatenation at reader_csv.go:316 (and :384), compare the total with
config.LargestEntryLimit; if exceeded, return a non-truncated invalid-input error (e.g.record size exceeds txn-entry-size-limit) so the latest line is not held over. One guard per variant is sufficient. - The repro's first assertion (the 6-byte holdover) passes — the holdover design itself works as intended; only the bound is missing.
- Relation to [Bug]: JSONLINE truncated-record holdover aliases a reused parser buffer, so record continuation never works #31280: that issue reports the held text being corrupted (parser-buffer aliasing), so continuation never completes — a different root cause with a different fix (copy the held bytes on holdover). This report is about the absence of a size bound on the accumulation. They compose: whichever way the aliasing is fixed, the holdover still grows past the row cap; and one of [Bug]: JSONLINE truncated-record holdover aliases a reused parser buffer, so record continuation never works #31280's own observed endings ("the run instead ends with
incomplete json recordat EOF") is exactly this unbounded-append path continuing line after line until EOF. - The Kafka entry point is NOT affected:
parseOneMessageclearsprevStron every error ("no streaming-LOAD resume across message boundaries", reader_kafka.go:395-398). The vulnerable path is the strict JSONLINE file/streaming scan inmakeBatchRows(reader_csv.go:196-206). - Severity s1: needs a truncated JSONLINE import file (e.g. a partially uploaded or interrupted export); recoverable by fixing the input; no data loss (the load ultimately fails at EOF with
incomplete json record).
Full reproduction, exactly as Loom ran it
Save as pkg/sql/colexec/external/loom_test_jsonline_holdover_test.go (helpers errorModeParam/numTestCols are committed in pkg/sql/colexec/external/error_mode_test.go), then run from the repo root:
CGO_CFLAGS="-I$(pwd)/cgo -I$(pwd)/thirdparties/install/include" CGO_LDFLAGS="-L$(pwd)/cgo -L$(pwd)/thirdparties/install/lib" go test ./pkg/sql/colexec/external -run TestLoomJSONLineHoldoverUnbounded -count=1 -v
--- test file ---
// Copyright 2026 Matrix One
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package external
import (
"io"
"strings"
"testing"
"github.com/matrixorigin/matrixone/pkg/config"
"github.com/matrixorigin/matrixone/pkg/sql/parsers/tree"
"github.com/stretchr/testify/require"
)
// TestLoomJSONLineHoldoverUnbounded: a truncated JSONLINE record is held over
// in prevStr across lines until a completing line arrives. Each incoming line
// is at most LargestEntryLimit bytes (the csv parser rejects a longer span),
// but the concatenation in prevStr is never measured: a file that opens a
// value and then keeps feeding still-unterminated lines grows the held-over
// record past LargestEntryLimit without any error, keeping the whole thing --
// and re-parsing all of it on every new line -- in memory until EOF.
func TestLoomJSONLineHoldoverUnbounded(t *testing.T) {
param, proc, _ := errorModeParam(t, tree.JSONLINE, tree.OBJECT, numTestCols)
r := &CsvReader{param: param}
// an opening that stays unterminated
_, err := r.transJsonObject2Lines(proc.Ctx, `{"a":[`, param.Attrs, param.Cols)
require.ErrorIs(t, err, io.ErrUnexpectedEOF, "a truncated object must hold over")
require.Equal(t, `{"a":[`, r.prevStr)
// every line keeps the record unterminated, so it keeps growing
chunk := strings.Repeat("1,", 512*1024) // 1MB of still-open content
for range 16 {
_, err = r.transJsonObject2Lines(proc.Ctx, chunk, param.Attrs, param.Cols)
require.ErrorIs(t, err, io.ErrUnexpectedEOF)
require.LessOrEqual(t, len(r.prevStr), config.LargestEntryLimit,
"a held-over record past LargestEntryLimit must be rejected, not accumulated")
}
}Found by Loom bug hunt (module: custom-de41a00730; tests: unit, white-box, concurrency; severity: S1)
来源 #31851:原始报告完整保留
#31851 完整复现、版本、证据和预期
Branch Name
main
Commit ID
Other Environment Information
- Hardware: Apple Silicon (arm64, macOS 15)
- OS: darwin/arm64, Go 1.27.1
- Plain Go unit test against
pkg/sql/colexec/external; no server needed. The same reader drives standalone mo-service LOAD DATA.
Actual Behavior
For JSONLINE (format=jsonline), each physical line whose accumulated JSON record is genuinely truncated causes transJsonObject2Lines/transJsonArray2Lines (pkg/sql/colexec/external/reader_csv.go:320-328, 388-395) to:
- re-
ParseNodeStringthe ENTIRE accumulated prefix (quadratic in number of lines), and - hold the accumulated text in
r.prevStrwith NO size bound (nomaxRecordSize/config.LargestEntryLimitcheck anywhere on the holdover),
until the record closes or the file ends. Measured on current main with a truncated JSONLINE array file (each line [1234567890123456789,, cgo build, go test -run TestLoomQuadTiming -count=1):
lines=2500 content=53KB elapsed=267.47ms
lines=5000 content=107KB elapsed=1.037s ( 3.9x for 2x lines)
lines=10000 content=214KB elapsed=4.010s ( 3.9x)
lines=20000 content=429KB elapsed=16.144s ( 4.0x)
Textbook O(n^2): a 21MB truncated JSONLINE file of 1M such lines would take ~11 hours of pure re-parsing on one CN worker while pinning the file's bytes in prevStr.
Memory side: with config.LargestEntryLimit set to 64KiB (server default is 64MiB, pkg/config/configuration.go:203-211), a 20000-line file (429KB payload, every line far below the limit) accumulated prevStr up to 344,064 bytes (observed between reader batches) before failing at EOF with incomplete json record -- over 5x the configured per-record bound. The equivalent payload as ONE physical CSV record is rejected immediately with csv record size ... exceeds max record size ... tunable by cn config 'largest-entry-limit' (verified: TestLoomCSVSingleRecordBoundStillEnforced in the embedded repro, and at SQL level on a standalone instance a 300MB single-line file fails with invalid input: csv record size 67174400 exceeds max record size 67108864). The JSONLINE holdover path is the only record shaping that escapes this documented, tunable bound.
This is a reconfirmation and expansion of open issue #31304, which already records the unbounded prevStr growth; this report adds (a) measurement on latest main, (b) the quadratic re-parse cost of the same holdover loop, and (c) the contrast anchor proving the CSV
equivalent is bounded. Fix directions: bound the accumulated holdover by maxRecordSize (fail with the standard record-size error, like oversized CSV records), and/or advance the JSON parse incrementally instead of re-parsing the whole prefix per line.
Expected Behavior
config.LargestEntryLimit(CN tomllargest-entry-limit) is documented as bounding "the default max weight of one CSV record read by the LOAD DATA / external-table parser" (pkg/config/configuration.go:203-211, and the runtime error text "tunable by cn config 'largest-entry-limit'" frompkg/sql/util/csvparser/csv_parser.go:609-617). A JSONLINE record assembled by the holdover is still one record; its accumulated weight must not pass that bound while each physical line alone is below it.- The accumulation should not re-parse its whole prefix for every appended line; either incremental parsing or a size check that fails fast keeps load time linear.
Steps to Reproduce
Go unit test file pkg/sql/colexec/external/loom_test_jsonline_holdover_budget_test.go (reuses committed helpers errorModeParam, colLine from error_mode_test.go); complete source in the repro field. Run:
export CGO_CFLAGS="-I<repo>/cgo -I<repo>/thirdparties/install/include"
export CGO_LDFLAGS="-L<repo>/thirdparties/install/lib -L<repo>/cgo"
go test ./pkg/sql/colexec/external/ -run 'TestLoomQuadTiming|TestLoomJSONLineTruncationBypassesRecordBound|TestLoomCSVSingleRecordBoundStillEnforced' -count=1 -v
TestLoomQuadTimingprints the per-lines timing table above.TestLoomJSONLineTruncationBypassesRecordBoundsetsconfig.LargestEntryLimit = 64*1024, feeds 20000 lines of 21 bytes and asserts the observed held-over size exceeds the limit (PASSES on main = the bug; it also logs the measured max).TestLoomCSVSingleRecordBoundStillEnforcedfeeds the equivalent 200KB single-record payload and asserts the standard record-size error (PASSES, contrast anchor).
SQL-level anchor for the CSV bound (standalone mo-service, commit 4ca0d77):
dd if=/dev/zero bs=1048576 count=300 | tr '\0' 'a' > localbig.csv # 300MB single line
load data local infile 'localbig.csv' into table t;
-- ERROR 20301 (HY000): invalid input: csv record size 67174400 exceeds max record size 67108864, tunable by cn config 'largest-entry-limit'
Additional information
- The holdover loop:
reader_csv.go:388-395(transJsonArray2Lines:str = r.prevStr + str; ... bytejson.ParseNodeString(str) ... r.prevStr = str), reached frommakeBatchRowsatreader_csv.go:201-217via theunexpected EOF, wait for next batchcontinuation for each truncated line. csvparserdoes bound single records (recordWeight/appendToRecord/recordSizeLimitError,csv_parser.go:600-668), which is why only records that arrive as MANY small physical lines escape it.- NOTE: the accumulation interacts with the buffer-aliasing bug of [Bug]: JSONLINE truncated-record holdover aliases a reused parser buffer, so record continuation never works #31280 (first holdover aliases the reused parser buffer). Lines must keep the accumulated prefix parseable-yet-truncated for the chain to continue (the embedded repro uses equal-length lines that re-open
[), which is why the unbounded growth is not always observed with arbitrary content. The two issues are independent defects of the same holdover mechanism. - Related open issues: [Bug]: JSONLINE truncated-record holdover grows prevStr past LargestEntryLimit with no size bound #31304 (unbounded growth), [Bug]: JSONLINE truncated-record holdover aliases a reused parser buffer, so record continuation never works #31280 (aliasing).
- The unit test sleeps: none; the 20000-line run takes ~17s.
Full reproduction, exactly as Loom ran it
// File: pkg/sql/colexec/external/loom_test_jsonline_holdover_budget_test.go
// Run (after `make cgo-native-thirdparties-internal` so thirdparties/install exists):
// export CGO_CFLAGS="-I<repo>/cgo -I<repo>/thirdparties/install/include"
// export CGO_LDFLAGS="-L<repo>/thirdparties/install/lib -L<repo>/cgo"
// go test ./pkg/sql/colexec/external/ -run 'TestLoomQuadTiming|TestLoomJSONLineTruncationBypassesRecordBound|TestLoomCSVSingleRecordBoundStillEnforced' -count=1 -v
//
// Reuses committed test helpers from error_mode_test.go: errorModeParam, colLine, colA.
package external
import (
"io"
"strings"
"testing"
"time"
"github.com/matrixorigin/matrixone/pkg/config"
"github.com/matrixorigin/matrixone/pkg/container/batch"
"github.com/matrixorigin/matrixone/pkg/sql/parsers/tree"
"github.com/matrixorigin/matrixone/pkg/vm/process"
"github.com/stretchr/testify/require"
)
func loomRunContent(t *testing.T, keep int, content string) (error, int, int) {
param, proc, bat := errorModeParam(t, tree.JSONLINE, tree.ARRAY, keep)
t.Cleanup(func() { bat.Clean(proc.Mp()) })
r := &CsvReader{param: param}
r.reader = io.NopCloser(strings.NewReader(content))
parser, perr := newCSVParserFromReader(param.Extern, r.reader)
require.NoError(t, perr)
r.plh = &ParseLineHandler{csvReader: parser}
maxHeld := 0
for {
finished, e := r.makeBatchRows(proc, bat)
if len(r.prevStr) > maxHeld {
maxHeld = len(r.prevStr)
}
if e != nil {
return e, bat.RowCount(), maxHeld
}
if finished {
return nil, bat.RowCount(), maxHeld
}
}
}
// Quadratic re-parse: 2x lines => ~4x time.
func TestLoomQuadTiming(t *testing.T) {
for _, lines := range []int{2500, 5000, 10000, 20000} {
var b strings.Builder
for i := 0; i < lines; i++ {
b.WriteString("[1234567890123456789,")
b.WriteString("\n")
}
content := b.String()
start := time.Now()
_, _, _ = loomRunContent(t, colLine, content)
t.Logf("lines=%d content=%dKB elapsed=%v", lines, len(content)/1024, time.Since(start))
}
}
// The accumulated holdover passes LargestEntryLimit although every line is far below it.
func TestLoomJSONLineTruncationBypassesRecordBound(t *testing.T) {
restore := config.LargestEntryLimit
config.LargestEntryLimit = 64 * 1024
defer func() { config.LargestEntryLimit = restore }()
var b strings.Builder
for i := 0; i < 20000; i++ {
b.WriteString("[1234567890123456789,")
b.WriteString("\n")
}
content := b.String()
err, _, maxHeld := loomRunContent(t, colLine, content)
t.Logf("err: %v", err)
t.Logf("max prevStr held: %d (LargestEntryLimit=%d)", maxHeld, config.LargestEntryLimit)
require.Greater(t, maxHeld, config.LargestEntryLimit)
}
// Contrast: the same payload as ONE physical record IS rejected by the bound.
func TestLoomCSVSingleRecordBoundStillEnforced(t *testing.T) {
restore := config.LargestEntryLimit
config.LargestEntryLimit = 64 * 1024
defer func() { config.LargestEntryLimit = restore }()
content := "[" + strings.Repeat("1234567890", 20000) // 200KB single record
err, _, _ := loomRunContent(t, colLine, content)
require.Error(t, err)
require.Contains(t, err.Error(), "exceeds max record size")
}
var _ = batch.NewOffHeap
var _ process.AnalyzerFound by Loom bug hunt (module: custom-de41a00730; tests: unit, white-box, end-to-end, concurrency; severity: S1)
Activity