Skip to content

chore: Flow customizado com os atributos de deploy - #1771

Draft
aspeddro wants to merge 3 commits into
mainfrom
chore/custom-flow-deploy-attributes
Draft

chore: Flow customizado com os atributos de deploy#1771
aspeddro wants to merge 3 commits into
mainfrom
chore/custom-flow-deploy-attributes

Conversation

@aspeddro

@aspeddro aspeddro commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator

deploy_flows.pydeploy_schedules e job_variables do objeto flow, mas prefect.Flow não declara nenhum dos dois — o Pyrefly acusa missing-attribute, hoje silenciado com 80 # pyrefly: ignore nos flows.py.

Adiciona pipelines/utils/flow.py: subclasse de prefect.Flow que declara os dois atributos (vazios por padrão) e um decorator flow que a instancia, com as mesmas opções do prefect.flow. Migra os 60 flows.py e remove as supressões.

Verificação: pyrefly check sem diagnósticos (972 → 892 supressões) e o loader do CI descobre os mesmos 189 flows, com schedules e job_variables idênticos, antes e depois.

Exemplo de uso

from prefect.schedules import Cron

from pipelines.utils.flow import flow


@flow(name="my_flow", log_prints=True)
def my_flow() -> None: ...

# deploy_schedules tem o tipo `list[Schedule] | None`
my_flow.deploy_schedules = [
    Cron("0 16 10,11,12,13 * *", timezone="America/Sao_Paulo")
]
my_flow.job_variables = {
    "memory": "8Gi"
}  # optional; size to the clean step's peak RAM

🤖 Generated with Claude Code

`deploy_flows.py` lê `deploy_schedules` e `job_variables` do objeto flow,
mas `prefect.Flow` não declara nenhum dos dois — atribuí-los funciona em
runtime e o Pyrefly acusa `missing-attribute`, o que vinha sendo silenciado
com 80 comentários `# pyrefly: ignore` espalhados pelos flows.

Adiciona `pipelines/utils/flow.py`: uma subclasse de `prefect.Flow` que
declara os dois atributos (vazios por padrão) e um decorator `flow` que a
instancia, com os mesmos argumentos do `prefect.flow`. Como herda de
`prefect.Flow`, as checagens `isinstance` do deploy e do próprio Prefect
seguem valendo — subclassear é o que o próprio Prefect faz em
`InfrastructureBoundFlow`.

Migra os 60 `flows.py` para `from pipelines.utils.flow import flow` e remove
os `# pyrefly: ignore [missing-attribute]` que existiam só por causa disso
(972 → 892 supressões, 0 diagnósticos). Em `deploy_flows.py`, `or None`
normaliza os padrões vazios para o que o Prefect recebia antes.

Verificação: o loader do CI descobre os mesmos 189 flows, com os mesmos
nomes, schedules e job_variables, antes e depois.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This change adds a Prefect-compatible project flow wrapper with deployment attributes, updates deployment registration, documents the convention, and migrates pipeline flows from direct Prefect imports.

Changes

Custom Flow Wrapper Migration

Layer / File(s) Summary
Custom Flow contract and validation
pipelines/utils/flow.py, pipelines/utils/tests/test_flow.py
Adds DeploySchedule, the custom Flow subclass, a Prefect-compatible flow decorator, and tests for option propagation, naming, isolation, and deployment attributes.
Deployment handling and authoring conventions
.github/scripts/deploy_flows.py, .claude/rules/..., AGENTS.md, pipelines/{{cookiecutter.pipeline_name}}/flows.py
Normalizes empty deployment attributes to None and documents the required project flow decorator.
Pipeline flow adoption
pipelines/crawler/..., pipelines/datasets/*/flows.py, pipelines/utils/*/flows.py
Updates pipeline modules to use pipelines.utils.flow and removes obsolete Pyrefly suppressions. Existing schedules and flow configuration remain unchanged.

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

Sequence Diagram(s)

sequenceDiagram
  participant PipelineFlow
  participant ProjectFlow
  participant PrefectFlow
  participant DeployScript

  PipelineFlow->>ProjectFlow: apply `@flow`
  ProjectFlow->>PrefectFlow: construct compatible Flow
  PrefectFlow-->>PipelineFlow: expose deploy_schedules and job_variables
  DeployScript->>PipelineFlow: read deployment attributes
  DeployScript->>PrefectFlow: register normalized deployment values
Loading

Possibly related PRs

Suggested labels: deploy-flow, chore

Suggested reviewers: davimacielcavalcante

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 1.67% 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
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.
Title check ✅ Passed The title clearly summarizes the main change: a custom Flow with deployment attributes.
Description check ✅ Passed The description covers the motivation, technical changes, migration scope, testing, and compatibility, but omits explicit risks and dependencies.
✨ Finishing Touches 💡 3
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch chore/custom-flow-deploy-attributes
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chore/custom-flow-deploy-attributes

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

@aspeddro esse pull request tem conflitos 😩

@mergify mergify Bot added the conflict [PR] Conflito de merge a resolver label Aug 7, 2026
@aspeddro aspeddro self-assigned this Aug 7, 2026
@aspeddro
aspeddro marked this pull request as draft August 7, 2026 19:05

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

🧹 Nitpick comments (1)
pipelines/utils/flow.py (1)

87-91: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Preserve the decorated signature for @flow.

The direct decorator overload currently maps Callable[..., Any] to Flow[..., Any], so direct @flow use loses the flow’s parameter and return types. Use the existing P and R type variables for this overload and for decorator(...). Prefect 3 already models Flow and flow with ParamSpec["P"] and ReturnType["R"].

🤖 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/utils/flow.py` around lines 87 - 91, Update the direct `@flow`
overload to use the existing P and R type variables, preserving the decorated
callable’s parameter and return types in its Flow result. Apply the same P/R
typing consistently to decorator(...), while retaining the current
positional-only signature and avoiding a new type-parameter syntax.
🤖 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 `@AGENTS.md`:
- Line 67: Clarify the flow-authoring rule in AGENTS.md: exported Flow objects
must be discoverable from flows.py and their underlying function must be defined
in that file, while factory functions such as br_ibge_ipca may still define
valid nested flow functions there. Align the wording with
prefect-pipeline-conventions.md without changing the decorator requirement.

In `@pipelines/utils/flow.py`:
- Around line 81-84: Add Google-style docstrings to Flow.__init__ and decorator
in pipelines/utils/flow.py, documenting their parameters and behavior; add
Google-style docstrings to the helper and test functions in
pipelines/utils/tests/test_flow.py, and annotate every test function with ->
None. Update all three listed sites: pipelines/utils/flow.py lines 81-84 and
134-135, and pipelines/utils/tests/test_flow.py lines 8-58.

In `@pipelines/utils/tests/test_flow.py`:
- Around line 49-58: Update test_aceita_atribuicao_dos_atributos_de_deploy so it
does not mutate the shared module-level _flow_com_opcoes; create an isolated
flow instance with the same configuration inside the test, or restore
deploy_schedules and job_variables in a finally block while preserving the
existing assertions.

---

Nitpick comments:
In `@pipelines/utils/flow.py`:
- Around line 87-91: Update the direct `@flow` overload to use the existing P and
R type variables, preserving the decorated callable’s parameter and return types
in its Flow result. Apply the same P/R typing consistently to decorator(...),
while retaining the current positional-only signature and avoiding a new
type-parameter syntax.
🪄 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: 19f55518-0f33-4935-9227-2f90666f6c2a

📥 Commits

Reviewing files that changed from the base of the PR and between 9e2e491 and 1c4f7b4.

📒 Files selected for processing (65)
  • .claude/rules/prefect-pipeline-conventions.md
  • .github/scripts/deploy_flows.py
  • AGENTS.md
  • pipelines/crawler/ibge_inflacao/flows.py
  • pipelines/datasets/au_abs_cpi/flows.py
  • pipelines/datasets/au_abs_labour_force/flows.py
  • pipelines/datasets/br_anatel_banda_larga_fixa/flows.py
  • pipelines/datasets/br_anatel_telefonia_movel/flows.py
  • pipelines/datasets/br_anp_precos_combustiveis/flows.py
  • pipelines/datasets/br_ans_beneficiario/flows.py
  • pipelines/datasets/br_bcb_agencia/flows.py
  • pipelines/datasets/br_bcb_estban/flows.py
  • pipelines/datasets/br_bcb_sicor/flows.py
  • pipelines/datasets/br_bcb_taxa_cambio/flows.py
  • pipelines/datasets/br_bcb_taxa_selic/flows.py
  • pipelines/datasets/br_bd_indicadores/flows.py
  • pipelines/datasets/br_bd_siga_o_dinheiro/flows.py
  • pipelines/datasets/br_bndes_operacoes_contratadas/flows.py
  • pipelines/datasets/br_camara_dados_abertos/flows.py
  • pipelines/datasets/br_cgu_beneficios_cidadao/flows.py
  • pipelines/datasets/br_cgu_cartao_pagamento/flows.py
  • pipelines/datasets/br_cgu_emendas_parlamentares/flows.py
  • pipelines/datasets/br_cgu_licitacao_contrato/flows.py
  • pipelines/datasets/br_cgu_pessoal_executivo_federal/flows.py
  • pipelines/datasets/br_cgu_servidores_executivo_federal/flows.py
  • pipelines/datasets/br_cnj_improbidade_administrativa/flows.py
  • pipelines/datasets/br_cvm_administradores_carteira/flows.py
  • pipelines/datasets/br_cvm_fi/flows.py
  • pipelines/datasets/br_cvm_oferta_publica_distribuicao/flows.py
  • pipelines/datasets/br_denatran_frota/flows.py
  • pipelines/datasets/br_fgv_igp/flows.py
  • pipelines/datasets/br_ibge_inpc/flows.py
  • pipelines/datasets/br_ibge_ipca/flows.py
  • pipelines/datasets/br_ibge_ipca15/flows.py
  • pipelines/datasets/br_ibge_pnadc/flows.py
  • pipelines/datasets/br_inmet_bdmep/flows.py
  • pipelines/datasets/br_me_caged/flows.py
  • pipelines/datasets/br_me_cnpj/flows.py
  • pipelines/datasets/br_me_comex_stat/flows.py
  • pipelines/datasets/br_me_rais/flows.py
  • pipelines/datasets/br_me_siconfi/flows.py
  • pipelines/datasets/br_mp_pep/flows.py
  • pipelines/datasets/br_ms_cnes/flows.py
  • pipelines/datasets/br_ms_sia/flows.py
  • pipelines/datasets/br_ms_sih/flows.py
  • pipelines/datasets/br_ms_sinan/flows.py
  • pipelines/datasets/br_poder360_pesquisas/flows.py
  • pipelines/datasets/br_rf_cafir/flows.py
  • pipelines/datasets/br_rf_cno/flows.py
  • pipelines/datasets/br_rj_isp_estatisticas_seguranca/flows.py
  • pipelines/datasets/br_senado_dados_abertos/flows.py
  • pipelines/datasets/br_sfb_sicar/flows.py
  • pipelines/datasets/br_stf_corte_aberta/flows.py
  • pipelines/datasets/br_tse_eleicoes/flows.py
  • pipelines/datasets/fundacao_lemann/flows.py
  • pipelines/datasets/test_dataset/flows.py
  • pipelines/datasets/us_bls_cpi/flows.py
  • pipelines/datasets/us_bls_qcew/flows.py
  • pipelines/datasets/world_cricsheet/flows.py
  • pipelines/utils/execute_dbt_model/flows.py
  • pipelines/utils/flow.py
  • pipelines/utils/materialize_prod/flows.py
  • pipelines/utils/metadata/flows.py
  • pipelines/utils/tests/test_flow.py
  • pipelines/{{cookiecutter.pipeline_name}}/flows.py

Comment thread AGENTS.md
### File conventions

- `flows.py`: Define flows with `@flow`. Flows **must be defined at module level in this file** — `deploy_flows.py` only collects `Flow` objects whose function is defined there (an `obj.fn.__code__.co_filename` check).
- `flows.py`: Define flows with `@flow` from **`pipelines.utils.flow`**, never `prefect.flow` — the repo's decorator returns a `prefect.Flow` subclass that declares the deploy attributes (`deploy_schedules`, `job_variables`), which the Prefect class does not, so setting them on a plain `prefect.Flow` is a Pyrefly `missing-attribute` error. Flows **must be defined at module level in this file** — `deploy_flows.py` only collects `Flow` objects whose function is defined there (an `obj.fn.__code__.co_filename` check).

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

Clarify the module-level flow rule.

Line 67 says that flows must be defined at module level. .claude/rules/prefect-pipeline-conventions.md permits a factory such as br_ibge_ipca when the inner function is defined in the same file. State that the exported Flow object must be discoverable from flows.py, while nested factory functions remain valid.

The repository guides should not give conflicting authoring rules.

🤖 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 `@AGENTS.md` at line 67, Clarify the flow-authoring rule in AGENTS.md: exported
Flow objects must be discoverable from flows.py and their underlying function
must be defined in that file, while factory functions such as br_ibge_ipca may
still define valid nested flow functions there. Align the wording with
prefect-pipeline-conventions.md without changing the decorator requirement.

Comment thread pipelines/utils/flow.py Outdated
Comment on lines +81 to +84
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.deploy_schedules = []
self.job_variables = {}

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 | 🟠 Major | ⚡ Quick win

Add the required function documentation and annotations.

  • pipelines/utils/flow.py#L81-L84: Add a Google-style docstring for Flow.__init__.
  • pipelines/utils/flow.py#L134-L135: Add a Google-style docstring for decorator.
  • pipelines/utils/tests/test_flow.py#L8-L58: Add Google-style docstrings to the helper and test functions. Add -> None to each test function.

As per coding guidelines, “add Google-Style type hints and docstrings to Python functions.”

📍 Affects 2 files
  • pipelines/utils/flow.py#L81-L84 (this comment)
  • pipelines/utils/flow.py#L134-L135
  • pipelines/utils/tests/test_flow.py#L8-L58
🤖 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/utils/flow.py` around lines 81 - 84, Add Google-style docstrings to
Flow.__init__ and decorator in pipelines/utils/flow.py, documenting their
parameters and behavior; add Google-style docstrings to the helper and test
functions in pipelines/utils/tests/test_flow.py, and annotate every test
function with -> None. Update all three listed sites: pipelines/utils/flow.py
lines 81-84 and 134-135, and pipelines/utils/tests/test_flow.py lines 8-58.

Source: Coding guidelines

Comment on lines +49 to +58
def test_aceita_atribuicao_dos_atributos_de_deploy():
schedules: list[DeploySchedule] = [
{"cron": "0 16 10 * *", "timezone": "America/Sao_Paulo"}
]

_flow_com_opcoes.deploy_schedules = schedules
_flow_com_opcoes.job_variables = {"memory": "8Gi"}

assert _flow_com_opcoes.deploy_schedules == schedules
assert _flow_com_opcoes.job_variables == {"memory": "8Gi"}

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

Avoid mutation of a module-level test flow.

This test changes _flow_com_opcoes without restoring its defaults. Test order changes can then make tests that expect empty attributes fail. Create a flow inside this test, or restore both attributes in finally.

🤖 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/utils/tests/test_flow.py` around lines 49 - 58, Update
test_aceita_atribuicao_dos_atributos_de_deploy so it does not mutate the shared
module-level _flow_com_opcoes; create an isolated flow instance with the same
configuration inside the test, or restore deploy_schedules and job_variables in
a finally block while preserving the existing assertions.

aspeddro and others added 2 commits August 7, 2026 21:43
Troca os dicts `{"cron": ..., "timezone": ...}` pelo `Cron` do
`prefect.schedules`, que já recebe o `timezone` — 54 agendamentos em 50
`flows.py`. `deploy_schedules` passa a ser `list[Schedule]` (o que o `Cron`
devolve) e `deploy_flows.py` não precisa mais converter dict → Cron.

Os agendamentos agora são validados na importação do módulo, e não só no
deploy.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

conflict [PR] Conflito de merge a resolver

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant