Skip to content

sort_keys moves a parent value into an array-of-tables element #729

Backlog

Description

@fernandezbaptiste

Hullo folks,

I'm doing some research for Tessl Code Review and we ran it against your repo. It flagged a potential issue, and I figured it made sense to share it with you:

dumps(..., sort_keys=True) can change which table owns a value when a parsed table contains an array of tables. The output remains valid TOML, so a configuration rewrite can silently change its meaning.

Reproduced on current main 3cdcbde4f35afd83010fcd0a29e5f3665d674628, Python 3.14.2/macOS:

import tomlkit

source = "[t]\nz = 1\n[[t.a]]\nx = 2\n"
document = tomlkit.loads(source)
output = tomlkit.dumps(document, sort_keys=True)

print(output)
print(document.unwrap())
print(tomlkit.loads(output).unwrap())

Actual output:

[t]
[[t.a]]
x = 2
z = 1

Before: {'t': {'z': 1, 'a': [{'x': 2}]}}

After reparsing: {'t': {'a': [{'x': 2, 'z': 1}]}}

Expected: sorting preserves the data, with z = 1 still in t, before the [[t.a]] section.

In _sort_container_body(), the isinstance(value, dict) grouping does not treat AoT as a section-opening entry. Alphabetical order can therefore put it before an ordinary value; rendering that value afterward gives it the array element's scope.

This follows the recursive sorting added in #617. I checked its discussion and related sorting reports; the problem here is the changed table ownership, rather than incomplete sorting.

The reproduction used unchanged source and the public parse/dump APIs. No mocked parser, fix PR or full-suite run is included.

Full transparency: I work at Tessl, and we've spotted that using Tessl Code Review - using repository-level context and specific review lenses that improve over time through feedback. That’s how this finding surfaced.

We’re just getting started and want to offer the tool free to open-source projects. If this is useful, happy to give you access.

Baptiste

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions