Skip to content

[Bugfix] br_me_comex_stat - #1766

Merged
DaviMacielCavalcante merged 4 commits into
mainfrom
fix/br_me_comex_stat_poll_migration
Aug 7, 2026
Merged

DaviMacielCavalcante merged 4 commits into
mainfrom
fix/br_me_comex_stat_poll_migration

Conversation

@DaviMacielCavalcante

@DaviMacielCavalcante DaviMacielCavalcante commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator

Descrição do PR

O conjunto do Comex Stat estava desatualizado: NCM parado em 2026-06 e município em
2026-05, com a fonte já publicando julho. As runs terminavam COMPLETED todo dia,
registrando Poll, e encerravam no gate com Não há novas atualizações na fonte original.

Motivação/Contexto: o gate do poll_source_for_update_task compara
source_max_date (data de cobertura, 2026-07-01) com o Table.Update.latest, que é
relógio — o register_table_materialization_task grava ali o bq.last_modified(). Como
o dado do mês M sai no começo de M+1, a cobertura fica sempre cerca de um mês atrás do
relógio, e o gate só passa quando faz mais de um mês desde a última materialização. Na
prática o conjunto ingeria mês sim, mês não.

Estado que motivou a correção:

Tabela Table.Update (relógio) Cobertura publicada
ncm_exportacao 2026-07-03 …2026-06
ncm_importacao 2026-07-03 …2026-06
municipio_exportacao 2026-06-26 …2026-05
municipio_importacao 2026-06-26 …2026-05

Com julho na fonte, a conta do NCM ficava 2026-07-01 > 2026-07-03 — falso, travado
até setembro. As tabelas de município já tinham perdido junho pelo mesmo motivo.

Detalhes Técnicos

Principais alterações na pipeline/scripts: migração das quatro tabelas para o modelo
de reconciliação de cobertura (pipelines/utils/metadata/poll.py), o mesmo do
_run_cnes:

  • poll_source_for_update_taskregister_source_coverage_task +
    check_source_is_ahead_of_table_task
  • register_table_materialization_task + commit_source_update_task
    sync_table_coverage_task

Agora os dois lados do gate são data de cobertura. O register_source_coverage_task
fica fora do if not force_run, então o Poll é gravado em toda run.

Sem loop de backfill (como o br_me_caged) e sem guarda de fonte vazia (como o CNES):
a fonte publica o CSV do ano inteiro, então qualquer run já refaz janeiro–mês corrente e
recupera mês perdido. to_partitions grava data.csv com nome fixo por partição, então
re-subir o ano sobrescreve os mesmos objetos e o append não duplica.

Também adiciona pipelines/datasets/br_me_comex_stat/README.md com o contexto da base:
as particularidades da fonte, a validação contra os totais oficiais do MDIC, o
RawDataSource único compartilhado pelas quatro tabelas, e a armadilha do seed.

Mudanças nos dados e no schema: nenhuma. Os modelos dbt, o schema e as partições
ficam iguais. A cobertura BD Pro continua PartBdpro com free_lag de 6 meses.

Impacto no desempenho: o conjunto passa a materializar todo mês em vez de mês sim,
mês não. Cada run reprocessa o ano corrente, que é o comportamento que já existia.

Teste e Validações

Riscos e Mitigações

Riscos conhecidos:

  • O seed do Table.Update é pré-requisito do gate novo: sem ele, o modelo novo herda o
    congelamento do antigo (foi o que segurou o CNES de 2026-06-17 a 2026-08-03). Já
    aplicado, mas qualquer run do código antigo o regrava como relógio — por isso os
    deployments estão pausados até este PR entrar. Conferir antes de despausar:
    client.get_table_update_latest(...) tem que voltar dia 1º, nunca timestamp com hora.
  • O RawDataSource é um só para as quatro tabelas, então o RawDataSource.Update é um
    ponteiro compartilhado. Não afeta o gate, que compara contra o Table.Update de cada
    tabela.

Planos de rollback: reverter o commit devolve o gate antigo. O Table.Update volta a
ser relógio na primeira materialização, sem intervenção.

Dependencias

  • Nenhuma dependencia adicional

Summary by CodeRabbit

  • New Features

    • Improved dataset ingestion by reconciling source coverage with table coverage.
    • Added checks to identify when source data is ahead of available table data.
    • Synchronized table coverage during pipeline execution.
  • Documentation

    • Added comprehensive Portuguese documentation covering data sources, partitions, validation, schedules, execution behavior, and local verification.

@DaviMacielCavalcante DaviMacielCavalcante added the deploy-flow [PR] Dispara deploy dos flows alterados no work pool basedosdados-dev (Prefect 3 staging) label Aug 6, 2026
@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 0bace534-016d-467c-b326-b863278c3dbf

📥 Commits

Reviewing files that changed from the base of the PR and between 65de653 and 36e69be.

📒 Files selected for processing (1)
  • pipelines/datasets/br_me_comex_stat/README.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • pipelines/datasets/br_me_comex_stat/README.md

📝 Walkthrough

Walkthrough

The Comex Stat flow now tracks source and table coverage instead of source updates and materialization. The README documents ingestion, validation, migration, scheduling, and execution behavior.

Changes

Comex Stat coverage reconciliation

Layer / File(s) Summary
Coverage-based flow control
pipelines/datasets/br_me_comex_stat/flows.py
The flow registers source coverage, runs when the source is ahead or force_run is enabled, synchronizes table coverage after metadata updates, and removes the final source-update commit.
Ingestion and validation documentation
pipelines/datasets/br_me_comex_stat/README.md
The README documents the source tables, annual-file processing, date parsing, validation, and shared source metadata.
Migration and execution documentation
pipelines/datasets/br_me_comex_stat/README.md
The README documents coverage reconciliation, Table.Update seeding, execution defaults, schedules, and local import behavior.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant ComexStatFlow
  participant SourceCoverageRegistration
  participant TableCoverageSynchronization
  ComexStatFlow->>SourceCoverageRegistration: register latest source coverage
  SourceCoverageRegistration-->>ComexStatFlow: return source coverage
  ComexStatFlow->>ComexStatFlow: continue when source is ahead or force_run is enabled
  ComexStatFlow->>TableCoverageSynchronization: synchronize table coverage after metadata updates
Loading

Possibly related PRs

Suggested reviewers: winzen

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed O título identifica claramente uma correção no pipeline br_me_comex_stat e segue o padrão de palavra-chave exigido.
Description check ✅ Passed A descrição cobre motivação, alterações técnicas, impacto, validações, riscos, rollback e dependências, conforme o template.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/br_me_comex_stat_poll_migration

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@mergify

mergify Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

@DaviMacielCavalcante esse pull request tem conflitos 😩

@mergify mergify Bot added the conflict [PR] Conflito de merge a resolver label Aug 7, 2026
@DaviMacielCavalcante DaviMacielCavalcante removed the conflict [PR] Conflito de merge a resolver label Aug 7, 2026
@mergify mergify Bot added the conflict [PR] Conflito de merge a resolver label Aug 7, 2026
@DaviMacielCavalcante DaviMacielCavalcante removed the conflict [PR] Conflito de merge a resolver label Aug 7, 2026
@mergify mergify Bot added the conflict [PR] Conflito de merge a resolver label Aug 7, 2026
@DaviMacielCavalcante
DaviMacielCavalcante marked this pull request as ready for review August 7, 2026 14:51
@DaviMacielCavalcante DaviMacielCavalcante self-assigned this Aug 7, 2026
@DaviMacielCavalcante DaviMacielCavalcante added test-dev-model [PR] Roda testes DBT nos models modificados em basedosdados-dev table-approve [PR] Dispara Table Approve no merge check-metadata [PR] Dispara validação de metadados entre BigQuery e API de produção and removed conflict [PR] Conflito de merge a resolver labels Aug 7, 2026
@DaviMacielCavalcante DaviMacielCavalcante linked an issue Aug 7, 2026 that may be closed by this pull request

@coderabbitai coderabbitai 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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pipelines/datasets/br_me_comex_stat/README.md`:
- Around line 169-188: Update the migration examples in the README to use
properly paired, consistent code fences, ensuring subsequent headings render as
Markdown rather than code. In the `parameters` example, use valid Python boolean
syntax with `True` instead of `true`.
- Around line 229-233: Align the runtime documentation with the supported Python
version declared in pyproject.toml. Update the README’s venv and execution-image
guidance consistently: either remove the Python 3.11-only StrEnum dependency
from pipelines/utils/metadata/domain.py to preserve Python 3.10 support, or
document Python 3.12 as the required runtime and revise the supported-version
declaration accordingly.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: bba7da02-ebd4-4961-a0d0-f2624cd9dea0

📥 Commits

Reviewing files that changed from the base of the PR and between 4657c54 and 65de653.

📒 Files selected for processing (2)
  • pipelines/datasets/br_me_comex_stat/README.md
  • pipelines/datasets/br_me_comex_stat/flows.py

Comment thread pipelines/datasets/br_me_comex_stat/README.md
Comment thread pipelines/datasets/br_me_comex_stat/README.md
@mergify

mergify Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

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

Labels

check-metadata [PR] Dispara validação de metadados entre BigQuery e API de produção deploy-flow [PR] Dispara deploy dos flows alterados no work pool basedosdados-dev (Prefect 3 staging) table-approve [PR] Dispara Table Approve no merge test-dev-model [PR] Roda testes DBT nos models modificados em basedosdados-dev

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[databug] br_me_comex_stat

2 participants