Skip to content

Add PGN (portable game notation) input format - #93067

Closed
chhetripradeep wants to merge 15 commits into
ClickHouse:masterfrom
chhetripradeep:pgn-input-format
Closed

chhetripradeep wants to merge 15 commits into
ClickHouse:masterfrom
chhetripradeep:pgn-input-format

Conversation

@chhetripradeep

@chhetripradeep chhetripradeep commented Dec 25, 2025 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Add PGN (portable game notation) input format for reading chess datasets

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Workflow [PR]
Sync PR [sync-upstream/pr/93067]

@clickhouse-gh

clickhouse-gh Bot commented Dec 25, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3237a44]

Summary: ❌

job_name test_name status info comment
BuzzHouse (amd_tsan) FAIL
Logical error: '!atom.negative' (STID: 2508-42d7) FAIL cidb
Build profile diff ERROR

AI Review

Summary

This PR adds a new PGN input format, schema inference, documentation, and focused regressions for BOM handling, escape lines, result validation, and target-table defaults. The remaining correctness gap is that row-boundary detection still depends on tags: a tagless game is accepted at the start of a file, but a second tagless game after a completed first one is still misparsed as trailing tokens of the previous row.

Findings

⚠️ Majors

  • [src/Processors/Formats/Impl/PGNRowInputFormat.cpp:55-57,373-409] parseGame already allows a game with no tag section, but readMoves still uses [ as the only next-row boundary after a result marker. With input such as 1. e4 e5 1-0 followed by a blank line and 1. d4 d5 0-1, the second game's opening 1. reaches the terminated branch and raises Invalid PGN: unexpected token ... after the game termination marker instead of starting a new row. That makes support for tagless PGN position-dependent. Either reject tagless games uniformly before readMoves, or recognize a blank-line-separated next game after termination and add a regression for consecutive tagless games.
Final Verdict

Needs changes before merge: the parser's current handling of tagless games is still inconsistent and depends on where the game appears in the file.

LLVM Coverage Report

Measured on commit 3237a44.

Metric Baseline Current Δ
Lines 88.50% 88.50% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 80.70% 80.70% +0.00%

Changed lines: Changed C/C++ lines covered: 349/370 (94.32%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Dec 25, 2025
@chhetripradeep
chhetripradeep force-pushed the pgn-input-format branch 2 times, most recently from ecfabd2 to 926bdfa Compare December 26, 2025 02:22
@nihalzp nihalzp self-assigned this Dec 29, 2025
@nikitamikhaylov nikitamikhaylov added the comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). label Dec 29, 2025

@nihalzp nihalzp left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was trying out simple_games.pgn and printed all the rows and got:

   ┏━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━┓
   ┃ event        ┃ site        ┃ date       ┃ round ┃ white    ┃ black    ┃ result ┃ white_elo ┃ black_elo ┃ moves    ┃
   ┡━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━┩
1. │ Test Event   │ Test Site   │ 2024.01.01 │ 1     │ Player A │ Player B │ 1-0    │      2500 │      2400 │ e5 Nc6   │
   ├──────────────┼─────────────┼────────────┼───────┼──────────┼──────────┼────────┼───────────┼───────────┼──────────┤
2. │ Test Event 2 │ Test Site 2 │ 2024.01.02 │ 2     │ Player C │ Player D │ 0-1    │      2600 │      2550 │ d5 dxc4  │
   └──────────────┴─────────────┴────────────┴───────┴──────────┴──────────┴────────┴───────────┴───────────┴──────────┘

It only shows black's moves. Also, we do not have any move related queries in tests, let's add them in tests.


If the move contains castling notation move: (0-0 or 0-0-0), we do not seem to able to parse it. For example this,

1. e4 e5 2. Nf3 Nc6 3. 0-0 0-0 4. d4 d6 5. 0-0-0 *

If the Result is missing, I think we can try parse the result from moves for a PGN like this:

[Event "Event"]
[Site "Site"]
[Date "2026.01.01"]
[Round "1"]
[White "Alice"]
[Black "Bob"]

1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 1-0

If I try to load this PGN:

[Event "x"]
[WhiteElo "123"]
[BlackElo "456"]

*

using:

SELECT *
FROM file('path_to_pgn', 'PGN',
          'event String, white_elo String');

it crashes.


I think there are some issues with file segmentation engine. I tried running simple_games.pgn's segmentation path with:

SELECT * FROM file('simple_games.pgn', 'PGN') SETTINGS max_parsing_threads=4, input_format_parallel_parsing=1, min_chunk_bytes_for_parallel_parsing=1, max_block_size=1 FORMAT PRETTY;

and it gave me 18 rows.

But with input_format_parallel_parsing=0 it worked fine.

We can either fix it or not support file segmentation engine for PGN for now. We can add support for that later if that's easier.

Comment thread docs/en/interfaces/formats/PGN.md Resolved
Comment thread docs/en/interfaces/formats/PGN.md Resolved
@nihalzp

nihalzp commented Jan 12, 2026

Copy link
Copy Markdown
Member

Additionally, let's add a test for each of the issues in the review. It will make sure the same bugs do not reappear in the future if someone else changes the code.

@clickhouse-gh

clickhouse-gh Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

Dear @nihalzp, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@nihalzp nihalzp self-assigned this Jun 1, 2026
@chhetripradeep
chhetripradeep force-pushed the pgn-input-format branch 2 times, most recently from 9283ee5 to 3d7addb Compare June 28, 2026 06:03
@chhetripradeep chhetripradeep added the can be tested Allows running workflows for external contributors label Jun 28, 2026
Comment thread docs/en/interfaces/formats/PGN.md Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Dear @nihalzp, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@nihalzp nihalzp self-assigned this Jul 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

Dear @nihalzp, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@alexey-milovidov alexey-milovidov self-assigned this Aug 20, 2026
@alexey-milovidov alexey-milovidov added the pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard label Aug 22, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Picked this up: merged master (the branch was ~26 700 commits behind) and pushed 2da54070bff0.

  • Reds fixed. Fast test and Build (arm_tidy) failed on -Wmissing-prototypes for registerInputFormatPGN / registerPGNSchemaReader and on modernize-use-starts-ends-with; Style check failed on the catch (...) around std::stoi. The Elo parsing now uses std::from_chars: an unknown rating (empty, ? or -, the spellings the standard reserves for it) is reported as an absent column so a table DEFAULT applies, and anything else non-numeric raises INCORRECT_DATA instead of silently becoming 0.
  • Documentation. docs/en/interfaces/formats was removed on master, so the page moved to docs/reference/formats/PGN.mdx. Its body is now generated from the Documentation attached with FormatFactory::setDocumentation in PGNRowInputFormat.cpp, and the page was added to docs/reference/navigation.json. The PR carries the pr-autogenerated-docs label, which is the sanctioned way to add the generated region of a new page.
  • Stale reference. 03775_pgn_format expected empty white and black under LIMIT and OFFSET; the parser returns the players there, exactly as it does without LIMIT, so the reference was wrong, not the parser.
  • New tests in 03777_pgn_format_edge_cases for an unknown rating (including the DEFAULT expression of the target table) and for a malformed one.

@nihalzp all of your review threads are addressed and resolved; every point of your review summary now has a test: exact moves of both colours and the compact 1.e4 notation (03776 test 8), castling, { ... } comments, a variation holding an unbalanced ), compact [Event"X"] tags and the result taken from the move text when the Result tag is missing (03777 test 5), a requested column of the wrong type, which raises an exception instead of an abort (03777 test 6), and parallel parsing (03776 test 9 — the format registers no file segmentation engine, so a PGN file is never split).

All three tests pass against a local build.

@clickhouse-gh

clickhouse-gh Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing commit 3237a4466aede61692abd4001f0dbe0181bd7e3f with master failed: RuntimeError: CI logs cluster query failed: SELECT file, symbol, sumIf(size, side = 'pr') AS pr_size, sumIf(size, side = 'base') AS base_size, toInt64(pr_size) - toInt64(base_size) AS delta FROM ( SELECT 'pr' AS side, file, replaceRegexpAll(replaceRegexpAll(symbol, ' ?\\[clone \\.llvm\\.[0-9]+\\]', ''), '\\.llvm\\.[0-9]+', '') AS symbol, size FROM binary_symbols WHERE date >= today() - 7 AND (repo = 'ClickHouse/ClickHouse' OR repo = '') AND pull_request_number = 93067 AND commit_sha = '3237a...(+746 chars elided)...6' AND check_name = 'arm_release' AND check_start_time = '2026-09-20 23:43:50' AND instance_id = 'i-02f83976e4a0e8d97' AND file IN ('./ci/tmp/build/programs/clickhouse', './ci/tmp/build/programs/clickhouse-keeper') AND size >= 1024 ) GROUP BY file, symbol HAVING abs(delta) >= 65536 ORDER BY abs(delta) DESC LIMIT 20.

See the job log for details.

alexey-milovidov and others added 3 commits August 25, 2026 02:30
…rmat

A file starting with a byte order mark produced a phantom first row, because
`PGNRowInputFormat` never skipped it: it now overrides `readPrefix` and calls
`skipBOMIfExists`. The escape mechanism of the standard - a line whose first
column is `%` is ignored - was not implemented, so such lines produced a bogus
extra row or leaked into `moves`; they are now skipped both between the tags
and inside the move text. Regression test `05029_pgn_format_bom_and_escape_lines`
covers a BOM-prefixed file and escape lines in all positions.

Co-Authored-By: Claude Fable 5 <[email protected]>
… refills

`isEscapeLine` peeked at the byte before the current position, which is not
in the buffer when a `%` escape line starts exactly at a `ReadBuffer` refill
boundary, so such a line was parsed as data. The parser now tracks the
previously consumed byte explicitly, and the state survives refills.

Regression test `05045_pgn_format_escape_line_at_buffer_boundary` reads a
file with escape lines through 1-, 3- and 16-byte read buffers, which forces
every `%` onto a refill boundary.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The Stress test (arm_tsan) failure on 12d25ec ("Hung check failed, possible deadlock found") is unrelated to this PR: the hung query is an AST-fuzzer query stuck in constant folding during query analysis (resolveFunction → IFunctionOverloadResolver::build), and the report does not mention the PGN format at all. This is the known issue #112203 (uninterruptible CPU-bound function evaluation over a large constant). @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=93067&sha=12d25ec6e9841172f85ade039f82cd508279a94b&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29 and provide a fix in a separate PR if one is not already in progress.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. Two corrections first, then the answer.

Not the PGN format: confirmed. PGN/pgn appear 0 times anywhere in hung_check.log.

Not #112203. The artifact holds 13 hung queries. Across all 13 processlist rows, resolveFunction = 0, IFunctionOverloadResolver = 0, QueryAnalyzer = 0. Those frames occur only in the aggregated stack appendix at the end of the file (2, 5 and 18 hits in the last 32 KiB), which is exactly the part CIDB keeps while dropping the processlist rows.

What actually hung: one holder plus 12 waiters on a single recursive_mutex.

Holder, Row 1: SYSTEM PAUSE VIEWS, elapsed 1543 s, is_cancelled: 1, max_execution_time: 60, StorageConnectionsErrors: 7, AddressesMarkedAsFailed: 7. Chain:

InterpreterSystemQuery::startStopActionInDatabase -> ActionLocksManager::add
  -> StorageProxy::getActionLock -> StorageTableFunctionProxy::getNestedImpl   [takes nested_mutex]
  -> TableFunctionURL::getStorage -> readSchemaFromFormat
  -> ReadWriteBufferFromHTTP::doWithRetries -> sleepForMilliseconds   [ReadWriteBufferFromHTTP.cpp:399]

Rows 2 to 13 are SYSTEM STOP VIEWS / PAUSE VIEWS / STOP MERGES / STOP MOVES plus one SELECT ... FROM merge('information_schema', '.*'), all blocked at StorageTableFunction.h:41 on that same mutex. So a metadata-only admin command runs url schema inference while holding the proxy mutex, inside an uninterruptible retry backoff.

The ask. The holder's frame is already covered by your own #112930: it replaces that exact line (- sleepForMilliseconds(milliseconds_to_wait) -> + waitBeforeRetry(...)), adds the isQueryTimeLimitReached() checks, and ships 05024_url_function_schema_inference_soft_timeout and 05029_url_function_schema_inference_hard_timeout_during_backoff. I have nothing to add there.

The other half is unowned: #112930 touches StorageProxy, StorageTableFunction, InterpreterSystemQuery and ActionLock 0 times. A bare SYSTEM STOP/PAUSE ... walks every database and table and materializes a lazy proxy just to take an action lock, although a table function cannot merge, move or have views. With #112930 in, that no longer hangs, but it still does network I/O per table and fails the whole statement when an endpoint is down. Two in-tree precedents decline exactly this: StorageTableFunction.h returns nullptr/false from getStoragePolicy/storesDataOnDisk to "Avoid loading nested table", and DatabaseURL.cpp:159 refuses the same forwarding because "the lazy proxies ... would have to materialize and start up the nested storage just to answer a classification query". I will send that as a separate PR and link it here.

Why it surfaced now: #114502 (merged 2026-08-24) added STOP MERGES, STOP MOVES, STOP VIEWS and PAUSE VIEWS to the stress workload, and its own comment notes that such a statement "walks every database and table".

@groeneai

Copy link
Copy Markdown
Collaborator

The separate PR is up: #116774

It stops StorageTableFunctionProxy from resolving the table function to answer a lock or a size query, so neither the table-less SYSTEM STOP/PAUSE catalog walk nor system.tables runs schema inference per table any more. In this report that removes the single resolver; the other twelve queries were only waiting on the mutex it held. The uninterruptible retry backoff itself stays with #112930.

alexey-milovidov and others added 2 commits August 29, 2026 11:26
… marker

The `result` of a game is carried both by the `Result` tag and by the game
termination marker of the move text, but neither relationship was validated:
any tag value was accepted verbatim, and a termination marker was ignored
whenever a tag had already filled `result`, so both `[Result "won"]` and
`[Result "1-0"] ... 0-1` were ingested silently. Now a `Result` tag outside
`1-0`, `0-1`, `1/2-1/2`, `*` and a termination marker that contradicts the
game result both raise `INCORRECT_DATA`.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The Stress test (amd_asan_ubsan) failure on 468cbd70c8ba is the known issue #107619 (Logical error: Not-ready Set is passed as the second argument for function), unrelated to this input-format-only PR. @groeneai, investigate that failure and provide a fix in a separate PR; if a fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

A fix for this one is already in progress: #114058

Route pinned from that run's own artifacts (report):

  • fatal.log: the aborting query is SELECT * FROM merge(currentDatabase(), '^row_policy_table$') ORDER BY id ASC NULLS LAST, query id 0e52ecb5-4001-4821-ba95-037789bebf1b.
  • query_log.tsv.zst for that query id: log_comment is 04509_row_policy_arrayjoin_filter.sh, used_row_policies is ['test_7.row_policy_table.all'].
  • The query itself contains no IN, so the unready set can only be the one in the policy that test creates: CREATE ROW POLICY valid_policy ON row_policy_table FOR SELECT USING value IN (SELECT arrayJoin([10, 20])) TO ALL.

On master, ReadFromMerge::RowPolicyData::RowPolicyData compiles that predicate with a local ExpressionAnalyzer (StorageMerge.cpp:1745) and keeps only its ActionsDAG (:1747), so the PreparedSets that owns the subquery's FutureSetFromSubquery dies with the constructor and nothing ever builds the set. addFilterTransform (:1806) turns that DAG into the FilterStep whose FilterTransform::doTransform is the frame above FunctionIn::executeImpl in the stack.

#114058 keeps that PreparedSets and adds a DelayedCreatingSetsStep beside the policy filter step. Its test pins this spelling, SELECT * FROM merge(currentDatabase(), '^mrp_mt$') under USING value IN (SELECT 10). It has been open since 2026-08-09 with no review yet.

One caveat: STID 0250-41a5 is a message bucket rather than a single defect, so not every hit is this route. The IStorageSystemOneBlock route is #117039.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 The sole red on 565eea1ab03a was Fast test → 05047_distributed_plan_finished_stages_drain (NO_SUCH_DATA_PART: "part ... selected by the coordinator is not available on this replica"), which dropped every downstream job. It is unrelated to this input-format-only PR — the failing query is the system.query_log wall-clock assertion of that test, read through the distributed plan. It has since been fixed on master by #116987 and #117397, both of which landed after this branch last merged master.

Merged master (00ff4a11606f) so the fix is pulled in and CI reruns from scratch. No PGN code changed; all six PGN tests (03775, 03776, 03777, 05029, 05045, 05048) pass against a fresh local build of the merge result.

…esult

Two gaps in the `PGN` parser found by the review of the previous commit:

- `skipVariation` did not honour the escape mechanism of the standard, so a
  `%` line inside a parenthesized variation was read as ordinary text. A `)`
  written on such a line closed the variation early and leaked the rest of the
  variation into the mainline `moves`. `isEscapeLine` is now checked there as
  well, exactly like in `readMoves` and `skipWhitespaceAndComments`.
- A game whose movetext has moves but no game termination marker, and which has
  no `Result` tag, was accepted with an empty `result`. That contradicts the
  documented contract that `result` is one of `1-0`, `0-1`, `1/2-1/2` or `*`,
  so it now raises `INCORRECT_DATA`.

The documentation sentence about the result is extended accordingly, in both
the `setDocumentation` body and `docs/reference/formats/PGN.mdx`.

New test `05137_pgn_format_variation_escape_line_and_missing_result` covers an
escape line containing `)` inside a variation (also read one byte at a time so
that the line starts at a buffer refill boundary), a game without any result,
and a `Result` tag without a termination marker.
alexey-milovidov and others added 2 commits September 16, 2026 15:44
`readMoves` kept scanning ordinary tokens after it had accepted a game
termination marker, so a malformed game such as `1.e4 e5 1-0 2.Nf3 Nc6`
was stored with `moves = 'e4 e5 Nf3 Nc6'`. The marker now ends the
movetext: any later ordinary token (including a repeated marker) raises
`INCORRECT_DATA`, while comments, variations and escape lines after the
marker are still skipped. Documented in both the `setDocumentation` body
and `docs/reference/formats/PGN.mdx`; regression test
`05225_pgn_format_tokens_after_termination_marker`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
bool terminated = false;

/// Read move text until end of game (next [ or EOF or blank line followed by [)
while (!in.eof() && *in.position() != '[')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

parseGameImpl already treats the tag-pair section as optional, so a tagless game is accepted when it appears first in the file. But readMoves still uses [ as the only row boundary, so after the first game's result this loop keeps scanning until it sees another tag header.

That makes support for missing tags position-dependent. For example, this input parses the first game and then throws on the second one:

1. e4 e5 1-0

1. d4 d5 0-1

The second game's opening 1. reaches the terminated branch below and becomes Invalid PGN: unexpected token ... after the game termination marker. Please either reject tagless games uniformly before readMoves, or recognize a blank-line-separated next game after a termination marker and add a regression for consecutive tagless games.

@alexey-milovidov alexey-milovidov removed their assignment Sep 19, 2026
@alexey-milovidov alexey-milovidov added the close in a month if not active This will be closed in case of no information label Sep 19, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

I've asked in Slack, but no one was interested.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors close in a month if not active This will be closed in case of no information comp-formats Input/output formats (CSV/JSON/Parquet/ORC/Arrow/Protobuf/etc.). pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants