From 9cf5be20c98e747721bf64966f6a6107635fe742 Mon Sep 17 00:00:00 2001 From: satriadhikara <84092642+satriadhikara@users.noreply.github.com> Date: Thu, 23 Jul 2026 20:21:14 +0700 Subject: [PATCH 1/3] Fix validation of nested out-of-order tables --- tests/test_toml_document.py | 7 +++++++ tomlkit/container.py | 29 +++++++++++++++++------------ 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/tests/test_toml_document.py b/tests/test_toml_document.py index 7ba61f5e..d5440a89 100644 --- a/tests/test_toml_document.py +++ b/tests/test_toml_document.py @@ -643,6 +643,13 @@ def test_valid_out_of_order_independent_tables() -> None: assert doc.as_string() == "[a]\nx=1\n[zz]\n[a.b]\nc=1\n" +def test_valid_nested_out_of_order_table_after_unrelated_table() -> None: + content = "[a]\n[a.b.c]\n[a.b]\n[[zz]]\n[a.b.d]\n" + doc = parse(content) + assert doc.unwrap() == {"a": {"b": {"c": {}, "d": {}}}, "zz": [{}]} + assert doc.as_string() == content + + def test_set_value_on_out_of_order_table_with_empty_concrete_part() -> None: # A super table defined after its sub-table (the "defining a super-table # afterward is ok" spec example) leaves an empty concrete `[x]` part. diff --git a/tomlkit/container.py b/tomlkit/container.py index 8ff30d98..7b40395c 100644 --- a/tomlkit/container.py +++ b/tomlkit/container.py @@ -423,19 +423,24 @@ def _validate_table_candidate(self, current: Table, candidate: Table) -> None: continue if k in current.value._map: - existing = current.value.item(k) - if isinstance(existing, (Table, AoT)) != isinstance(v, (Table, AoT)): - raise KeyAlreadyPresent(k) - if k.is_dotted(): - raise TOMLKitError("Redefinition of an existing table") - if isinstance(existing, Table) and isinstance(v, Table): - if not existing.is_super_table() and not v.is_super_table(): - # Both sides are concrete `[table]` definitions of the - # same name; the table is declared twice. + index = current.value._map[k] + indices = index if isinstance(index, tuple) else (index,) + for i in indices: + existing = current.value._body[i][1] + if isinstance(existing, (Table, AoT)) != isinstance( + v, (Table, AoT) + ): raise KeyAlreadyPresent(k) - # One side is still an implicit/super table, so a duplicate - # (if any) is nested deeper - keep checking the subtree. - self._validate_table_candidate(existing, v) + if k.is_dotted(): + raise TOMLKitError("Redefinition of an existing table") + if isinstance(existing, Table) and isinstance(v, Table): + if not existing.is_super_table() and not v.is_super_table(): + # Both sides are concrete `[table]` definitions of the + # same name; the table is declared twice. + raise KeyAlreadyPresent(k) + # One side is still an implicit/super table, so a duplicate + # (if any) is nested deeper - keep checking the subtree. + self._validate_table_candidate(existing, v) continue if not k.is_dotted(): From 096e4c77f99d211e01ffe2b375e3318058c3830d Mon Sep 17 00:00:00 2001 From: satriadhikara <84092642+satriadhikara@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:33:52 +0700 Subject: [PATCH 2/3] Validate out-of-order table candidates against every fragment append() compared a new table only with the last fragment of an out-of-order table, so a table declared twice across fragments was accepted, e.g. [a.b.c] [a.b] [a] [a.b.d] [a.b]. Master rejected these only because the proxy was wrongly treated as a non-table (#571). Also reject a [table] header redefining a table created by dotted keys, e.g. [a] b.y=1 [a.b.c] [q] [a.b]. Differential fuzzing against tomllib (~250k generated documents): no new disagreements vs master, and invalid documents wrongly accepted drop from 2813 to 14. --- tests/test_toml_document.py | 33 +++++++++++++++++++++++++++++++++ tomlkit/container.py | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 66 insertions(+), 1 deletion(-) diff --git a/tests/test_toml_document.py b/tests/test_toml_document.py index 613665f3..9b13d91f 100644 --- a/tests/test_toml_document.py +++ b/tests/test_toml_document.py @@ -681,6 +681,39 @@ def test_valid_nested_out_of_order_table_with_multiple_fragments() -> None: assert doc.as_string() == content +@pytest.mark.parametrize( + "content", + [ + pytest.param( + "[a.b.c]\n[a.b]\n[a]\n[a.b.d]\n[a.b]\n", + id="duplicate-concrete-table-across-fragments", + ), + pytest.param( + "[a]\n[a.b.c]\n[a.b]\n[q]\n[a.b.d]\n[a.b]\n", + id="duplicate-concrete-table-in-earlier-fragment", + ), + pytest.param( + "[a]\n[q]\n[a.b.c.e]\n[a.b]\n[a]\n[a.b.d]\n", + id="duplicate-concrete-parent-in-earlier-fragment", + ), + pytest.param( + "[a]\nb.y=1\n[a.b.c]\n[q]\n[a.b]\n", + id="dotted-key-table-redefined-by-header", + ), + ], +) +def test_out_of_order_table_rejects_redefinition(content: str) -> None: + with pytest.raises(TOMLKitError): + parse(content) + + +def test_valid_out_of_order_sub_table_of_dotted_key_table() -> None: + content = "[a]\nb.y=1\n[a.b.c]\n[q]\n[a.b.d]\n" + doc = parse(content) + assert doc.unwrap() == {"a": {"b": {"y": 1, "c": {}, "d": {}}}, "q": {}} + assert doc.as_string() == content + + @pytest.mark.parametrize( "header", [ diff --git a/tomlkit/container.py b/tomlkit/container.py index 94f8463a..8759e5ee 100644 --- a/tomlkit/container.py +++ b/tomlkit/container.py @@ -305,6 +305,7 @@ def append( return self elif current.is_super_table(): + self._validate_earlier_fragments(key, current_idx, item) if item.is_super_table(): # We need to merge both super tables if ( @@ -364,6 +365,7 @@ def append( # — _raw_append below will create an out-of-order entry and # preserve table ordering in the document. assert isinstance(current, Table) + self._validate_earlier_fragments(key, current_idx, item) self._validate_table_candidate(current, item) elif isinstance(item, AoT): if not isinstance(current, AoT): @@ -421,6 +423,27 @@ def append( self._validate_out_of_order_table(key) return self + def _validate_earlier_fragments( + self, key: Key, idx: int | tuple[int, ...], candidate: Table + ) -> None: + # `append` compares the candidate with the last fragment of an + # out-of-order table only; it must not collide with the earlier ones + # either, e.g. [a.b.c] [a.b] [a] [a.b.d] [a.b] declares [a.b] twice. + if not isinstance(idx, tuple): + return + for i in idx[:-1]: + k, fragment = self._body[i] + if not isinstance(fragment, Table): + continue + if key.is_dotted() and k is not None and k.is_dotted(): + # Merging two tables created by dotted keys is legal. + continue + if not candidate.is_super_table() and ( + not fragment.is_super_table() or (k is not None and k.is_dotted()) + ): + raise KeyAlreadyPresent(k) + self._validate_table_candidate(fragment, candidate) + def _validate_table_candidate(self, current: Table, candidate: Table) -> None: for k, v in candidate.value.body: if k is None: @@ -430,13 +453,22 @@ def _validate_table_candidate(self, current: Table, candidate: Table) -> None: index = current.value._map[k] indices = index if isinstance(index, tuple) else (index,) for i in indices: - existing = current.value._body[i][1] + existing_key, existing = current.value._body[i] if isinstance(existing, (Table, AoT)) != isinstance( v, (Table, AoT) ): raise KeyAlreadyPresent(k) if k.is_dotted(): raise TOMLKitError("Redefinition of an existing table") + if ( + existing_key is not None + and existing_key.is_dotted() + and isinstance(v, Table) + and not v.is_super_table() + ): + # A table created by dotted keys (stored as a super + # table) cannot be redefined by a `[table]` header. + raise TOMLKitError("Redefinition of an existing table") if isinstance(existing, Table) and isinstance(v, Table): if not existing.is_super_table() and not v.is_super_table(): # Both sides are concrete `[table]` definitions of the From f396241f8e9db56ca664ea8a031101f019b593ac Mon Sep 17 00:00:00 2001 From: satriadhikara <84092642+satriadhikara@users.noreply.github.com> Date: Sun, 11 Oct 2026 19:16:11 +0700 Subject: [PATCH 3/3] Keep the incremental validation cache in sync with in-place merges Merging a super table in place into the last fragment of an out-of-order table mutated a fragment the validation cache had already copied, so later fragments were validated against a stale copy and e.g. a.x=1 [a.b.c] [a.b.d] [q] [a.b.d] was accepted. Merge the new part into the cached container as well. With the cache correct, earlier fragments only need the cheap check that a concrete [table] does not redefine a concrete or dotted-key fragment; drop the recursive per-fragment validation, which was quadratic for tables split into many fragments. Differential fuzzing against tomllib (~250k generated documents): no invalid document accepted, no new disagreements vs master. --- tests/test_toml_document.py | 4 ++++ tomlkit/container.py | 40 ++++++++++++++++++++++++------------- 2 files changed, 30 insertions(+), 14 deletions(-) diff --git a/tests/test_toml_document.py b/tests/test_toml_document.py index 9b13d91f..77520172 100644 --- a/tests/test_toml_document.py +++ b/tests/test_toml_document.py @@ -696,6 +696,10 @@ def test_valid_nested_out_of_order_table_with_multiple_fragments() -> None: "[a]\n[q]\n[a.b.c.e]\n[a.b]\n[a]\n[a.b.d]\n", id="duplicate-concrete-parent-in-earlier-fragment", ), + pytest.param( + "a.x=1\n[a.b.c]\n[a.b.d]\n[q]\n[a.b.d]\n", + id="duplicate-table-merged-into-validated-fragment", + ), pytest.param( "[a]\nb.y=1\n[a.b.c]\n[q]\n[a.b]\n", id="dotted-key-table-redefined-by-header", diff --git a/tomlkit/container.py b/tomlkit/container.py index 8759e5ee..0a432408 100644 --- a/tomlkit/container.py +++ b/tomlkit/container.py @@ -305,7 +305,7 @@ def append( return self elif current.is_super_table(): - self._validate_earlier_fragments(key, current_idx, item) + self._validate_earlier_fragments(current_idx, item) if item.is_super_table(): # We need to merge both super tables if ( @@ -339,6 +339,24 @@ def append( # Mutating in place is O(1) per merge. The defensive copy # that protected the out-of-order validation pass has been # moved into OutOfOrderTableProxy (its only consumer). + cached = self._validation_cache.get(key) + if ( + cached is not None + and isinstance(current_idx, tuple) + and cached[0] == len(current_idx) + ): + # `current` is already merged into the cached + # validation container of this out-of-order key; + # merge the new part there too, or later fragments + # would be validated against a stale copy. + temp = cached[1] + try: + for k, v in item.value.body: + temp.append(k, copy.deepcopy(v), validate=True) + temp._validate_out_of_order_table() + except Exception: + self._validation_cache.pop(key, None) + raise for k, v in item.value.body: current.append(k, v) @@ -365,7 +383,6 @@ def append( # — _raw_append below will create an out-of-order entry and # preserve table ordering in the document. assert isinstance(current, Table) - self._validate_earlier_fragments(key, current_idx, item) self._validate_table_candidate(current, item) elif isinstance(item, AoT): if not isinstance(current, AoT): @@ -424,25 +441,20 @@ def append( return self def _validate_earlier_fragments( - self, key: Key, idx: int | tuple[int, ...], candidate: Table + self, idx: int | tuple[int, ...], candidate: Table ) -> None: - # `append` compares the candidate with the last fragment of an - # out-of-order table only; it must not collide with the earlier ones - # either, e.g. [a.b.c] [a.b] [a] [a.b.d] [a.b] declares [a.b] twice. - if not isinstance(idx, tuple): + # `append` compares a concrete `[table]` with the last fragment of an + # out-of-order table only; it must not redefine an earlier concrete or + # dotted-key fragment either, e.g. [a] [q] [a.b.c] [a] declares [a] + # twice. Nested collisions are caught by the incremental validation. + if candidate.is_super_table() or not isinstance(idx, tuple): return for i in idx[:-1]: k, fragment = self._body[i] - if not isinstance(fragment, Table): - continue - if key.is_dotted() and k is not None and k.is_dotted(): - # Merging two tables created by dotted keys is legal. - continue - if not candidate.is_super_table() and ( + if isinstance(fragment, Table) and ( not fragment.is_super_table() or (k is not None and k.is_dotted()) ): raise KeyAlreadyPresent(k) - self._validate_table_candidate(fragment, candidate) def _validate_table_candidate(self, current: Table, candidate: Table) -> None: for k, v in candidate.value.body: