Skip to content

fix(toml): centralize source-preserving document synchronization - #515

Open
marlon-costa-dc wants to merge 10 commits into
0.12.0-devfrom
fix/native-toml-sync-20261206-10edeccf
Open

marlon-costa-dc wants to merge 10 commits into
0.12.0-devfrom
fix/native-toml-sync-20261206-10edeccf

Conversation

@marlon-costa-dc

@marlon-costa-dc marlon-costa-dc commented Dec 6, 2026 •

Copy link
Copy Markdown
Contributor

Composição validada; falha nativa #732 continua exposta

Head: cf2f8b84ac7fa715a3241e0e68b2c1e7cad8a688. Árvore: a5983aafa5423ec0cc2c39248631669bd47c7dd5.

A CI 47672168139 / job 146153575329 executou o preview 11dcba28833a183ecc4fc12cdbb37c3dbe2cbe9f, com pais integração 651eef43 e este head. Sua árvore coincide com a composição revisada. O ambiente instalou TOMLKit 0.15.2.

Setup passou. Ruff reportou zero erros em 0,18 s. Pyrefly reportou zero erros em 2,45 s. Os quatro casos comuns de array e as quatro variantes Table/InlineTable passaram nas duas etapas padrão.

  • Etapa principal: 1 failed, 1.317 passed, 70 deselected em 28,80 s.
  • Segunda etapa: 1 failed, 55 passed em 1,04 s.
  • Ambas param no reproduzidor de TOMLKit #732, com erro de parse na linha 1, coluna 6.
  • O caso #677 continua não alcançado pelo failfast. Nenhuma suíte atingiu timeout.

As threads de cobertura de raízes, ordenação, preservação de comentários e fronteira JSON estão resolvidas. Permanecem abertas as de #677, #732 e acoplamento nominal ao tipo nativo de tabela fragmentada. O check do Cubic terminou com sucesso, mas não executou uma revisão nova deste merge; não se atribui uma revisão inexistente a esse status.

O reparo de arrays está integrado pelo #518, inclusive com a CI push do merge aprovada. O novo sincronizador deste PR continua bloqueado para merge e adoção pelo Infra. Os reproduzidores upstream permanecem ativos e os 22 + 4 casos continuam na árvore.

Rastreabilidade: versão 1.9; 2026-12-06; Marlon Costa marlon.costa@datacosmos.com.br — Datacosmos.


Histórico anterior

Reparo integrado adotado; regressões sem duplicação

Head: cf2f8b84ac7fa715a3241e0e68b2c1e7cad8a688. Árvore: a5983aafa5423ec0cc2c39248631669bd47c7dd5.

O CLI #518 foi integrado no commit 651eef4332de458158003e0f798a48e486607280. Sua árvore coincide com a que aprovou 1.469 testes, os quatro casos de array, lint, Pyrefly, Sonar e Semgrep na CI 47671030224 / job 146149988738.

Este merge ordinário conserva os pais 440f403e e 651eef43. A comparação completa preserva os seis blobs de fonte específicos do fornecedor, incluindo starmap, validação JSON strict e a nova API. Contra 440, apenas dois arquivos de teste mudam:

  • Entra o módulo comum de quatro casos, exatamente no blob integrado 2ce1ada4a5e2da3fdcb404001b6ecacd3acf6651.
  • Sai somente o bloco duplicado de 56 linhas do módulo de documentos. Esse módulo volta ao blob db3db92acab14456fd4bb2de3e6ba6bf43693a49, com seus 22 casos intactos.

O total fica 22 + 4, sem duplicação ou perda de regressões. O caso de atualização ordenada passa a fazer parte desta composição e atende à observação correspondente da revisão.

A CI padrão desta composição ainda precisa concluir. Os recibos anteriores não são transferidos para este head. Os testes de TOMLKit #677/#732 permanecem ativos; o bloqueio de #732 e a adoção pelo Infra continuam pendentes. Não pronto para merge.

Rastreabilidade: versão 1.8; 2026-12-06; Marlon Costa marlon.costa@datacosmos.com.br — Datacosmos.


Histórico anterior

Arrays corrigidos e comprovados; bloqueio upstream permanece

Head: 440f403e8328abfcef1d13301d697e5690a28eec. Árvore: b8f24a56b394d7d52d763bf4dece2c7cae44860a.

A CI 47670085003 / job 146146933489, tentativa 1, executou a61e1afcdf87925cc8597502c27d4b0efc216b0e, com pais bef2da1c e este head. A árvore testada coincide com a do candidato. TOMLKit instalado: 0.15.2.

  • Setup passou.
  • Ruff: zero erros, 0,23 s. Pyrefly: zero erros, 3,29 s.
  • Extend, shorten e empty passaram nas duas etapas padrão. A perda de comentários reproduzida no parent está corrigida.
  • A etapa principal terminou com 1 failed, 1316 passed, 70 deselected em 36,31 s. A segunda terminou com 1 failed, 54 passed em 1,36 s. Não houve timeout.
  • As duas falhas são do reproduzidor ativo de TOMLKit #732, com o mesmo erro de parse na linha 1, coluna 6. O caso #677 ainda não foi alcançado.

Os quatro casos diretos de Table/InlineTable, com e sem poda, passaram nas duas etapas. A thread que pedia essa cobertura foi marcada como resolvida depois da leitura dos oito registros PASS. A thread da perda de comentários foi resolvida pela revisão automática.

O reparo do helper existente e suas regressões seguem também no PR independente #518, para qualificação e integração sem depender do novo sincronizador. A revisão identificou uma cobertura adicional necessária para sort_values=True em Array comentado existente. Esse caso será incluído no módulo comum do #518 e adotado aqui, preservando a normalização e evitando testes duplicados.

Este PR continua bloqueado para merge e adoção pelo Infra. A release oficial mais recente do TOMLKit continua 0.15.3; a correção #732 ainda não foi publicada nela. A edição de marcas de proveniência permanece separada. Nenhum caso upstream foi retirado, desativado ou relaxado.

Rastreabilidade: versão 1.7; 2026-12-06; Marlon Costa marlon.costa@datacosmos.com.br — Datacosmos.


Histórico anterior

Reparo do Array publicado após falha causal na CI

Head: 440f403e8328abfcef1d13301d697e5690a28eec. Árvore: b8f24a56b394d7d52d763bf4dece2c7cae44860a.

A CI do RED e21deeee, run 47669384921 / job 146144694516, testou c0f41504fb17a9e8f7ae61d08b759f1311beee7f. O preview combina a base bef2da1c e e21; sua árvore é idêntica à do RED. Python 3.13.18 e TOMLKit 0.15.2 foram instalados.

Setup, Ruff e Pyrefly passaram. As duas etapas padrão falharam no novo caso extend: os comentários retornados eram ('', '', ''), em vez de ('# first slot', '# second slot', ''). A etapa principal reportou 1 failed, 1313 passed, 70 deselected em 37,72 s; a segunda, 1 failed, 51 passed em 1,42 s. Sem timeout. Shorten, empty e os dois reproduzidores upstream não foram alcançados nesse run.

O reparo altera apenas o helper existente em Part04, +8/-6. Ele mantém o Array original, altera o prefixo por índice, remove a cauda por slice e amplia com add_line. Assim, usa as operações públicas nativas sem reconstruir o Array, acessar campos privados ou inventar associação de comentários por valor. A normalização e o no-op de permutações com sort_values permanecem anteriores à mutação.

Revisão independente conferiu o TOMLKit 0.15.2, os consumidores e os testes de ordenação. Todos os 25 casos permanecem byteidênticos, no blob 2605f3f33bf307d3d3e97128f067da14136000c7. O starmap e as correções de lint concorrentes também permanecem intactos.

A CI padrão deste head ainda precisa comprovar o reparo. TOMLKit #677/#732 e a edição das marcas de proveniência continuam pendentes. Não pronto para merge ou adoção pelo Infra. Nenhuma dependência, projeção, regra ou limite mudou.

Rastreabilidade: versão 1.6; 2026-12-06; Marlon Costa marlon.costa@datacosmos.com.br — Datacosmos.


Histórico anterior

Regressão pública de comentários publicada; correções concorrentes preservadas

Head: e21deeee9b7f58566f82090e3226d699783934be. Árvore: e325f2f71389b28b438dc23a07211a3e5927e63b.

O merge ordinário tem pais 32930eb58f1fcd1ddb4a18c80a1ae0293acb1dd8 e dfebf96ab4c1e72dfbbd2090ce77ab9dba6b27a8. Preserva a integração concorrente, o uso de starmap e as correções ISC004. Contra o primeiro pai, muda apenas o teste público: +56/-0. Ao retirar o novo bloco, o arquivo coincide byte a byte com o teste de 32930eb. Nenhuma fonte produtiva, dependência ou projeção mudou neste passo.

Os três novos casos verificam ampliação, redução e esvaziamento de uma Array. Exigem valores parseados, comentários inline dos slots sobreviventes, notas standalone, comentário externo da chave, identidade do mesmo Array e segunda passagem estável. O caso de ampliação inclui comentário standalone terminal e último valor sem vírgula. Os comentários seguem a posição nativa; não há associação por valor inventada. Total: 25 casos, com os três novos antes dos reproduzidores upstream. A CI padrão deve estabelecer o RED antes do reparo do helper existente.

O checkout efetivo e11755b7b4ade27ab0a2b8aadbfe8741fa6bed78 da CI do parent combina a base bef2da1c com 32930eb5; sua árvore é idêntica à de 32930eb.

A CI própria de 32930eb terminou. Setup passou; Ruff e Pyrefly passaram com zero erros. A etapa principal reportou 1 failed, 1313 passed, 70 deselected em 25,72 s; a segunda etapa reportou 1 failed, 51 passed em 0,90 s. Ambas expuseram o mesmo defeito TOMLKit #732. Portanto, os três findings anteriores de lint estão resolvidos nesse parent. Esse recibo não qualifica o novo teste nem remove o bloqueio upstream.

Não pronto para merge ou adoção pelo Infra. O reparo dos arrays preservará o owner CLI existente. A edição de marcas de proveniência no Infra continua separada: não foi encontrada operação pública nativa que altere essas marcas conservando todos os comentários standalone.

Rastreabilidade: versão 1.5; 2026-12-06; Marlon Costa marlon.costa@datacosmos.com.br — Datacosmos.


Histórico anterior

Candidata 32930eb: base atual adotada e correções de lint publicadas

Head: 32930eb58f1fcd1ddb4a18c80a1ae0293acb1dd8. Árvore: ed3d33c8dee5190171a52a2eb23df6eb64d4b623. CI própria em andamento. O PR continua bloqueado para merge.

O merge normal 600e7ee6560f107b0847015aa0fe772243de28be, com pais ee12578 e bef2da1, adota a integração na branch candidata. Usa a árvore 199fdd7845ede9e1b93b7cbac696b6cddfdde98f do preview GitHub e6671c8 já executado. A comparação completa de 1.140 folhas preservou os sete paths TOML e os cinco paths XLSX/ambiente integrados.

O filho 32930 corrige os três diagnósticos nativos restantes: FURB140 com itertools.starmap sobre o mesmo zip(..., strict=True); dois ISC004 com parênteses nas concatenações intencionais dos fixtures. Os outros oito métodos do owner permanecem idênticos. O AST integral dos testes permanece igual: 22 casos, 189 tokens de strings, 38 chamadas tm.that e quatro assert. Validação JSON strict, recursão e algoritmo de arrays preservados. Blobs revisados e publicados: owner 93b8f09be324c8f8e399f122d8e19674f89a6965; testes db3db92acab14456fd4bb2de3e6ba6bf43693a49.

O diagnóstico veio da CI 47667870108 / job146139888972: setup aprovado, Ruff com três findings, Pyrefly com zero erros, 1 failed, 1313 passed, 70 deselected em 24,25 s na etapa de testes executada. Os seis casos novos de JSON/raízes passaram. O artefato 15995531725, SHA-256 8e9feb4df930b14c016c9ccbe35cad3cbd356b1e59a7067d87b8726489081a1b, identifica os três pontos; os dois FBT001 anteriores já desapareceram.

CI própria de 32930: 47668837671 / job146142958605 ainda precisa concluir. O resultado anterior não é transferido.

O defeito nativo TOMLKit #732 e a análise dos comentários em arrays alterados continuam abertos. A versão instalada no recibo anterior é 0.15.2. A correção #732 ainda não está na release oficial 0.15.3; #677 está em 0.15.3, mas seu teste não foi alcançado no recibo anterior. Ambos os reproduzidores permanecem ativos. Nenhum lock, projeção, limite ou regra foi alterado.

Rastreabilidade do complemento: versão 1.4; 06/12/2026 — America/Sao_Paulo; Marlon Costa marlon.costa@datacosmos.com.br — Datacosmos.


Histórico preservado até ee12578

Fronteira JSON e raízes nativas complementadas; nova CI pendente

Head atual: ee1257853155b8295421de153ef79a8c191e46c3. Árvore: dcb9edd9079a58cab3639715a5f74da099da148b.

O filho 2a03fe75 valida o payload com o JSON_MAPPING_ADAPTER existente, em modo strict, antes da conversão TOML e de qualquer mutação. A recursão recebe o mapping validado. Foram adicionados seis casos públicos: rejeição de timestamp TOML fora da fronteira JSON com/sem poda e raízes Table/InlineTable com/sem poda. Eles verificam causa, bytes intactos quando inválido, alteração no documento pai, comentários e ponto fixo. Total: 22 casos. Os 16 anteriores permanecem ativos.

O filho ee125785 altera somente duas assinaturas de teste para *, prune: bool. A revisão confirmou a violação FBT001 pela configuração real select = ["ALL"], sem exceção para bool em testes, e pela implementação oficial do Ruff 0.17.6. A mudança preserva casos e expectativas. Não se deduz desse diagnóstico estático que os cinco findings da CI anterior estejam resolvidos.

A revisão independente aprovou o delta JSON/raízes para CI. A cadeia pública de m.ValidationError foi conferida no Core instalado e no lock standalone. Não foram introduzidos casts, mocks ou acessos privados para construir os casos inválidos.

Os bloqueios TOMLKit #677/#732 continuam. A perda/associação de comentários em arrays alterados está em análise no owner CLI existente; o Infra não receberá um algoritmo paralelo. Esta revisão não altera dependências, locks, arquivos gerados, políticas ou limites.

A CI padrão deste head precisa concluir. O recibo anterior abaixo é histórico e não qualifica automaticamente o novo candidato.

Rastreabilidade: versão 1.3; 2026-12-06; Marlon Costa marlon.costa@datacosmos.com.br — Datacosmos.


Histórico e evidências anteriores

CI confirmou o bloqueio de poda nativa

Head testado: 10edeccf81af8027034f9c80a7738646cfbc4559.

A CI 47665701778 / job 146133041643, tentativa 1, executou o preview ca8c96b42a6faaa597026459636a68f192fe44ca. Seus pais são a base 5d6beb18 e este head; a árvore coincide com a do candidato. O setup usou o workspace 6d4dc1e4, Python 3.13.18 e TOMLKit 0.15.2.

  • Setup passou.
  • Pyrefly 1.4.1 passou: zero erros, 2,209 s.
  • Ruff 0.17.6 reportou 5 findings. O log mostra a contagem, mas não os diagnósticos individuais; eles continuam pendentes de leitura no artefato 15994940999. Nenhuma regra foi deduzida dessa contagem.
  • A etapa principal de testes foi pulada após check. A etapa autoral project-tests, condicionada apenas ao setup, executou: 1 failed, 1304 passed, 70 deselected em 30,14 s.
  • 14 dos 16 casos novos passaram. O reproduzidor de #732 falhou ao reler o TOML emitido após poda: Invalid initial character for a key part (at line 1, column 6). O caso #677 não foi alcançado por causa da parada na primeira falha.
  • Sonar, Semgrep e Cubic encerraram com status success. Isso não substitui os gates bloqueantes nem significa que as observações de revisão estejam todas resolvidas.

A perda de validade está comprovada na dependência instalada. A correção permanece no owner upstream, sem fallback, consolidação destrutiva, supressão ou alteração dos casos de regressão.

Revisão em andamento

Os casos de raízes Table/InlineTable e a validação estrita da entrada JSON estão sendo complementados. O comportamento de comentários em arrays alterados precisa de delimitação e prova. A integração nominal com OutOfOrderTableProxy já existe no CLI e corresponde ao tipo retornado pelo TOMLKit; o código usa seus métodos de mapping e não acessa campos como _container ou _tables. Não se afirma independência desse tipo da dependência.

Não pronto para merge ou adoção pelo Infra. Locks e política de atualização permanecem intactos. Os bloqueios de lint e dependência não foram reclassificados como sucesso.

Rastreabilidade: versão 1.2; 2026-12-06; Marlon Costa marlon.costa@datacosmos.com.br — Datacosmos.


Escopo e histórico do candidato

Causa e alteração

O Infra mantém uma sincronização genérica de TOML fora do domínio canônico. Ela usa um helper de leitura que consolida tabelas fora de ordem em uma cópia; uma escrita nessa cópia não garante alteração do documento original.

Este PR adiciona u.Cli.toml_sync_document_values(document, payload, *, prune=False) no owner TOML do CLI. A API propõe sincronizar os valores mantendo os nós inalterados e seus comentários. A entrada exige Document, Table ou InlineTable estáveis. As views de filhos são consultadas de novo pela API pública antes de cada mutação. O payload passa por validação nativa antes das escritas; a recursão usa um único snapshot.

A comparação distingue boolean, integer e float em estruturas aninhadas. Ela reutiliza u.same_type do Core. Os helpers públicos existentes mantêm seus contratos; não há alias de compatibilidade, cópia do parser ou acesso privado do TOMLKit. O consumidor Infra ainda precisa adotar esta API e retirar seu helper duplicado.

Head: 10edeccf81af8027034f9c80a7738646cfbc4559.
Árvore: b34d4742a0e92136a108ff596f2f950ad267e3af.
Base de implementação: 5d6beb189df78970551e6b20c91a6632ff72bc49.

Provas incluídas

São 16 casos ordinários pela fachada pública. Cobrem escrita no documento original, tabelas inline e fora de ordem, quoted keys, strings multilinha e AoT inalterados, poda opcional, tipos nativos, arrays, rejeição de null antes de mutar e ponto fixo.

Os testes de tipos verificam Integer e Float nativos e o texto produzido. Uma comparação Python de dicionários poderia aceitar incorretamente True == 1 == 1.0; essa falsa prova foi evitada.

Os casos incluem os reproduzidores oficiais de TOMLKit #677 e #732. Nenhum foi removido, desativado, marcado xfail ou movido para slow. Execução local: não executada. A CI padrão deste head ainda precisa estabelecer o resultado. A revisão independente encontrou os bloqueios nativos descritos abaixo.

Bloqueio nativo conhecido

Os locks lidos do membro CLI e do workspace 6d4dc1e4c767848b1d23345e9e8679efc71a6886 ainda selecionam TOMLKit 0.15.2.

  • TOMLKit #677 corrige a perda de campos irmãos ao substituir uma chave fragmentada. A correção saiu em 0.15.3.
  • TOMLKit #732 corrige TOML inválido após remover uma chave dotted aninhada em inline table. Foi mesclado em 2026-12-04, no commit 87fc86a8d1b4d920a7ed277eaea947c6228729ed, e ainda não está na release oficial mais recente. O teste upstream já reconsulta a view antes de cada remoção; isso não elimina esse defeito nas versões publicadas.

Este PR não contém a correção desses defeitos da dependência e não está pronto para merge. Os testes permanecem ativos para que a CI exponha o comportamento da versão realmente instalada. Não haverá adaptação do teste, supressão ou implementação paralela para aparentar verde.

Dependências e continuidade

A declaração CLI continua tomlkit>=0.15.1. A CI instala pelo setup frozen e não re-resolve dependências. O escritor canônico dos locks é make upg, no owner do runtime. Declarações, locks e arquivos gerados permanecem sem alteração.

O Infra #3044 e a preservação de fontes autorais da issue #333 dependem da prova do fornecedor e de uma versão nativa admissível. O consumidor precisa adotar o fornecedor pelo produtor existente antes de chamar a nova API. A materialização de gitlinks da issue #333 continua fora deste reparo.

Rastreabilidade

Versão: 1.1
Data: 2026-12-06
Autor: Marlon Costa marlon.costa@datacosmos.com.br — Datacosmos.


Summary by cubic

Adds u.Cli.toml_sync_document_values to the CLI owner, centralizing source-preserving TOML document synchronization so flext-infra can drop its generic helper. The recursive API validates the full JSON payload before mutation, re-reads fragmented child views from the document root before each write, only removes absent keys with prune=True, and compares native scalar types instead of Python aggregate equality. It also extends TomlParent to cover InlineTable and OutOfOrderTableProxy, resizes string arrays in place so native comments and Array identity survive extend/shorten/empty operations, and adds 26 public test cases including reproducers for TOMLKit #677 and #732. The array resize regressions are shared from the integrated four-case module instead of duplicated locally.

Blockers

  • The pinned TOMLKit 0.15.2 lacks the #677 fix (released in 0.15.3), and #732 is still unreleased, so CI should expose those failures rather than suppress them.
  • No pins, lock changes, or test suppression are included; the PR is not ready to merge. It also merges 0.12.0-dev and fixes lint findings (FURB140, ISC004) without altering test scenarios.

Written for commit cf2f8b8. Summary will update on new commits.

View guided diff

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 <marlon.costa@datacosmos.com.br> — Datacosmos

Signed-off-by: Marlon Costa <marlon.costa@datacosmos.com.br>
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:
python-poetry/tomlkit#732
python-poetry/tomlkit#677
https://github.com/python-poetry/tomlkit/releases/tag/0.15.3

Traceability v1.1 — 2026-12-06
Author: Marlon Costa <marlon.costa@datacosmos.com.br> — Datacosmos

Signed-off-by: Marlon Costa <marlon.costa@datacosmos.com.br>

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

3 issues found across 7 files

Confidence score: 2/5

  • In flextcliutilitiestoml_part_04.py, this assignment goes through a proxy affected by TOMLKit 0.15.2’s #677 sibling-loss defect. Block this path until CI uses an admissible TOMLKit version or the proxy is safely consolidated.
  • In flextcliutilitiestoml_part_04.py, prune=True relies on TOMLKit’s known-unfixed #732 dotted-key deletion behavior, which can fail the reproducer or damage sibling keys. Validate an admissible TOMLKit release or add a safe workaround.
  • flextcliutilitiestoml_part_04.py imports the undocumented OutOfOrderTableProxy implementation type, which conflicts with the PR’s claim that it avoids private TOMLKit access.

You’re at about 92% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact contact@cubic.dev.

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py">

<violation number="1" location="src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py:12">
P2: Custom agent: **Flag AI Slop and Fabricated Changes**

This import relies on TOMLKit’s undocumented `OutOfOrderTableProxy` implementation type, contradicting the PR’s claim that it uses no private TOMLKit access. Resolve out-of-order views through a supported public API or revise that claim.</violation>

<violation number="2" location="src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py:88">
P1: This prune operation relies on TOMLKit's known-unfixed #732 dotted-key deletion behavior, so `prune=True` can fail the new reproducer or damage sibling keys. Validate an admissible TOMLKit release or add a safe workaround before enabling this path.</violation>

<violation number="3" location="src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py:114">
P1: This assignment still writes through an `OutOfOrderTableProxy`, whose locked TOMLKit 0.15.2 has the #677 sibling-loss defect. Block this path until CI uses an admissible TOMLKit version or the proxy is safely consolidated before mutation.</violation>
</file>
Architecture diagram
sequenceDiagram
    participant C as Infra Consumer
    participant API as flext_cli TOML Utilities
    participant T as TOMLKit Library
    participant D as TOML Document

    Note over C,D: TOML Document Synchronization Flow

    C->>API: toml_sync_document_values(document, payload, prune=)
    
    API->>API: Validate full payload via toml_document_from_mapping()
    alt Payload invalid (e.g., null value)
        API-->>C: TypeError raised before any mutation
    else Payload valid
        API->>API: Normalize current doc state via JSON_MAPPING_ADAPTER
        API->>API: Recursive _sync_document_values()
        
        loop For each payload key
            alt prune=True and key missing from payload
                API->>API: Re-read fresh parent view via _toml_parent_at()
                API->>D: Delete absent key from original document
            end
            
            alt Nested mapping value
                API->>API: Recurse with extended path
            else Scalar/array changed
                API->>API: Compare with current value via _toml_values_equal()
                API->>D: Re-read parent view from root
                
                alt String array replacement
                    API->>API: Use toml_sync_string_list() 
                else Other value change
                    API->>D: Apply new value preserving trivia
                end
            end
        end
    end

    Note over API,D: TOMLKit handles fragment refresh
    D-->>API: Mutated document (source-preserving)
    API-->>C: None (in-place update)

    Note over C,D: Verification (tests)
    C->>API: toml_dumps(document)
    API->>D: Serialize
    D-->>API: Rendered TOML string
    API-->>C: String with preserved comments/formatting
Loading

Reply with feedback, questions, or to request a fix.

View guided diff | Re-trigger cubic

if prune:
for key in current:
if key not in payload:
del FlextCliUtilitiesTomlPart04._toml_parent_at(document, path)[

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1: This prune operation relies on TOMLKit's known-unfixed #732 dotted-key deletion behavior, so prune=True can fail the new reproducer or damage sibling keys. Validate an admissible TOMLKit release or add a safe workaround before enabling this path.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py, line 88:

<comment>This prune operation relies on TOMLKit's known-unfixed #732 dotted-key deletion behavior, so `prune=True` can fail the new reproducer or damage sibling keys. Validate an admissible TOMLKit release or add a safe workaround before enabling this path.</comment>

<file context>
@@ -6,30 +6,140 @@
+        if prune:
+            for key in current:
+                if key not in payload:
+                    del FlextCliUtilitiesTomlPart04._toml_parent_at(document, path)[
+                        key
+                    ]
</file context>

tuple(item for item in value if isinstance(item, str)),
)
else:
parent[key] = value

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1: This assignment still writes through an OutOfOrderTableProxy, whose locked TOMLKit 0.15.2 has the #677 sibling-loss defect. Block this path until CI uses an admissible TOMLKit version or the proxy is safely consolidated before mutation.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py, line 114:

<comment>This assignment still writes through an `OutOfOrderTableProxy`, whose locked TOMLKit 0.15.2 has the #677 sibling-loss defect. Block this path until CI uses an admissible TOMLKit version or the proxy is safely consolidated before mutation.</comment>

<file context>
@@ -6,30 +6,140 @@
+                        tuple(item for item in value if isinstance(item, str)),
+                    )
+                else:
+                    parent[key] = value
+
+    @staticmethod
</file context>


from flext_core import u
from tomlkit.items import Array
from tomlkit.container import OutOfOrderTableProxy

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: Custom agent: Flag AI Slop and Fabricated Changes

This import relies on TOMLKit’s undocumented OutOfOrderTableProxy implementation type, contradicting the PR’s claim that it uses no private TOMLKit access. Resolve out-of-order views through a supported public API or revise that claim.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At src/flext_cli/_utilities/_toml/flextcliutilitiestoml_part_04.py, line 12:

<comment>This import relies on TOMLKit’s undocumented `OutOfOrderTableProxy` implementation type, contradicting the PR’s claim that it uses no private TOMLKit access. Resolve out-of-order views through a supported public API or revise that claim.</comment>

<file context>
@@ -6,30 +6,140 @@
 
 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
</file context>

Comment thread tests/unit/test_toml_document_sync.py Resolved
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 10edecc 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 <marlon.costa@datacosmos.com.br> — Datacosmos
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 <marlon.costa@datacosmos.com.br> — Datacosmos
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 <marlon.costa@datacosmos.com.br> — Datacosmos
Adopt the exact GitHub preview tree already executed by CI 47667870108. Preserve all seven TOML changes and the five integrated XLSX/environment files without conflict or content reconstruction.

Marlon Costa <marlon.costa@datacosmos.com.br> — Datacosmos.
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 <marlon.costa@datacosmos.com.br> — Datacosmos.
Preserve 32930eb and its ordinary merge of the current integration with
ee12578. Retain the FURB140 starmap correction and both ISC004 grouping
corrections exactly. Adopt the reviewed three-case RED regression from
dfebf96 before the upstream native reproducers.

The first-parent delta is only 56 added lines in the public test file.
All current twenty-two cases remain byte-for-byte intact; the candidate
contains twenty-five cases. The full recursive trees were read without
truncation and differ at exactly one blob, with no removed paths.

The productive Array repair awaits a real RED result from normal PR CI.
No source, lock, generated output, workflow, gate, budget or ref is
changed by this immutable merge. No local execution or rerun occurred.

Traceability v1.0 — 2026-12-06
Marlon Costa <marlon.costa@datacosmos.com.br> — Datacosmos
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 e21deee 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 <marlon.costa@datacosmos.com.br> — Datacosmos.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

All reported issues were addressed across 1 file (changes from recent commits).

You’re at about 93% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact contact@cubic.dev.

Reply with feedback, questions, or to request a fix.

View guided diff | Re-trigger cubic

marlon-costa-dc added a commit that referenced this pull request Dec 6, 2026
Exercise sort_values=True with a real same-length value change in a parsed Array. Verify sorted parsed values, native positional inline comments, standalone comments, the array-key comment, original object identity, and an unchanged second pass.

Keep the source and the three existing resize regressions unchanged. This closes the concrete coverage gap raised on PR #515 at discussion_r4817563858; the previous sorted tests covered initial creation or no-op election. The common module will be adopted by #515 without copying this test there.

This additional case requires the standard CI of the published candidate; no runtime success is claimed in advance.

Traceability v1.0 — 2026-12-06 — Marlon Costa <marlon.costa@datacosmos.com.br> — Datacosmos.
Adopt integration merge 651eef4 from PR #518 through ordinary merge ancestry. Preserve the complete document-sync API, strict JSON boundary, typed comparator with starmap, native source owners, and all concurrent changes.

Reuse tests/unit/test_toml_array_sync.py exactly as integrated, with its four public resize and sorted-update cases. Remove only the identical 56-line three-case block from test_toml_document_sync.py. The remaining document module is the reviewed 22-case version; the combined set contains 22 document cases plus four common array cases.

PR #518's qualified preview 192892a had the same tree as the real integration merge. CI 47671030224 passed setup, lint, Pyrefly, and 1469 tests, including all four array cases; Sonar and Semgrep passed. Post-merge push CI 47671773654 is still being observed. This merge candidate has not run CI, and the document-sync upstream #732/#677 blockers remain explicit.

Traceability v1.0 — 2026-12-06 — Marlon Costa <marlon.costa@datacosmos.com.br> — Datacosmos.
@sonarqubecloud

sonarqubecloud Bot commented Dec 6, 2026

Copy link
Copy Markdown

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant