Skip to content

Conversation

@HyeockJinKim
Copy link
Collaborator

Complete migration to ANN001 (missing-type-function-argument) linter rule by adding type annotations to all remaining function arguments across the entire codebase.

This is the final phase (Phase 5) completing the ANN001 migration work:

  • Phase 1-4: Previously completed (585 violations)
  • Phase 5: client, web, testutils, appproxy, manager (remaining 461 violations)

Changes Summary

Client Module (~300 violations fixed)

  • client/cli: All CLI commands with Click parameters, API sessions
  • client/func: VFolder, session, base API functions
  • client core: Session, utils, compat, output formatters, request handlers
  • Added proper await keywords for all async calls (fixed unused-coroutine errors)

Web & TestUtils (~26 violations fixed)

  • web/logging: BraceStyleAdapter logging parameters
  • web/proxy: Middleware handler type annotations
  • web/stats: Handler tracking middleware
  • testutils/mock: Mock function parameters, async context managers

AppProxy Module (~70 violations fixed)

  • coordinator/models: SQLAlchemy TypeDecorator methods, model helpers
  • common/utils: Handler attributes, decorators, utilities
  • worker/proxy: Frontend/backend proxy parameters

Manager Module (~100 violations fixed)

  • models: SQLAlchemy model methods, TypeDecorator, Row init methods
  • repositories: User, session, scheduler, vfolder repository methods
  • api/gql_legacy: Remaining GraphQL resolvers and mutations
  • registry: Session creation, occupancy calculations

Type Error Fixes Fixed all mypy type errors introduced by annotations:

  • minilang query filter/ordering: Table | Join | type unions
  • SQLAlchemy compatibility: Proper casts for InstrumentedAttribute
  • GraphQL types: AsyncPaginatedConnectionField, connection_type
  • UUID/string conversions in global IDs
  • Mapping to dict conversions where needed
  • Row null checks in repositories

Type Annotation Patterns Used

  • Click parameters: str | None, bool, int, tuple[str, ...]
  • GraphQL resolvers: root: Any, info: graphene.ResolveInfo
  • Middleware: handler: Callable[[web.Request], Awaitable[web.StreamResponse]]
  • SQLAlchemy: Dialect, TypeDecorator, ColumnElement | InstrumentedAttribute
  • Async sessions: AsyncSession, AsyncConnection
  • Domain types: AccessKey, SessionId, AgentId

Verification ✅ All lint checks pass: pants lint :: ✅ All type checks pass: pants check :: ✅ Zero ANN001 violations remaining

Total violations fixed: 1046+ across all phases

Co-Authored-By: Claude Sonnet 4.5 noreply@anthropic.com

resolves #NNN (BA-MMM)

Checklist: (if applicable)

  • Milestone metadata specifying the target backport version
  • Mention to the original issue
  • Installer updates including:
    • Fixtures for db schema changes
    • New mandatory config options
  • Update of end-to-end CLI integration tests in ai.backend.test
  • API server-client counterparts (e.g., manager API -> client SDK)
  • Test case(s) to:
    • Demonstrate the difference of before/after
    • Demonstrate the flow of abstract/conceptual models with a concrete implementation
  • Documentation
    • Contents in the docs directory
    • docstrings in public interfaces and type annotations

HyeockJinKim and others added 6 commits January 28, 2026 05:26
Enable flake8-annotations rules to enforce return type annotations:
- ANN201: missing-return-type-undocumented-public-function
- ANN202: missing-return-type-private-function
- ANN205: missing-return-type-static-method
- ANN206: missing-return-type-class-method

All existing code already complies with these rules.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Add missing function argument type annotations to fix ANN001 violations:

- helpers (2): package installation functions
- install (3): context, docker, widgets functions
- logging (9): formatter and handler parameters
- account_manager (15): API utils and base model methods
- accelerator (17): device plugins across CUDA, IPU, ROCm, TPU, etc
- common (45): CLI, Redis, Docker, validators, and utility functions

Key patterns fixed:
- Click CLI parameters: click.Parameter, click.Context
- Exception handlers: type[BaseException] | None, BaseException | None
- Comparison methods: Any type for 'other' parameter
- Decorator functions: Callable types
- SQLAlchemy methods: Dialect types

Also fixed mypy type checking errors:
- FstabEntry unpacking in common/utils.py
- Iterator type annotations in common/etcd.py
- TypeEngine/TypeDecorator casts in account_manager/models/base.py

Phase 1 total: 91 violations fixed

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Add missing function argument type annotations to fix ANN001 violations:

- kernel/app (1): service_info parameter
- kernel/vendor (9): AWS Polly and H2O service integration functions
- kernel/__root__ (42): base runner, intrinsic services, utilities, logging
- kernel/python (69): drawing library (canvas, color, turtle, encoding)

Key patterns fixed:
- Service info parameters: Mapping[str, Any]
- Drawing coordinates: float | int
- Color parameters: Color type
- Queue types: Queue[T] with appropriate type parameters
- Stream parameters: asyncio.StreamReader, zmq.Socket
- Hook functions: Callable with sync/async union types

Also fixed mypy type checking error:
- sitecustomize.py: Changed input prompt parameter from str to object to match builtins.input signature

Phase 2 total: 121 violations fixed

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Add missing function argument type annotations to fix ANN001 violations:

- agent/docker (26): kernel, files, intrinsic, resources
- agent/__root__ (37): agent, kernel, resources, server, filesystem
- agent/dummy (39): agent, kernel, intrinsic
- agent/kubernetes (37): agent, kernel, files, intrinsic, kube objects, resources

Key patterns fixed:
- Kernel/Session identifiers: KernelId, SessionId types
- Device allocation: Mapping[SlotName, Mapping[DeviceId, Decimal]]
- Service ports and options: Mapping[str, Any], list[ServicePort]
- Container resources: resource_opts, preopen_ports parameters
- File system operations: Path | str types
- Kubernetes objects: container_port, service_type, PV/PVC parameters

Phase 3 total: 139 violations fixed

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
…e 4/4)

Complete Phase 4 of ANN001 linter rule migration by adding type annotations
to all function arguments in the manager package (234 violations fixed).

Changes include:
- manager/config: ManagerStatus type annotation
- manager/data: ColumnElement type annotations
- manager/api: GraphQL middleware, utilities, and endpoint handlers
- manager/cli: All Click CLI command parameters
- manager/api/gql_legacy: GraphQL resolvers, mutations, and utilities

Type annotation patterns applied:
- GraphQL resolvers: root: Any, info: graphene.ResolveInfo
- Mutations: **kwargs: Any with properly typed specific parameters
- Click CLI: param: click.Parameter | None, ctx: click.Context | None
- Utility functions: Appropriate types based on context

Mypy fixes:
- gql_relay.py: Fixed type checking for connection_type parameter
- routing.py: Handle int | None return type conversion
- endpoint.py: Pass required GraphQueryContext, fix return types
- artifact db_source: Cast InstrumentedAttribute to ColumnElement
- session.py: Convert Mapping to dict for type compatibility

This completes all 4 phases of the ANN001 migration:
- Phase 1: helpers, install, logging, account_manager, accelerator, common (91 violations)
- Phase 2: kernel (121 violations)
- Phase 3: agent (139 violations)
- Phase 4: manager (234 violations)

Total: 585 violations fixed across all modules.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
…n arguments

Complete migration to ANN001 (missing-type-function-argument) linter rule by adding
type annotations to all remaining function arguments across the entire codebase.

This is the final phase (Phase 5) completing the ANN001 migration work:
- Phase 1-4: Previously completed (585 violations)
- Phase 5: client, web, testutils, appproxy, manager (remaining 461 violations)

## Changes Summary

### Client Module (~300 violations fixed)
- **client/cli**: All CLI commands with Click parameters, API sessions
- **client/func**: VFolder, session, base API functions
- **client core**: Session, utils, compat, output formatters, request handlers
- Added proper await keywords for all async calls (fixed unused-coroutine errors)

### Web & TestUtils (~26 violations fixed)
- **web/logging**: BraceStyleAdapter logging parameters
- **web/proxy**: Middleware handler type annotations
- **web/stats**: Handler tracking middleware
- **testutils/mock**: Mock function parameters, async context managers

### AppProxy Module (~70 violations fixed)
- **coordinator/models**: SQLAlchemy TypeDecorator methods, model helpers
- **common/utils**: Handler attributes, decorators, utilities
- **worker/proxy**: Frontend/backend proxy parameters

### Manager Module (~100 violations fixed)
- **models**: SQLAlchemy model methods, TypeDecorator, Row __init__ methods
- **repositories**: User, session, scheduler, vfolder repository methods
- **api/gql_legacy**: Remaining GraphQL resolvers and mutations
- **registry**: Session creation, occupancy calculations

### Type Error Fixes
Fixed all mypy type errors introduced by annotations:
- minilang query filter/ordering: Table | Join | type unions
- SQLAlchemy compatibility: Proper casts for InstrumentedAttribute
- GraphQL types: AsyncPaginatedConnectionField, connection_type
- UUID/string conversions in global IDs
- Mapping to dict conversions where needed
- Row null checks in repositories

### Type Annotation Patterns Used
- Click parameters: `str | None`, `bool`, `int`, `tuple[str, ...]`
- GraphQL resolvers: `root: Any, info: graphene.ResolveInfo`
- Middleware: `handler: Callable[[web.Request], Awaitable[web.StreamResponse]]`
- SQLAlchemy: `Dialect`, `TypeDecorator`, `ColumnElement | InstrumentedAttribute`
- Async sessions: `AsyncSession`, `AsyncConnection`
- Domain types: `AccessKey`, `SessionId`, `AgentId`

## Verification
✅ All lint checks pass: `pants lint ::`
✅ All type checks pass: `pants check ::`
✅ Zero ANN001 violations remaining

Total violations fixed: 1046+ across all phases

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings January 28, 2026 01:14
@github-actions github-actions bot added size:L 100~500 LoC comp:manager Related to Manager component comp:agent Related to Agent component comp:client Related to Client component comp:common Related to Common component comp:cli Related to CLI component comp:webserver Related to Web Server component comp:storage-proxy Related to Storage proxy component comp:app-proxy Related to App Proxy component labels Jan 28, 2026
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR completes Phase 5 of the ANN001 linter rule migration by adding type annotations to function arguments across the entire codebase. The PR fixes 461 violations in this phase (1046+ total across all phases) and removes the ANN001 rule from the ruff ignore list.

Changes:

  • Added type annotations to function arguments in client, web, testutils, appproxy, manager, agent, storage, kernel, and accelerator modules
  • Fixed mypy type errors introduced by the new annotations using appropriate casts, type guards, and type ignore comments
  • Removed test files that appear to be empty or no longer needed

Reviewed changes

Copilot reviewed 203 out of 210 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
pyproject.toml Removed ANN001 from ruff ignore list
tools/build-macros.py Added type annotations to build macro functions
tests/unit/manager/notification/*/BUILD Deleted empty test BUILD files
tests/unit/manager/models/gql_models/* Deleted test file and BUILD
src/ai/backend/web/* Added type annotations to middleware and logging handlers
src/ai/backend/testutils/* Added type annotations to mock utilities
src/ai/backend/storage/volumes/* Added type annotations to storage client methods
src/ai/backend/storage/api/client.py Added type annotations to iterator helpers
src/ai/backend/runner/* Added type annotations to hash phrase utilities
src/ai/backend/manager/* Added extensive type annotations to models, repositories, API handlers, CLI commands
src/ai/backend/appproxy/* Added type annotations to coordinator and worker proxy code
src/ai/backend/agent/* Added type annotations to agent, resources, and platform-specific code
src/ai/backend/kernel/* Added type annotations to kernel execution and service code
src/ai/backend/client/* Added type annotations to CLI commands and API functions
src/ai/backend/common/* Added type annotations to utility functions
src/ai/backend/logging/* Added type annotations to logging formatters and handlers
src/ai/backend/install/* Added type annotations to installer utilities
src/ai/backend/accelerator/* Added type annotations to accelerator plugin code
Comments suppressed due to low confidence (1)

src/ai/backend/common/docker.py:434

  • This class implements lt, but does not implement le or ge.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

print(f"env = {pretty_env!r}, build = {case[1]!r}, exec = {case[2]!r}")

def _run_legacy(session, idx, name, envs, clean_cmd, build_cmd, exec_cmd) -> None:
def _run_legacy(
Copy link

Copilot AI Jan 28, 2026

Choose a reason for hiding this comment

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

Variable _run_legacy is not used.

Copilot uses AI. Check for mistakes.
"""

def __getitem__(cls, slice_) -> t.Trafaret:
def __getitem__(cls, slice_: slice) -> t.Trafaret:
Copy link

Copilot AI Jan 28, 2026

Choose a reason for hiding this comment

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

Normal methods should have 'self', rather than 'cls', as their first parameter.

Copilot uses AI. Check for mistakes.
return hash((self.project, self.name, self.tag, self.registry, self.architecture))

def __lt__(self, other) -> bool:
def __lt__(self, other: ImageRef) -> bool:
Copy link

Copilot AI Jan 28, 2026

Choose a reason for hiding this comment

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

This method raises ValueError - should raise a TypeError or return NotImplemented instead.

Copilot uses AI. Check for mistakes.
…to return NotImplemented for non-ResourceSlot/ImageRef objects
@HyeockJinKim HyeockJinKim added this pull request to the merge queue Jan 28, 2026
Merged via the queue into main with commit dcbeab7 Jan 28, 2026
33 checks passed
@HyeockJinKim HyeockJinKim deleted the feat/apply-linter-ann branch January 28, 2026 01:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp:agent Related to Agent component comp:app-proxy Related to App Proxy component comp:cli Related to CLI component comp:client Related to Client component comp:common Related to Common component comp:manager Related to Manager component comp:storage-proxy Related to Storage proxy component comp:webserver Related to Web Server component size:L 100~500 LoC

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants