<#1298 build: type-check all examples with mypy an...
# flyte-github
a
#1298 build: type-check all examples with mypy and ty; add ty make target + pre-commit hook Pull request opened by cosmicBboy Why are the changes needed?
make mypy
only checked
src/
plus two hand-picked example files (
examples/basics/hello.py
,
hello_v2.py
), so type regressions in the other ~500 example scripts — the SDK's primary user-facing documentation — went unnoticed, and several SDK typing gaps forced users into unannotatable code. This PR makes the entire tree (
src/
+
examples/
) pass both mypy and ty, and enforces it on every commit. Baseline before this change: 548 mypy errors and 1059 ty diagnostics across the tree. What changes were proposed in this pull request? Tooling •
make mypy
now checks `src/ examples/`; new
make ty
target checks the same scope; both run as prek pre-commit hooks. • `[tool.mypy]`:
explicit_package_bases
+
mypy_path = ["src"]
so example scripts with recurring filenames (
main.py
,
app.py
, ...) resolve to unique module names in one invocation. • `[tool.ty.rules]`:
unresolved-import
ignored (same policy as mypy's
ignore_missing_imports
— examples import optional heavy deps like torch/sklearn); unused-ignore-comment rules disabled in both directions since the tree is checked by two checkers; fixed two stale rule names (
possibly-unbound-*
→
possibly-missing-*
) that ty had renamed and were silently not applying. • ty added to the dev dependency group, with an
exclude-newer-package
override (ty releases outpace the repo's 5-day recency cutoff). SDK — typing-only, no runtime or user-facing API changes • `File`/`Dir` generic
T
now defaults to
Any
(PEP 696):
File(path=...)
and
File.new_remote()
type-check without an annotation on the assignment target (~150 errors). •
File.open()
gains mode-based overloads (
"rb"
→ readable handle,
"wb"
→ writable). The overloads live on a plain method returning
AbstractAsyncContextManager
delegating to the
@asynccontextmanager
generator, because neither mypy nor ty matches overloads through that decorator (~170 errors across both checkers). • `AppEnvironment.on_startup`/`server`/`on_shutdown` accept sync or async callables — matching their documented behavior and the
iscoroutinefunction
dispatch in
_serve.py
— and preserve the decorated function's type. •
AsyncConnector
is now
Generic[M: ResourceMeta]
with a default, so subclasses can parameterize (
AsyncConnector[MyJobMetadata]
) and narrow `create`/`get`/`delete`/`get_logs` honestly.
metadata_type
corrected to
type[M]
(every real connector assigns a class; internal code calls
.decode
on it), and
get_logs
is typed to permit the async-generator form the connector server already documents and handles. Unparameterized subclasses type-check exactly as before. • ~280 further ty diagnostics fixed across 84 src files (casts, narrowed annotations, TYPE_CHECKING imports). 28 justified
# ty: ignore[rule]
comments remain, each marking a documented checker limitation. Examples (~470 fixes across ~180 files) • Recurring honest patterns:
flyte.ctx()
None-guards, coroutine-list annotations,
BaseException
filtering after
gather(return_exceptions=True)
. •
Runner.run
is now honestly typed
-> Run
in every mode: hybrid mode (test-only) wraps its natively computed outputs in the same inline Run wrapper local mode uses, instead of returning raw task outputs. This removed the
R | Run
union that would otherwise have required
assert isinstance(run, Run)
narrowing at ~75 example call sites. • Renamed
examples/plugins/polars
→ `polars_examples`: the directory shadowed the real polars package in ty's module resolution, producing 72 false diagnostics. • Only 4
# ty: ignore
comments across all examples. Real bugs the checkers caught (fixed here) • Missing
@syncify
on
CodeModeAgent.run
—
agent.run.aio(...)
call sites would
AttributeError
at runtime. •
typing.NotRequired
import that crashes on Python 3.10 (project floor). • A stray
flyte.g
statement (AttributeError when run). • A custom image builder example returning
str
where the
ImageBuilder
protocol requires
ImageBuild
. • Shadowed FastAPI
app
variables (serve handles overwriting the ASGI app), deprecated
datetime.utcnow()
, and a
gpu_memory_utilization
kwarg silently dropped by pydantic. Known follow-ups (deliberately not fixed — behavior-change constraint) •
src/flyte/cli/_tui/_remote/_screens.py:767-772
reads nonexistent proto fields (`pb2.id`/`pb2.task_template`), so that TUI panel always hits its error fallback; likely intended fields noted in a comment. •
src/flyte/storage/_remote_fs.py:148
— dead code path awaits a syncify sync wrapper. • Protocol/stub drift in
remote/_client/_protocols.py
worked around with ~7 casts. API behavior changes (intentional) •
flyte.run(...)
/
with_runcontext(...).run(...)
now returns a
Run
in every mode. Hybrid mode (test-only) previously returned the task's raw outputs; it now wraps them in the same inline Run wrapper local mode uses (
wait()
no-op,
outputs()
serves the values). •
flyte.ctx()
now always returns a
TaskContext
. Outside a task it returns a falsy null context (
NULL_TASK_CONTEXT
) whose fields are all
None
, instead of
None
itself — so task code reads
flyte.ctx().action
without None-guards. Detect task execution with truthiness (
if flyte.ctx():
). Compat note: code using identity checks (
flyte.ctx() is None
) must switch to truthiness; all in-repo call sites (src, plugins, examples, tests) were converted. One such site — the log-record factory in
flyte/_logging.py
— initially slipped through and hung any await on a
DynamicBatcher
future whose
process_fn
logged an error; fixed and covered by the previously-hanging
test_error_propagation
. How was this patch tested? •
make mypy
— clean (810 files) •
make ty
— clean •
make unit_test
— 4268 passed, 9 skipped • bigquery / databricks / snowflake plugin suites (subclass
AsyncConnector
) — 91 passed •
File.open
read/write round-trip verified at runtime; `ruff format`/`check` clean • All pre-commit hooks (fmt, mypy, ty, uvlock) passed on commit 🤖 Generated with Claude Code flyteorg/flyte-sdk