From faa5d56f2c60c013c90ee338dcdcd340834f21e0 Mon Sep 17 00:00:00 2001 From: Marlon Costa Date: Sun, 6 Dec 2026 12:04:10 -0300 Subject: [PATCH 1/7] fix(toml): synchronize native document values through the public owner MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Provide u.Cli.toml_sync_document_values for the recursive operation currently owned by flext-infra. Validate the complete payload once before mutation and reuse one semantic snapshot. Preserve unchanged native nodes, comments and string-array occurrences; prune absent keys only when explicitly requested. Keep stable document/table roots and re-read fragmented child views through public native access before each mutation. Leave consolidated read and ensure helpers unchanged. Extend the existing TomlParent contract for native inline and fragmented containers. Add 12 ordinary public cases for original-document writes, inline and quoted keys, equal multiline/AoT source, exact pruning, array installation, invalid payloads and fragmented-view deletion/write lifecycles. No local runtime was executed. CI must qualify the nested deletion behavior in the pinned TOMLKit; source inspection alone does not establish that result. Related: flext-sh/flext-infra#333, flext-sh/flext-infra#3044 Traceability v1.0 — 2026-12-06 Author: Marlon Costa — Datacosmos Signed-off-by: Marlon Costa --- src/flext_cli/_typings/base.py | 6 +- src/flext_cli/_typings/domain.py | 10 +- .../_toml/flextcliutilitiestoml_part_01.py | 5 +- .../_toml/flextcliutilitiestoml_part_02.py | 2 +- .../_toml/flextcliutilitiestoml_part_03.py | 2 +- .../_toml/flextcliutilitiestoml_part_04.py | 108 +++++++++- tests/unit/test_toml_document_sync.py | 202 ++++++++++++++++++ 7 files changed, 317 insertions(+), 18 deletions(-) create mode 100644 tests/unit/test_toml_document_sync.py diff --git a/src/flext_cli/_typings/base.py b/src/flext_cli/_typings/base.py index dbf0c8c35..4d30b6723 100644 --- a/src/flext_cli/_typings/base.py +++ b/src/flext_cli/_typings/base.py @@ -12,8 +12,8 @@ from flext_core import t from jinja2.sandbox import SandboxedEnvironment -from tomlkit.container import Container -from tomlkit.items import AoT, Array, Item, Table +from tomlkit.container import Container, OutOfOrderTableProxy +from tomlkit.items import AoT, Array, InlineTable, Item, Table from tomlkit.toml_document import TOMLDocument from typing_extensions import TypeForm @@ -44,7 +44,7 @@ class FlextCliTypesBase: type TomlArray = Array type TomlAoT = AoT type TomlContainer = Container - type TomlParent = TOMLDocument | Table + type TomlParent = TOMLDocument | Table | InlineTable | OutOfOrderTableProxy type TomlValue = TOMLDocument | Table | Item | Array | AoT | Container type RuntimeAnnotation = TypeForm type SignalHandler = int | Callable[[int, FrameType | None], None] | None diff --git a/src/flext_cli/_typings/domain.py b/src/flext_cli/_typings/domain.py index dda79252f..ceabe7c45 100644 --- a/src/flext_cli/_typings/domain.py +++ b/src/flext_cli/_typings/domain.py @@ -14,7 +14,7 @@ from flext_core import p, t from ruamel.yaml.comments import CommentedMap, CommentedSeq from ruamel.yaml.tokens import CommentToken -from tomlkit.container import Container +from tomlkit.container import Container, OutOfOrderTableProxy from tomlkit.items import AoT, Array, Item, Table from tomlkit.toml_document import TOMLDocument @@ -98,7 +98,12 @@ class FlextCliTypesDomain: ] type ServiceMessageFormatter = Callable[[str, ResultValue], str] type TomlMappingSource = ( - t.JsonPayload | t.JsonMapping | Mapping[str, t.Scalar] | Item | TOMLDocument + t.JsonPayload + | t.JsonMapping + | Mapping[str, t.Scalar] + | Item + | TOMLDocument + | OutOfOrderTableProxy ) type TomlUnwrappedSource = t.JsonPayload | t.JsonMapping | Item type TomlStringListSource = ( @@ -111,6 +116,7 @@ class FlextCliTypesDomain: | Array | AoT | Container + | OutOfOrderTableProxy | t.JsonMapping | t.JsonPayload ) diff --git a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_01.py b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_01.py index 72b732e05..2ff07517c 100644 --- a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_01.py +++ b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_01.py @@ -12,6 +12,7 @@ import tomlkit from flext_core import r, u +from tomlkit.container import OutOfOrderTableProxy from tomlkit.items import AoT, Array, Item, Table from tomlkit.toml_document import TOMLDocument @@ -52,7 +53,9 @@ def toml_unwrap_item( """ return FlextCliUtilitiesConversion.JSON_VALUE_ADAPTER.validate_python( - value.unwrap() if isinstance(value, TOMLDocument | Item) else value, + value.unwrap() + if isinstance(value, TOMLDocument | Item | OutOfOrderTableProxy) + else value, strict=True, ) diff --git a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_02.py b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_02.py index cbc7867bd..dcfc9b350 100644 --- a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_02.py +++ b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_02.py @@ -108,7 +108,7 @@ def toml_table_child(container: TOMLDocument | Table, key: str) -> Table | None: return value if isinstance(value, Table) else None @staticmethod - def toml_item_child(container: TOMLDocument | Table, key: str) -> Item | None: + def toml_item_child(container: t.Cli.TomlParent, key: str) -> Item | None: """Return a raw TOML item from a container. Returns: diff --git a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_03.py b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_03.py index 3c17a96d7..79d649903 100644 --- a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_03.py +++ b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_03.py @@ -53,7 +53,7 @@ def toml_ensure_tool_table(doc: TOMLDocument) -> Table: return FlextCliUtilitiesTomlPart02.toml_ensure_table(doc, "tool") @staticmethod - def toml_value(container: TOMLDocument | Table, key: str) -> t.JsonValue | None: + def toml_value(container: t.Cli.TomlParent, key: str) -> t.JsonValue | None: """Return a normalized TOML value from a container. Returns: diff --git a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py index 1a8675f7d..8d9efa9cf 100644 --- a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py +++ b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py @@ -6,30 +6,118 @@ from __future__ import annotations -from collections.abc import Sequence -from typing import TYPE_CHECKING +from collections.abc import Mapping, Sequence from flext_core import u -from tomlkit.items import Array +from tomlkit.container import OutOfOrderTableProxy +from tomlkit.items import Array, InlineTable, Table +from tomlkit.toml_document import TOMLDocument from flext_cli import t +from flext_cli._utilities import FlextCliUtilitiesConversion from flext_cli._utilities._toml import ( FlextCliUtilitiesTomlPart01, FlextCliUtilitiesTomlPart02, FlextCliUtilitiesTomlPart03, ) -if TYPE_CHECKING: - from tomlkit.items import Table - from tomlkit.toml_document import TOMLDocument - - class FlextCliUtilitiesTomlPart04: """Implementation part for FlextCliUtilitiesTomlPart04.""" + @staticmethod + def toml_sync_document_values( + document: TOMLDocument | Table | InlineTable, + payload: t.JsonMapping, + *, + prune: bool = False, + ) -> None: + """Synchronize native TOML values while preserving unchanged source items. + + Validate the complete payload before mutation. By default, absent keys + remain untouched; prune=True removes them recursively. The root must be + a stable document or table. Fragmented child views are read again from + that root before every mutation; a proxy is not a valid root. + Native conversion and validation errors propagate unchanged. + """ + FlextCliUtilitiesTomlPart01.toml_document_from_mapping(payload) + current = FlextCliUtilitiesConversion.JSON_MAPPING_ADAPTER.validate_python( + document.unwrap(), + strict=True, + ) + FlextCliUtilitiesTomlPart04._sync_document_values( + document, (), payload, current, prune=prune + ) + + @staticmethod + def _toml_parent_at( + document: TOMLDocument | Table | InlineTable, + path: Sequence[str], + ) -> t.Cli.TomlParent: + """Resolve a fresh native view from the stable document root. + + Returns: + The original table or its current out-of-order view. + + Raises: + TypeError: If a path component no longer identifies a native table. + + """ + parent: t.Cli.TomlParent = document + for key in path: + child: object = parent[key] + if not isinstance(child, Table | InlineTable | OutOfOrderTableProxy): + msg = f"TOML sync path is not a table: {key}" + raise TypeError(msg) + parent = child + return parent + + @staticmethod + def _sync_document_values( + document: TOMLDocument | Table | InlineTable, + path: tuple[str, ...], + payload: t.JsonMapping, + current: t.JsonMapping, + *, + prune: bool, + ) -> None: + """Apply validated values without retaining invalidated native views.""" + if prune: + for key in current: + if key not in payload: + del FlextCliUtilitiesTomlPart04._toml_parent_at(document, path)[ + key + ] + for key, value in payload.items(): + current_value = current.get(key) + if current_value == value: + continue + parent = FlextCliUtilitiesTomlPart04._toml_parent_at(document, path) + child: object = parent.get(key) + if ( + isinstance(child, Table | InlineTable | OutOfOrderTableProxy) + and isinstance(value, Mapping) + and isinstance(current_value, Mapping) + ): + FlextCliUtilitiesTomlPart04._sync_document_values( + document, (*path, key), value, current_value, prune=prune + ) + elif ( + isinstance(child, Array) + and isinstance(value, list) + and all(isinstance(item, str) for item in child) + and all(isinstance(item, str) for item in value) + ): + FlextCliUtilitiesTomlPart04.toml_sync_string_list( + parent, + key, + tuple(item for item in value if isinstance(item, str)), + ) + else: + parent[key] = value + @staticmethod def toml_sync_value( - container: TOMLDocument | Table, + container: t.Cli.TomlParent, key: str, expected: t.JsonValue, ) -> bool: @@ -47,7 +135,7 @@ def toml_sync_value( @staticmethod def toml_sync_string_list( - container: TOMLDocument | Table, + container: t.Cli.TomlParent, key: str, expected: Sequence[str], *, diff --git a/tests/unit/test_toml_document_sync.py b/tests/unit/test_toml_document_sync.py new file mode 100644 index 000000000..25c1662c7 --- /dev/null +++ b/tests/unit/test_toml_document_sync.py @@ -0,0 +1,202 @@ +"""Public recursive TOML synchronization without replacing authored source. + +Copyright (c) 2026 FLEXT Team. All rights reserved. +SPDX-License-Identifier: MIT +""" + +from __future__ import annotations + +from copy import deepcopy + +import pytest + +from tests import t, tm, u + + +class TestsFlextCliTomlDocumentSync: + """Preserve native document structure while applying declared values.""" + + @staticmethod + @pytest.mark.parametrize( + "source", + [ + ( + "# document\n" + "[project]\nname = 'demo' # name\n" + 'description = """first\n[tool.uv]\nlast"""\n' + "[build-system]\nrequires = ['hatchling']\n" + "[project.optional-dependencies]\nextra = ['pkg'] # extra\n" + ), + ( + 'settings = { "literal.key" = " keep ", active = true } # inline\n' + "[[indexes]] # first\nname = 'private'\n" + "[[indexes]] # second\nname = 'other'\n" + ), + ], + ) + def test_equal_values_preserve_document_bytes(source: str) -> None: + """Equal scalars, multiline strings, inline tables and AoT keep trivia.""" + document = tm.not_none(u.Cli.toml_parse_text(source)) + payload = tm.not_none(u.Cli.toml_as_mapping(document)) + + u.Cli.toml_sync_document_values(document, payload, prune=True) + + tm.that(u.Cli.toml_dumps(document), eq=source) + + @staticmethod + def test_sync_updates_out_of_order_values_in_original_document() -> None: + """Nested changes reach every real fragment and keep unrelated source.""" + source = ( + "[tool.uv]\n" + 'link-mode = "copy" # linking\n' + "environments = [\n" + ' "old", # environment\n' + "]\n" + "[project]\nname = 'demo' # project\n" + "[tool.uv.sources]\n" + 'vendor = { path = "vendor/client", editable = true } # source\n' + ) + document = tm.not_none(u.Cli.toml_parse_text(source)) + payload: t.JsonMapping = { + "tool": {"uv": {"link-mode": "clone", "environments": ["new"]}}, + } + + u.Cli.toml_sync_document_values(document, payload) + rendered = u.Cli.toml_dumps(document) + + tm.that( + rendered, + eq=source.replace('"copy"', '"clone"').replace('"old"', '"new"'), + ) + u.Cli.toml_sync_document_values(document, payload) + tm.that(u.Cli.toml_dumps(document), eq=rendered) + + @staticmethod + def test_sync_changes_inline_values_without_replacing_the_table() -> None: + """A changed inline child retains its siblings, quoted keys and comment.""" + source = ( + 'settings = { "literal.key" = "old", keep = \'literal\' } # inline\n' + ) + document = tm.not_none(u.Cli.toml_parse_text(source)) + + u.Cli.toml_sync_document_values( + document, + {"settings": {"literal.key": "new"}}, + ) + + tm.that(u.Cli.toml_dumps(document), eq=source.replace('"old"', '"new"')) + + @staticmethod + @pytest.mark.parametrize("prune", [False, True]) + def test_sync_prunes_only_when_requested(prune: bool) -> None: + """Remove absent root, fragmented and inline keys only for exact sync.""" + source = ( + "obsolete = true\n" + "[tool.uv]\n" + 'link-mode = "copy" # linking\n' + "retired = true\n" + "[project]\nname = 'demo' # project\n" + "[tool.uv.sources]\n" + 'vendor = { path = "vendor/client", editable = true, retired = true }' + " # source\n" + ) + document = tm.not_none(u.Cli.toml_parse_text(source)) + payload: t.JsonDict = { + "project": {"name": "demo"}, + "tool": { + "uv": { + "link-mode": "clone", + "sources": { + "vendor": {"path": "vendor/client", "editable": True}, + }, + }, + }, + } + original_payload = deepcopy(payload) + + u.Cli.toml_sync_document_values(document, payload, prune=prune) + rendered = u.Cli.toml_dumps(document) + tm.that(payload, eq=original_payload) + tm.that(rendered, has="[project]\nname = 'demo' # project\n") + tm.that(rendered, has="# linking") + tm.that(rendered, has="# source") + if prune: + tm.that(tm.ok(u.Cli.toml_mapping_from_text_result(rendered)), eq=payload) + else: + tm.that(rendered, eq=source.replace('"copy"', '"clone"')) + u.Cli.toml_sync_document_values(document, payload, prune=prune) + tm.that(u.Cli.toml_dumps(document), eq=rendered) + + @staticmethod + @pytest.mark.parametrize( + ("source", "payload"), + [ + ("", {"values": []}), + ("values = [1]\n", {"values": ["1"]}), + ], + ) + def test_sync_installs_arrays_with_the_declared_values( + source: str, + payload: t.JsonMapping, + ) -> None: + """Empty and string arrays cannot disappear through scalar normalization.""" + document = tm.not_none(u.Cli.toml_parse_text(source)) + + u.Cli.toml_sync_document_values(document, payload, prune=True) + + tm.that(u.Cli.toml_mapping_from_text(u.Cli.toml_dumps(document)), eq=payload) + + @staticmethod + @pytest.mark.parametrize("prune", [False, True]) + def test_invalid_payload_fails_before_mutating_source(prune: bool) -> None: + """Native null rejection precedes both updates and removal of absent keys.""" + source = 'name = "old" # name\nretained = true\n' + document = tm.not_none(u.Cli.toml_parse_text(source)) + + with u.Tests.raises(TypeError, match="TOML does not support null values"): + u.Cli.toml_sync_document_values( + document, + {"name": "new", "invalid": None}, + prune=prune, + ) + + tm.that(u.Cli.toml_dumps(document), eq=source) + + @staticmethod + @pytest.mark.parametrize( + ("source", "payload"), + [ + ( + "[section.first]\nobsolete = true\n" + "[unrelated]\nkeep = 'value'\n" + '[section]\nvalue = "old" # retained\n', + {"section": {"value": "new"}, "unrelated": {"keep": "value"}}, + ), + ( + "[tool.uv.first]\nobsolete = true\n" + "[project]\nname = 'demo'\n" + "[tool.uv.second]\nobsolete = true\n" + "[unrelated]\nkeep = 'value'\n" + '[tool.uv]\nvalue = "old" # retained\n', + { + "project": {"name": "demo"}, + "unrelated": {"keep": "value"}, + "tool": {"uv": {"value": "new"}}, + }, + ), + ], + ) + def test_prune_refreshes_fragmented_views_before_later_mutations( + source: str, + payload: t.JsonMapping, + ) -> None: + """Deleting earlier fragments cannot invalidate a later write or deletion.""" + document = tm.not_none(u.Cli.toml_parse_text(source)) + + u.Cli.toml_sync_document_values(document, payload, prune=True) + rendered = u.Cli.toml_dumps(document) + + tm.that(tm.ok(u.Cli.toml_mapping_from_text_result(rendered)), eq=payload) + tm.that(rendered, has="# retained") + u.Cli.toml_sync_document_values(document, payload, prune=True) + tm.that(u.Cli.toml_dumps(document), eq=rendered) From 10edeccf81af8027034f9c80a7738646cfbc4559 Mon Sep 17 00:00:00 2001 From: Marlon Costa Date: Sun, 6 Dec 2026 12:11:19 -0300 Subject: [PATCH 2/7] fix(toml): compare native value kinds and retain upstream failure cases MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Traverse mappings without Python's aggregate equality. Compare remaining TOML values by exact type and value, using Core's same_type and one recursive comparison for nested arrays. Keep the single payload preflight and semantic snapshot; do not revalidate complete subtrees while synchronizing. Prove boolean/integer/float changes through native items and serialized TOML, including nested mappings and arrays. Add the exact public reproducers for TOMLKit #732 (nested dotted-key deletion) and #677 (fragmented replacement losing siblings). Preserve their assertions without skips or fallback. The latest official release remains 0.15.3. It includes #677, but #732 was merged after that release and is still unreleased. Re-reading child views is not evidence that #732 is fixed. This candidate remains blocked pending CI and an admissible native dependency release; no pin or lock is changed. Sources: https://github.com/python-poetry/tomlkit/pull/732 https://github.com/python-poetry/tomlkit/pull/677 https://github.com/python-poetry/tomlkit/releases/tag/0.15.3 Traceability v1.1 — 2026-12-06 Author: Marlon Costa — Datacosmos Signed-off-by: Marlon Costa --- .../_toml/flextcliutilitiestoml_part_04.py | 62 ++++++++---- tests/unit/test_toml_document_sync.py | 94 +++++++++++++++++++ 2 files changed, 136 insertions(+), 20 deletions(-) diff --git a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py index 8d9efa9cf..ff65c7a91 100644 --- a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py +++ b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py @@ -21,6 +21,7 @@ FlextCliUtilitiesTomlPart03, ) + class FlextCliUtilitiesTomlPart04: """Implementation part for FlextCliUtilitiesTomlPart04.""" @@ -89,31 +90,52 @@ def _sync_document_values( ] for key, value in payload.items(): current_value = current.get(key) - if current_value == value: - continue - parent = FlextCliUtilitiesTomlPart04._toml_parent_at(document, path) - child: object = parent.get(key) - if ( - isinstance(child, Table | InlineTable | OutOfOrderTableProxy) - and isinstance(value, Mapping) - and isinstance(current_value, Mapping) - ): + if isinstance(value, Mapping) and isinstance(current_value, Mapping): FlextCliUtilitiesTomlPart04._sync_document_values( document, (*path, key), value, current_value, prune=prune ) - elif ( - isinstance(child, Array) - and isinstance(value, list) - and all(isinstance(item, str) for item in child) - and all(isinstance(item, str) for item in value) + elif not FlextCliUtilitiesTomlPart04._toml_values_equal( + current_value, value ): - FlextCliUtilitiesTomlPart04.toml_sync_string_list( - parent, - key, - tuple(item for item in value if isinstance(item, str)), + parent = FlextCliUtilitiesTomlPart04._toml_parent_at(document, path) + child: object = parent.get(key) + if ( + isinstance(child, Array) + and isinstance(value, list) + and all(isinstance(item, str) for item in child) + and all(isinstance(item, str) for item in value) + ): + FlextCliUtilitiesTomlPart04.toml_sync_string_list( + parent, + key, + tuple(item for item in value if isinstance(item, str)), + ) + else: + parent[key] = value + + @staticmethod + def _toml_values_equal(current: t.JsonValue, expected: t.JsonValue) -> bool: + """Compare TOML scalar kinds through nested array and table values. + + Returns: + Whether the values and every nested native kind are identical. + + """ + if not u.same_type(current, expected): + return False + if isinstance(current, dict) and isinstance(expected, dict): + return current.keys() == expected.keys() and all( + FlextCliUtilitiesTomlPart04._toml_values_equal( + current[key], expected[key] ) - else: - parent[key] = value + for key in current + ) + if isinstance(current, list) and isinstance(expected, list): + return len(current) == len(expected) and all( + FlextCliUtilitiesTomlPart04._toml_values_equal(left, right) + for left, right in zip(current, expected, strict=True) + ) + return current == expected @staticmethod def toml_sync_value( diff --git a/tests/unit/test_toml_document_sync.py b/tests/unit/test_toml_document_sync.py index 25c1662c7..02062e5bf 100644 --- a/tests/unit/test_toml_document_sync.py +++ b/tests/unit/test_toml_document_sync.py @@ -9,6 +9,7 @@ from copy import deepcopy import pytest +from tomlkit.items import Array, Float, Integer from tests import t, tm, u @@ -200,3 +201,96 @@ def test_prune_refreshes_fragmented_views_before_later_mutations( tm.that(rendered, has="# retained") u.Cli.toml_sync_document_values(document, payload, prune=True) tm.that(u.Cli.toml_dumps(document), eq=rendered) + + @staticmethod + def test_sync_distinguishes_boolean_integer_and_float_values() -> None: + """Numerically equal scalars still require the declared TOML type.""" + document = tm.not_none( + u.Cli.toml_parse_text("enabled = true\namount = 1\n") + ) + + u.Cli.toml_sync_document_values( + document, + {"enabled": 1, "amount": 1.0}, + ) + + tm.that(document.item("enabled"), is_=Integer) + tm.that(document.item("amount"), is_=Float) + tm.that( + u.Cli.toml_dumps(document), + eq="enabled = 1\namount = 1.0\n", + ) + + @staticmethod + def test_sync_distinguishes_nested_mapping_and_array_types() -> None: + """Nested mappings and arrays cannot hide boolean or numeric type changes.""" + document = tm.not_none( + u.Cli.toml_parse_text( + "values = [true, 1]\n" + "nodes = [{enabled = true, amount = 1}]\n" + "[section]\nenabled = true\n" + "[section.nested]\namount = 1\n" + ) + ) + payload: t.JsonMapping = { + "values": [1, 1.0], + "nodes": [{"enabled": 1, "amount": 1.0}], + "section": {"enabled": 1, "nested": {"amount": 1.0}}, + } + + u.Cli.toml_sync_document_values(document, payload) + rendered = u.Cli.toml_dumps(document) + + values = document.item("values") + assert isinstance(values, Array) + tm.that(values.item(0), is_=Integer) + tm.that(values.item(1), is_=Float) + parsed = tm.ok(u.Cli.toml_mapping_from_text_result(rendered)) + nodes = parsed["nodes"] + assert isinstance(nodes, list) + node = nodes[0] + assert isinstance(node, dict) + tm.that(type(node["enabled"]), eq=int) + tm.that(type(node["amount"]), eq=float) + section = tm.not_none(u.Cli.toml_table_child(document, "section")) + nested = tm.not_none(u.Cli.toml_table_child(section, "nested")) + tm.that(section.item("enabled"), is_=Integer) + tm.that(nested.item("amount"), is_=Float) + u.Cli.toml_sync_document_values(document, payload) + tm.that(u.Cli.toml_dumps(document), eq=rendered) + + @staticmethod + def test_prune_nested_dotted_inline_key_preserves_valid_toml() -> None: + """Deleting one dotted child preserves its real sibling in the document.""" + document = tm.not_none( + u.Cli.toml_parse_text("x = {a.b.c = 1, a.b.d = 2}\n") + ) + payload: t.JsonMapping = {"x": {"a": {"b": {"d": 2}}}} + + u.Cli.toml_sync_document_values(document, payload, prune=True) + rendered = u.Cli.toml_dumps(document) + + tm.that(tm.ok(u.Cli.toml_mapping_from_text_result(rendered)), eq=payload) + u.Cli.toml_sync_document_values(document, payload, prune=True) + tm.that(u.Cli.toml_dumps(document), eq=rendered) + + @staticmethod + def test_replacing_fragmented_child_preserves_native_siblings() -> None: + """Replacing a repeated child cannot remove siblings in other fragments.""" + source = ( + "[y.y.b]\nc = 1\n" + "[y]\nd = 1\n" + "[y.b]\ne = 2\n" + "[y.y]\n" + ) + document = tm.not_none(u.Cli.toml_parse_text(source)) + + u.Cli.toml_sync_document_values(document, {"y": {"y": 1}}) + rendered = u.Cli.toml_dumps(document) + + tm.that( + tm.ok(u.Cli.toml_mapping_from_text_result(rendered)), + eq={"y": {"y": 1, "d": 1, "b": {"e": 2}}}, + ) + u.Cli.toml_sync_document_values(document, {"y": {"y": 1}}) + tm.that(u.Cli.toml_dumps(document), eq=rendered) From 2a03fe75ece83b3ff2f11d43e1b69608f664f12f Mon Sep 17 00:00:00 2001 From: Marlon Costa Date: Sun, 6 Dec 2026 12:27:21 -0300 Subject: [PATCH 3/7] fix(toml): validate JSON payload before native synchronization MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Validate the complete payload once with the existing strict JSON mapping adapter before the native TOML conversion preflight. Pass that validated mapping into recursion; native validation and conversion causes propagate. This closes the timestamp path that toml_document_from_mapping, which requires an already validated mapping, cannot reject by itself. Add six ordinary public cases: native TOML timestamp payloads fail at the JSON field before writes or pruning, and stable Table/InlineTable roots mutate their containing document with and without pruning. The tests check the native validation cause, unchanged rejected inputs, comments, values and a second-pass fixed point. Existing sixteen cases, including the TOMLKit #677/#732 reproducers, are preserved. The standard CI of parent 10edeccf used Python 3.13.18 and TOMLKit 0.15.2. It passed setup and Pyrefly, reported five unresolved lint findings, and ran 1304 passing tests before the #732 reproducer failed on invalid TOML. This child does not claim to fix those native defects or the unread lint diagnostics. No new runtime was executed. No lock, generated file, ref, workflow, gate, budget, suppression or private native field is changed. Traceability v1.0 — 2026-12-06 Marlon Costa — Datacosmos --- .../_toml/flextcliutilitiestoml_part_04.py | 16 +++-- tests/unit/test_toml_document_sync.py | 61 ++++++++++++++++++- 2 files changed, 69 insertions(+), 8 deletions(-) diff --git a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py index ff65c7a91..e41e5881f 100644 --- a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py +++ b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py @@ -34,19 +34,23 @@ def toml_sync_document_values( ) -> None: """Synchronize native TOML values while preserving unchanged source items. - Validate the complete payload before mutation. By default, absent keys - remain untouched; prune=True removes them recursively. The root must be - a stable document or table. Fragmented child views are read again from - that root before every mutation; a proxy is not a valid root. + Validate the complete JSON payload and TOML conversion before mutation. + Absent keys remain untouched; prune=True removes them recursively. The + root must be a stable document or table. Fragmented child views are read + again from that root before every mutation; a proxy is not a valid root. Native conversion and validation errors propagate unchanged. """ - FlextCliUtilitiesTomlPart01.toml_document_from_mapping(payload) + validated = FlextCliUtilitiesConversion.JSON_MAPPING_ADAPTER.validate_python( + payload, + strict=True, + ) + FlextCliUtilitiesTomlPart01.toml_document_from_mapping(validated) current = FlextCliUtilitiesConversion.JSON_MAPPING_ADAPTER.validate_python( document.unwrap(), strict=True, ) FlextCliUtilitiesTomlPart04._sync_document_values( - document, (), payload, current, prune=prune + document, (), validated, current, prune=prune ) @staticmethod diff --git a/tests/unit/test_toml_document_sync.py b/tests/unit/test_toml_document_sync.py index 02062e5bf..c7a774f0b 100644 --- a/tests/unit/test_toml_document_sync.py +++ b/tests/unit/test_toml_document_sync.py @@ -9,9 +9,9 @@ from copy import deepcopy import pytest -from tomlkit.items import Array, Float, Integer +from tomlkit.items import Array, Float, InlineTable, Integer, Table -from tests import t, tm, u +from tests import m, t, tm, u class TestsFlextCliTomlDocumentSync: @@ -163,6 +163,63 @@ def test_invalid_payload_fails_before_mutating_source(prune: bool) -> None: tm.that(u.Cli.toml_dumps(document), eq=source) + @staticmethod + @pytest.mark.parametrize("prune", [False, True]) + def test_non_json_payload_fails_before_mutating_source(*, prune: bool) -> None: + """A native TOML timestamp cannot pass the public JSON payload boundary.""" + source = 'name = "old" # name\nretained = true\n' + document = tm.not_none(u.Cli.toml_parse_text(source)) + payload_source = 'name = "new"\nstamp = 2026-01-01T00:00:00\n' + payload = tm.not_none(u.Cli.toml_parse_text(payload_source)) + + with u.Tests.raises(m.ValidationError) as error: + u.Cli.toml_sync_document_values(document, payload, prune=prune) + + tm.that(error.value.errors()[0]["loc"], eq=("stamp",)) + tm.that(error.value.errors()[0]["type"], eq="invalid-json-value") + tm.that(u.Cli.toml_dumps(document), eq=source) + tm.that(u.Cli.toml_dumps(payload), eq=payload_source) + + @staticmethod + @pytest.mark.parametrize("prune", [False, True]) + @pytest.mark.parametrize( + "source", + [ + ( + 'outside = "keep" # outside\n' + "[settings] # selected\n" + 'value = "old"\nobsolete = true\n' + ), + ( + 'outside = "keep" # outside\n' + 'settings = { value = "old", obsolete = true } # selected\n' + ), + ], + ids=("table", "inline-table"), + ) + def test_sync_table_roots_mutates_the_containing_document( + source: str, *, prune: bool + ) -> None: + """Stable Table and InlineTable roots update the real parent document.""" + document = tm.not_none(u.Cli.toml_parse_text(source)) + root = tm.not_none(u.Cli.toml_item_child(document, "settings")) + assert isinstance(root, Table | InlineTable) + expected: t.JsonMapping = { + "outside": "keep", + "settings": ( + {"value": "new"} if prune else {"value": "new", "obsolete": True} + ), + } + + u.Cli.toml_sync_document_values(root, {"value": "new"}, prune=prune) + rendered = u.Cli.toml_dumps(document) + + tm.that(tm.ok(u.Cli.toml_mapping_from_text_result(rendered)), eq=expected) + tm.that(rendered, has="# outside") + tm.that(rendered, has="# selected") + u.Cli.toml_sync_document_values(root, {"value": "new"}, prune=prune) + tm.that(u.Cli.toml_dumps(document), eq=rendered) + @staticmethod @pytest.mark.parametrize( ("source", "payload"), From ee1257853155b8295421de153ef79a8c191e46c3 Mon Sep 17 00:00:00 2001 From: Marlon Costa Date: Sun, 6 Dec 2026 12:32:15 -0300 Subject: [PATCH 4/7] test(toml): make pruning flags keyword-only MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Correct two boolean positional parameters in the public TOML sync tests. The repository enables Ruff ALL and exempts only assert in test files. The released Ruff 0.17.6 FBT001 rule applies to these two definitions; pytest parametrize already supplies the named parameters. Only the two signatures change. Test scenarios, assertions, order and ordinary budgets stay intact. This correction is supported by the rule and source configuration, not inferred from the five lint findings in the parent CI log. The other lint diagnostics remain unread. TOMLKit #677 and #732 remain active and this commit is not runtime-qualified. Traceability v1.0 — 2026-12-06 Marlon Costa — Datacosmos --- tests/unit/test_toml_document_sync.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/unit/test_toml_document_sync.py b/tests/unit/test_toml_document_sync.py index c7a774f0b..02ad66b76 100644 --- a/tests/unit/test_toml_document_sync.py +++ b/tests/unit/test_toml_document_sync.py @@ -89,7 +89,7 @@ def test_sync_changes_inline_values_without_replacing_the_table() -> None: @staticmethod @pytest.mark.parametrize("prune", [False, True]) - def test_sync_prunes_only_when_requested(prune: bool) -> None: + def test_sync_prunes_only_when_requested(*, prune: bool) -> None: """Remove absent root, fragmented and inline keys only for exact sync.""" source = ( "obsolete = true\n" @@ -149,7 +149,7 @@ def test_sync_installs_arrays_with_the_declared_values( @staticmethod @pytest.mark.parametrize("prune", [False, True]) - def test_invalid_payload_fails_before_mutating_source(prune: bool) -> None: + def test_invalid_payload_fails_before_mutating_source(*, prune: bool) -> None: """Native null rejection precedes both updates and removal of absent keys.""" source = 'name = "old" # name\nretained = true\n' document = tm.not_none(u.Cli.toml_parse_text(source)) From dfebf96ab4c1e72dfbbd2090ce77ab9dba6b27a8 Mon Sep 17 00:00:00 2001 From: Marlon Costa Date: Sun, 6 Dec 2026 12:43:40 -0300 Subject: [PATCH 5/7] test(toml): expose comment loss when resizing string arrays MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add three ordinary regressions through the public string-array sync owner: extend after a terminal standalone comment without a trailing comma, shorten, and empty the array. Check parsed values, inline comments of the surviving native slots, all standalone comments, the outer key comment, the original Array identity and a second-pass fixed point. The cases preserve TOMLKit's positional comment semantics. They do not infer ownership from an equal string value or require comments to move with a reordered value. Existing code replaces the whole Array whenever its length changes, so these cases are prepared to expose that authored loss independently of the known native dependency failures. All twenty-two existing cases remain byte-for-byte intact. These new cases precede the upstream #732/#677 reproducers so ordinary failfast can expose this owner defect. No productive source, lock, generated file, workflow, gate, budget, suppression or ref is changed. This RED candidate has not been executed; runtime evidence must come from normal PR CI. Editing an existing reserved provenance comment while retaining standalone comments remains a separate native API limitation and is not addressed. Traceability v1.0 — 2026-12-06 Marlon Costa — Datacosmos --- tests/unit/test_toml_document_sync.py | 56 +++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/tests/unit/test_toml_document_sync.py b/tests/unit/test_toml_document_sync.py index 02ad66b76..17ae6dad7 100644 --- a/tests/unit/test_toml_document_sync.py +++ b/tests/unit/test_toml_document_sync.py @@ -316,6 +316,62 @@ def test_sync_distinguishes_nested_mapping_and_array_types() -> None: u.Cli.toml_sync_document_values(document, payload) tm.that(u.Cli.toml_dumps(document), eq=rendered) + @staticmethod + @pytest.mark.parametrize( + ("expected", "comments"), + [ + (["new", "keep", "added"], ("# first slot", "# second slot", "")), + (["new"], ("# first slot",)), + ([], ()), + ], + ids=("extend", "shorten", "empty"), + ) + def test_string_array_resize_preserves_existing_comments_and_identity( + expected: list[str], + comments: tuple[str, ...], + ) -> None: + """Native slots retain their comments; standalone notes remain in place.""" + source = ( + "values = [\n" + " # before values\n" + ' "old", # first slot\n' + " # between values\n" + ' "keep" # second slot\n' + " # after values\n" + "] # array\n" + ) + document = tm.not_none(u.Cli.toml_parse_text(source)) + original = tm.not_none(u.Cli.toml_item_child(document, "values")) + assert isinstance(original, Array) + + tm.that( + u.Cli.toml_sync_string_list(document, "values", expected), + eq=True, + ) + rendered = u.Cli.toml_dumps(document) + + tm.that( + tm.ok(u.Cli.toml_mapping_from_text_result(rendered))["values"], + eq=expected, + ) + tm.that( + u.Cli.toml_array_item_comments(document, "values"), + eq=comments, + ) + for comment in ( + "# before values", + "# between values", + "# after values", + "# array", + ): + tm.that(rendered, has=comment) + assert u.Cli.toml_item_child(document, "values") is original + tm.that( + u.Cli.toml_sync_string_list(document, "values", expected), + eq=False, + ) + tm.that(u.Cli.toml_dumps(document), eq=rendered) + @staticmethod def test_prune_nested_dotted_inline_key_preserves_valid_toml() -> None: """Deleting one dotted child preserves its real sibling in the document.""" From 32930eb58f1fcd1ddb4a18c80a1ae0293acb1dd8 Mon Sep 17 00:00:00 2001 From: Marlon Costa Date: Sun, 6 Dec 2026 12:45:10 -0300 Subject: [PATCH 6/7] fix(toml): satisfy native lint without changing synchronization cases MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use itertools.starmap for the existing recursive pair comparison. Parenthesize the two intentional source-string concatenations. Preserve all 22 public cases, fixtures, assertions and strict JSON validation. Native diagnostics: 47667870108 / job146139888972; FURB140 and two ISC004 findings. This change does not fix the upstream TOMLKit deletion defect or qualify this PR for merge. Marlon Costa — Datacosmos. --- .../_toml/flextcliutilitiestoml_part_04.py | 7 +++++-- tests/unit/test_toml_document_sync.py | 20 +++++++++++-------- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py index e41e5881f..93b8f09be 100644 --- a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py +++ b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py @@ -7,6 +7,7 @@ from __future__ import annotations from collections.abc import Mapping, Sequence +from itertools import starmap from flext_core import u from tomlkit.container import OutOfOrderTableProxy @@ -136,8 +137,10 @@ def _toml_values_equal(current: t.JsonValue, expected: t.JsonValue) -> bool: ) if isinstance(current, list) and isinstance(expected, list): return len(current) == len(expected) and all( - FlextCliUtilitiesTomlPart04._toml_values_equal(left, right) - for left, right in zip(current, expected, strict=True) + starmap( + FlextCliUtilitiesTomlPart04._toml_values_equal, + zip(current, expected, strict=True), + ) ) return current == expected diff --git a/tests/unit/test_toml_document_sync.py b/tests/unit/test_toml_document_sync.py index 02ad66b76..db3db92ac 100644 --- a/tests/unit/test_toml_document_sync.py +++ b/tests/unit/test_toml_document_sync.py @@ -225,17 +225,21 @@ def test_sync_table_roots_mutates_the_containing_document( ("source", "payload"), [ ( - "[section.first]\nobsolete = true\n" - "[unrelated]\nkeep = 'value'\n" - '[section]\nvalue = "old" # retained\n', + ( + "[section.first]\nobsolete = true\n" + "[unrelated]\nkeep = 'value'\n" + '[section]\nvalue = "old" # retained\n' + ), {"section": {"value": "new"}, "unrelated": {"keep": "value"}}, ), ( - "[tool.uv.first]\nobsolete = true\n" - "[project]\nname = 'demo'\n" - "[tool.uv.second]\nobsolete = true\n" - "[unrelated]\nkeep = 'value'\n" - '[tool.uv]\nvalue = "old" # retained\n', + ( + "[tool.uv.first]\nobsolete = true\n" + "[project]\nname = 'demo'\n" + "[tool.uv.second]\nobsolete = true\n" + "[unrelated]\nkeep = 'value'\n" + '[tool.uv]\nvalue = "old" # retained\n' + ), { "project": {"name": "demo"}, "unrelated": {"keep": "value"}, From 440f403e8328abfcef1d13301d697e5690a28eec Mon Sep 17 00:00:00 2001 From: Marlon Costa Date: Sun, 6 Dec 2026 12:55:04 -0300 Subject: [PATCH 7/7] fix(toml): preserve native array comments when resizing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Retain the original Array, update existing positions, delete a shortened tail, and add new values through the public add_line API. Native comments remain positional. Keep the existing normalization and idempotence contract. The standard CI run 47669384921 on e21deeee reproduced the extend regression with TOMLKit 0.15.2: inline comments became ('', '', ''). Lint and Pyrefly passed; the primary test step reported 1 failed, 1313 passed, 70 deselected in 37.72s. The second standard step reproduced the same failure with 51 passed in 1.42s. Shorten and empty were not reached under failfast. Preserve all 25 public sync cases and the concurrent lint repairs. This source fix still requires normal CI. Upstream #677/#732 and editing reserved provenance comments remain separate blockers. Traceability v1.0 — 2026-12-06 — Marlon Costa — Datacosmos. --- .../_toml/flextcliutilitiestoml_part_04.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py index 93b8f09be..8b1dff736 100644 --- a/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py +++ b/src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py @@ -172,6 +172,8 @@ def toml_sync_string_list( ) -> bool: """Synchronize a TOML string-array value; return True if mutated. + Existing arrays retain native comments by position when values change. + Returns: The resulting ``bool``. @@ -186,14 +188,14 @@ def toml_sync_string_list( if normalized_expected is None: return False original = FlextCliUtilitiesTomlPart02.toml_item_child(container, key) - if ( - not sort_values - and isinstance(original, Array) - and len(original) == len(normalized_expected) - ): - for index, value in enumerate(normalized_expected): + if isinstance(original, Array): + for index, value in enumerate(normalized_expected[: len(original)]): if original[index] != value: original[index] = value + if len(original) > len(normalized_expected): + del original[len(normalized_expected) :] + elif len(original) < len(normalized_expected): + original.add_line(*normalized_expected[len(original) :]) return True container[key] = FlextCliUtilitiesTomlPart01.toml_array(normalized_expected) return True