Skip to content

[Data] br_rf_cnpj: correção do tabble-approve - #1798

Merged
luizavboas merged 4 commits into
mainfrom
data/br_rf_cnpj_tabble_approve
Aug 13, 2026
Merged

[Data] br_rf_cnpj: correção do tabble-approve#1798
luizavboas merged 4 commits into
mainfrom
data/br_rf_cnpj_tabble_approve

Conversation

@luizavboas

@luizavboas luizavboas commented Aug 12, 2026

Copy link
Copy Markdown
Collaborator

Descrição do PR:

Correções para o table-approve do br_rf_cnpj e ajustes de pipeline associados.

  • Motivação/Contexto: O dataset br_rf_cnpj estava referenciado incorretamente em br_bd_diretorios_brasil__empresa.sql (ainda apontava para o br_me_cnpj antigo), os modelos SQL não tinham os comentários exigidos pelo table-approve, e o parâmetro download_max_parallel divergia do valor real usado nas runs manuais.

Detalhes Técnicos:

  • Principais alterações na pipeline/scripts:
    • br_bd_diretorios_brasil__empresa.sql: migrado de br_me_cnpj para br_rf_cnpj, trocando a coluna de data de data para data_referencia.

    • Adicionado comentário -- Atualizado em 2026-08-11 em todos os models de br_rf_cnpj para o table-approve;

    • pipelines/crawler/rf_cnpj/flows.py: de DateFormat.YEAR_MD para DateFormat.YEAR_MONTH no registro de metadados (empresas/estabelecimentos/socios e diretório empresa), e date_format="%Y-%m" padronizado para o enum DateFormat.YEAR_MONTH.

    • pipelines/crawler/rf_cnpj/tasks.py: download_max_parallel default alterado de 5 para 15, alinhando ao valor já usado manualmente nas execuções.

    • Comentários # pyrefly: ignore [...] para suprimir diagnósticos indesejados do Pyrefly

Summary by CodeRabbit

  • New Features
    • Added scheduled data pipelines for CNPJ dictionaries, companies, partners, simplified businesses, and establishments.
    • Improved historical CNPJ data processing with monthly reference dates and updated snapshot selection.
  • Improvements
    • Increased the default parallel download capacity to improve processing speed.
    • Updated the Brazil business directory with the latest CNPJ reference data.
  • Maintenance
    • Added update-date documentation and cleaned up obsolete SQL comments.
    • Improved validation support without changing generated metadata or runtime behavior.

…râmetro de download_max_parallel de 5 para 15 (era o que estava sendo manualmente inserido nas runs), mudança no padrão de datas no registro de metadados, mudança na query de br_bd_diretorios_brasil__empresa para usar br_rf_cnpj ao invés de br_me_cnpj. Também correções em arquivos com erros do Pyrefly
@luizavboas luizavboas self-assigned this Aug 12, 2026
@luizavboas luizavboas added table-approve [PR] Dispara Table Approve no merge 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) labels Aug 12, 2026
@coderabbitai

coderabbitai Bot commented Aug 12, 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: 5f4bae93-2077-498f-aafa-56322816d1ae

📥 Commits

Reviewing files that changed from the base of the PR and between 00ffbce and d04354d.

📒 Files selected for processing (2)
  • models/br_tse_eleicoes/code/python/diagnostics/tier2_overrides.json
  • pipelines/crawler/rf_cnpj/flows.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • pipelines/crawler/rf_cnpj/flows.py

📝 Walkthrough

Walkthrough

The PR migrates the directory company model to RF CNPJ snapshots, updates CNPJ crawler date handling and download concurrency, adds five scheduled Prefect flows, suppresses Pyrefly diagnostics, and completes a JSON diagnostics file.

Changes

CNPJ model and pipeline

Layer / File(s) Summary
RF CNPJ snapshot integration
models/br_bd_diretorios_brasil/..., models/br_rf_cnpj/*
The directory model uses RF CNPJ tables and filters data by the latest data_referencia snapshot. RF CNPJ model comments and obsolete commented expressions were updated.
Crawler date and concurrency settings
pipelines/crawler/rf_cnpj/flows.py, pipelines/crawler/rf_cnpj/tasks.py
Historical materialization and source-update commits use YEAR_MONTH. The default download concurrency increases from 5 to 15.
Scheduled RF CNPJ flows
pipelines/datasets/flows.py
A flow factory forwards loading options to _run_rf_cnpj and defines five daily São Paulo-scheduled table flows.

Static analysis and diagnostics

Layer / File(s) Summary
Pyrefly suppressions
models/us_harvard_cbdb/code/*.py
Targeted Pyrefly suppression comments were added without changing runtime behavior or schema definitions.
Diagnostics JSON structure
models/br_tse_eleicoes/code/python/diagnostics/tier2_overrides.json
The root JSON object now has its closing delimiter.

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

Mergeability Score: ⚪ Minimal · up to d0435

The PR updates dataset references, metadata date formats, approval comments, and a download parallelism default; no actionable merge-blocking risk remains based on the supplied evidence.

Sequence Diagram(s)

sequenceDiagram
  participant PrefectDeployment
  participant DatasetFlowFactory
  participant _run_rf_cnpj
  PrefectDeployment->>DatasetFlowFactory: trigger scheduled RF CNPJ flow
  DatasetFlowFactory->>_run_rf_cnpj: forward table and loading options
  _run_rf_cnpj-->>PrefectDeployment: complete table run
Loading

Possibly related PRs

Suggested reviewers: laura-l-amaral

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title uses the required [Data] prefix and clearly identifies the br_rf_cnpj table-approve correction, despite a minor typo.
Description check ✅ Passed The description states the motivation and lists the main SQL, pipeline, date-format, concurrency, and Pyrefly changes, but omits test, risk, dependency, and reviewer sections.
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 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch data/br_rf_cnpj_tabble_approve

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.

@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: 5

🤖 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 `@models/br_bd_diretorios_brasil/br_bd_diretorios_brasil__empresa.sql`:
- Around line 161-162: Update the join condition in the empresa query to match
the `situacao_cadastral` dictionary key against the establishment’s
`situacao_cadastral` field, not `identificador_matriz_filial`. Keep the existing
dictionary alias `t` and other query logic unchanged.

In `@models/br_rf_cnpj/br_rf_cnpj__socios_legado.sql`:
- Around line 1-2: Remove the empty br_rf_cnpj__socios_legado model if it is
unused; otherwise, implement executable SQL in the model and add its
corresponding schema.yml metadata so it is a valid active dbt model.

In `@pipelines/crawler/rf_cnpj/tasks.py`:
- Line 57: Document the download_max_parallel parameter in main’s Google-style
Args section, including its purpose and default value of 15. Follow the existing
Python docstring and type-hint conventions without changing the parameter
behavior.
- Line 57: Update the non-segmented download call in the task flow to pass the
configured download_max_parallel value into download_unzip_csv, matching the
segmented-table branch and preserving the flow configuration for all downloads.

In `@pipelines/datasets/flows.py`:
- Around line 10-29: Document both `_rf_cnpj_flow` and its nested `_flow` with
Google-style docstrings describing their parameters, schedule behavior, and
return values; add the appropriate return type annotation to `_rf_cnpj_flow`.
Preserve the existing flow configuration and parameter defaults while
documenting the public factory contract.
🪄 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: 19c97714-2c10-4719-981c-be749ed44164

📥 Commits

Reviewing files that changed from the base of the PR and between 267fda2 and 00ffbce.

📒 Files selected for processing (19)
  • models/br_bd_diretorios_brasil/br_bd_diretorios_brasil__empresa.sql
  • models/br_rf_cnpj/br_rf_cnpj__dicionario.sql
  • models/br_rf_cnpj/br_rf_cnpj__empresas.sql
  • models/br_rf_cnpj/br_rf_cnpj__empresas_legado.sql
  • models/br_rf_cnpj/br_rf_cnpj__estabelecimentos.sql
  • models/br_rf_cnpj/br_rf_cnpj__estabelecimentos_legado.sql
  • models/br_rf_cnpj/br_rf_cnpj__simples.sql
  • models/br_rf_cnpj/br_rf_cnpj__socios._legado.sql
  • models/br_rf_cnpj/br_rf_cnpj__socios.sql
  • models/br_rf_cnpj/br_rf_cnpj__socios_legado.sql
  • models/us_harvard_cbdb/code/clean.py
  • models/us_harvard_cbdb/code/gen_architecture.py
  • models/us_harvard_cbdb/code/gen_dbt.py
  • models/us_harvard_cbdb/code/gen_metadata_payload.py
  • models/us_harvard_cbdb/code/schema_spec.py
  • models/us_harvard_cbdb/code/upload.py
  • pipelines/crawler/rf_cnpj/flows.py
  • pipelines/crawler/rf_cnpj/tasks.py
  • pipelines/datasets/flows.py

Comment on lines +1 to +2
-- Atualizado em 2026-08-11

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- Model contents ---'
sed -n '1,80p' models/br_rf_cnpj/br_rf_cnpj__socios_legado.sql

printf '%s\n' '--- dbt project configuration ---'
fd -HI 'dbt_project\.yml' . -x sed -n '1,240p' {}

printf '%s\n' '--- References and selectors ---'
rg -n -C 3 'br_rf_cnpj__socios_legado|socios_legado|br_rf_cnpj' \
  -g '*.sql' -g '*.yml' -g '*.yaml' -g '*.md' .

Repository: basedosdados/pipelines

Length of output: 24118


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
import re

model = Path("models/br_rf_cnpj/br_rf_cnpj__socios_legado.sql")
project = Path("dbt_project.yml")
schema = Path("models/br_rf_cnpj/schema.yml")

content = model.read_text()
executable = "\n".join(
    line for line in content.splitlines()
    if line.strip() and not line.lstrip().startswith("--")
)

print(f"model_exists={model.exists()}")
print(f"model_path={model}")
print(f"executable_sql={bool(executable.strip())}")
print(f"configured_model_path={'model-paths: [models]' in project.read_text()}")
print(
    "dataset_configured="
    + str(bool(re.search(r"(?m)^    br_rf_cnpj:\s*$", project.read_text())))
)
print(
    "schema_entry="
    + str(bool(re.search(
        r"(?m)^\s*-\s+name:\s+br_rf_cnpj__socios_legado\s*$",
        schema.read_text(),
    )))
)
PY

Repository: basedosdados/pipelines

Length of output: 328


Remove or implement this dbt model.

models/br_rf_cnpj/br_rf_cnpj__socios_legado.sql contains no executable SQL, is included in the active models path, and has no schema.yml entry. Delete it if unused. Otherwise, add the model query and metadata.

🤖 Prompt for 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.

In `@models/br_rf_cnpj/br_rf_cnpj__socios_legado.sql` around lines 1 - 2, Remove
the empty br_rf_cnpj__socios_legado model if it is unused; otherwise, implement
executable SQL in the model and add its corresponding schema.yml metadata so it
is a valid active dbt model.

download_chunk_size: int = 15 * 1024 * 1024,
download_max_retries: int = 5,
download_max_parallel: int = 5,
download_max_parallel: int = 15,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Document download_max_parallel in main.

Add this parameter to the Google-style Args section. Its default changed to 15, but callers cannot find its purpose or default in the function documentation.

As per coding guidelines: **/*.py must use Google-Style type hints and docstrings.

🤖 Prompt for 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.

In `@pipelines/crawler/rf_cnpj/tasks.py` at line 57, Document the
download_max_parallel parameter in main’s Google-style Args section, including
its purpose and default value of 15. Follow the existing Python docstring and
type-hint conventions without changing the parameter behavior.

Source: Coding guidelines


🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

Pass the configured download controls to non-segmented downloads.

The new default reaches download_unzip_csv only in the segmented-table branch. The call at Line 161 omits max_parallel, so non-segmented tables continue to use download_unzip_csv defaults instead of the flow configuration.

Proposed fix
-                asyncio.run(download_unzip_csv(url_download, input_path))
+                asyncio.run(
+                    download_unzip_csv(
+                        url_download,
+                        input_path,
+                        chunk_size=download_chunk_size,
+                        max_retries=download_max_retries,
+                        max_parallel=download_max_parallel,
+                        timeout=download_timeout,
+                    )
+                )
🤖 Prompt for 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.

In `@pipelines/crawler/rf_cnpj/tasks.py` at line 57, Update the non-segmented
download call in the task flow to pass the configured download_max_parallel
value into download_unzip_csv, matching the segmented-table branch and
preserving the flow configuration for all downloads.

@luizavboas luizavboas added check-metadata [PR] Dispara validação de metadados entre BigQuery e API de produção and removed check-metadata [PR] Dispara validação de metadados entre BigQuery e API de produção labels Aug 12, 2026
@basedosdados basedosdados deleted a comment from coderabbitai Bot Aug 12, 2026
@basedosdados basedosdados deleted a comment from coderabbitai Bot Aug 12, 2026
@mergify

mergify Bot commented Aug 12, 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

@mergify

mergify Bot commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

@luizavboas esse pull request tem conflitos 😩

@mergify mergify Bot added the conflict [PR] Conflito de merge a resolver label Aug 13, 2026
@luizavboas
luizavboas merged commit ba841a5 into main Aug 13, 2026
14 checks passed
@luizavboas
luizavboas deleted the data/br_rf_cnpj_tabble_approve branch August 13, 2026 00:06
Winzen added a commit that referenced this pull request Aug 13, 2026
O #1783 moveu commit_source_update_task pra logo após o poll, removendo
a chamada antiga do fim do flow em todos os arquivos afetados. O #1798,
mergeado depois mas cortado de uma base anterior a esse merge, ainda
tinha essa chamada antiga e só editou parâmetros dela (date_format).
O merge do git combinou as duas sem detectar a duplicação lógica —
commit_source_update_task passou a ser chamado duas vezes por run.

Sem impacto de dados (é idempotente), só uma escrita redundante.
Winzen added a commit that referenced this pull request Aug 14, 2026
…a em rf_cnpj (#1779)

A migração pro poll.py que este PR propunha originalmente não é mais
necessária: o #1783 já corrigiu poll_source_for_update via
compare_against, e br_ans_beneficiario já usa esse default corrigido.

Mantido só o que continua valendo independente do mecanismo de poll:

- br_ans_beneficiario: colunas de texto categóricas trocadas de str para
  category (reduz footprint de memória do DataFrame), del/gc.collect()
  por estado em parquet_partition (corrige OOM), source_format="parquet"
  nos upload_to_gcs (sem isso o dump_header procurava .csv e não achava
  nada), job_variables={"memory": "3Gi"} (pico medido ~1.78Gi depois da
  otimização), compare_against="coverage" explícito no poll.
- rf_cnpj: remove uma chamada duplicada de commit_source_update_task que
  sobrou de um merge entre o #1783 (moveu a chamada pra cima) e o #1798
  (mergeado depois, cortado de uma base anterior, ainda tinha a chamada
  antiga) — sem impacto de dados (idempotente), só uma escrita redundante.
- Exclui models/world_aiddata_gcdf/code do Pyrefly (mesmo padrão de
  br_tse_eleicoes/us_harvard_cbdb/us_cfpb_hmda) — destrava o CI deste PR.
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 conflict [PR] Conflito de merge a resolver deploy-flow [PR] Dispara deploy dos flows alterados no work pool basedosdados-dev (Prefect 3 staging) table-approve [PR] Dispara Table Approve no merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants