Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
58 commits
Select commit Hold shift + click to select a range
2d2d31e
feat(server): implement `resource scoping` for `tasks` and `push noti…
sokoliva Feb 18, 2026
6093f7f
fix: add poolclass to allow.txt
sokoliva Feb 18, 2026
ce1a305
Merge branch '1.0-dev' of https://github.com/a2aproject/a2a-python in…
sokoliva Feb 19, 2026
6600b47
fix: test_inmemory_task_store.py merge caused error
sokoliva Feb 19, 2026
a212da7
Merge branch '1.0-dev' into resource-scoping
sokoliva Feb 19, 2026
ea89bbb
fix: - add alembic to dev field in pyproject.toml
sokoliva Feb 19, 2026
9301b8c
fix: update uv.lock
sokoliva Feb 19, 2026
62dce31
fix:
sokoliva Feb 19, 2026
86d769e
Merge branch '1.0-dev' into resource-scoping
sokoliva Feb 19, 2026
99cf89f
fix: fix linter issues
sokoliva Feb 19, 2026
a11d6de
Merge branch 'resource-scoping' of https://github.com/sokoliva/a2a-py…
sokoliva Feb 19, 2026
feb5033
Fix: fix some more linter errors
sokoliva Feb 19, 2026
212ad37
fix: more linter errors fixed
sokoliva Feb 19, 2026
f7b5c1c
fix: make parameter `ServerCallContext` non-optional in `PushNotifica…
sokoliva Feb 20, 2026
179b21a
Merge branch '1.0-dev' into resource-scoping
sokoliva Feb 20, 2026
38d7df6
fix: add ServerCallContext to tests/e2e/push_notifications/agent_app.py
sokoliva Feb 20, 2026
5eeb89d
Merge branch 'resource-scoping' of https://github.com/sokoliva/a2a-py…
sokoliva Feb 20, 2026
c4b282a
fix: small fix
sokoliva Feb 20, 2026
0090ecc
fix: fix unit test error
sokoliva Feb 20, 2026
0f51ef3
fi: fix
sokoliva Feb 20, 2026
00e5eac
fix: fix
sokoliva Feb 20, 2026
5d65aa6
chore: distribute alembic migration files. Add helper _get_owner_push…
sokoliva Feb 23, 2026
cbadd5b
Merge branch '1.0-dev' of https://github.com/a2aproject/a2a-python in…
sokoliva Feb 23, 2026
163c8c2
Merge branch '1.0-dev' into resource-scoping
sokoliva Feb 23, 2026
44ad799
fix: linter issues
sokoliva Feb 23, 2026
213ebb2
Merge branch 'resource-scoping' of https://github.com/sokoliva/a2a-py…
sokoliva Feb 23, 2026
5bfccf9
fix: uv run ruff format
sokoliva Feb 23, 2026
bde88f1
refactor: add an edge case to test_database_task_store
sokoliva Feb 24, 2026
db3d050
fix: uv run ruff format
sokoliva Feb 24, 2026
a37efe1
fix: typo
sokoliva Feb 24, 2026
782fcf7
chore: add migration for `push_notification_configs` table
sokoliva Feb 24, 2026
b77a4f6
Merge branch '1.0-dev' into resource-scoping
sokoliva Feb 24, 2026
3428956
fix: rename README to README.md
sokoliva Feb 24, 2026
d90b360
feat: enhance migration CLI with table and verbose options; add owner…
sokoliva Feb 24, 2026
efc54a9
Merge branch '1.0-dev' into resource-scoping
sokoliva Feb 25, 2026
28b6cfc
feat: enhance migration CLI with SQL mode and logging; update README …
sokoliva Feb 25, 2026
591fa76
Merge branch 'resource-scoping' of https://github.com/sokoliva/a2a-py…
sokoliva Feb 25, 2026
94f129d
fix: uv run ruff format
sokoliva Feb 25, 2026
7f9e2bc
fix: remove user existence check in resolve_user_scope function
sokoliva Feb 25, 2026
59f1fd4
feat: add CLI support for alembic in migration tool and update depend…
sokoliva Feb 25, 2026
31fd9c1
fix: add ImportError handling for Alembic in CLI and migration files
sokoliva Feb 25, 2026
e98b578
Merge branch '1.0-dev' into resource-scoping
sokoliva Feb 26, 2026
0c6d5f2
docs: update installation instructions for a2a-db migration tool
sokoliva Feb 26, 2026
f61eaf4
refactor: replace defaultdict with dict for in-memory task and notifi…
sokoliva Feb 26, 2026
73995fa
feat: introduce a2a-db CLI for database migrations and update documen…
sokoliva Feb 26, 2026
61e89fa
fix: format
sokoliva Feb 26, 2026
9dc9d0c
docs: clarify error message for --owner-name flag in downgrade test
sokoliva Feb 26, 2026
580d2ca
feat: update CLI flags for owner column in migrations and enhance err…
sokoliva Feb 27, 2026
4164a08
feat: refactor migration tests to use direct function calls and mock …
sokoliva Feb 27, 2026
874e72b
feat: enhance migration tests with importlib for coverage and refacto…
sokoliva Feb 27, 2026
8317e6f
Merge branch '1.0-dev' into resource-scoping
ishymko Feb 27, 2026
bf7961d
feat: rename a2a-db-cli to db-cli in installation instructions and up…
sokoliva Feb 27, 2026
34f3d76
Merge branch 'resource-scoping' of https://github.com/sokoliva/a2a-py…
sokoliva Feb 27, 2026
a041116
feat: update migration version table name to 'a2a_alembic_version'
sokoliva Feb 27, 2026
b7bbc17
feat: use VERSION_TABLE constant for alembic version table name in mi…
sokoliva Feb 27, 2026
1e19e18
fix: change last_updated type from String to DateTime
sokoliva Feb 27, 2026
55ee94e
feat: update column definitions for owner and last_updated in migrati…
sokoliva Feb 27, 2026
798e455
Merge branch '1.0-dev' into resource-scoping
sokoliva Feb 27, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# A generic, single database configuration.

[alembic]

# database URL. This is consumed by the user-maintained env.py script only.
# other means of configuring database URLs may be customized within the env.py
# file.
# IMPORTANT: This is a placeholder and an example, and should be replaced with your actual database URL.
sqlalchemy.url = sqlite+aiosqlite:///./test.db


# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARNING
handlers = console
qualname =

[logger_sqlalchemy]
level = WARNING
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
56 changes: 56 additions & 0 deletions alembic/README
Comment thread
sokoliva marked this conversation as resolved.
Outdated
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Database Migrations with Alembic

This directory contains database migration scripts for the A2A SDK, managed by [Alembic](https://alembic.sqlalchemy.org/).

## Configuration

- `alembic.ini`: Global configuration for Alembic, including the database URL.
- `env.py`: Python script that runs when the Alembic environment is invoked. It configures the SQLAlchemy engine and connects it to the migration context.
- `versions/`: Directory containing individual migration scripts.

## Common Commands

All commands should be run from the project root using `uv run`.

### Viewing Status
```bash
# View current migration version of the database
uv run alembic current

# View migration history
uv run alembic history --verbose
```

### Running Migrations
```bash
# Upgrade to the latest version
uv run alembic upgrade head

# Downgrade by one version
uv run alembic downgrade base
Comment thread
sokoliva marked this conversation as resolved.
Outdated
```

### Creating Migrations
```bash
# Create a new migration manually
uv run alembic revision -m "description of changes"

# Create a new migration automatically (detects changes in models.py)
uv run alembic revision --autogenerate -m "description of changes"
```

## Troubleshooting

### "duplicate column name" error
If you see an error like `sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) duplicate column name: owner`, it usually means the column was already created (perhaps by `Base.metadata.create_all()` in tests or development) but Alembic doesn't know about it yet.

To fix this, "stamp" the database to tell Alembic it is already at the latest version:
```bash
uv run alembic stamp head
```

## How to add a new migration
1. Modify the models in `src/a2a/server/models.py`.
2. Run `uv run alembic revision --autogenerate -m "Add new field to Task"`.
3. Review the generated script in `alembic/versions/`.
4. Apply the migration with `uv run alembic upgrade head`.
85 changes: 85 additions & 0 deletions alembic/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import asyncio

Check failure on line 1 in alembic/env.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Ruff (INP001)

alembic/env.py:1:1: INP001 File `alembic/env.py` is part of an implicit namespace package. Add an `__init__.py`.

from logging.config import fileConfig

from sqlalchemy import pool
from sqlalchemy.ext.asyncio import async_engine_from_config

from a2a.server.models import Base
from alembic import context


# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)

# add your model's MetaData object here for 'autogenerate' support
target_metadata = Base.metadata

# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")

Check failure on line 26 in alembic/env.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Ruff (ERA001)

alembic/env.py:26:1: ERA001 Found commented-out code
# ... etc.


def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.

This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.

Calls to context.execute() here emit the given string to the
script output.

"""
url = config.get_main_option('sqlalchemy.url')
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={'paramstyle': 'named'},
)

with context.begin_transaction():
context.run_migrations()


def do_run_migrations(connection):

Check failure on line 54 in alembic/env.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Ruff (ANN001)

alembic/env.py:54:23: ANN001 Missing type annotation for function argument `connection`

Check failure on line 54 in alembic/env.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Ruff (D103)

alembic/env.py:54:5: D103 Missing docstring in public function

Check failure on line 54 in alembic/env.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Ruff (ANN201)

alembic/env.py:54:5: ANN201 Missing return type annotation for public function `do_run_migrations`
context.configure(connection=connection, target_metadata=target_metadata)

with context.begin_transaction():
context.run_migrations()


async def run_async_migrations():

Check failure on line 61 in alembic/env.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Ruff (ANN201)

alembic/env.py:61:11: ANN201 Missing return type annotation for public function `run_async_migrations`
"""In this scenario we need to create an Engine
and associate a connection with the context.
"""

Check failure on line 64 in alembic/env.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Ruff (D205)

alembic/env.py:62:5: D205 1 blank line required between summary line and description
connectable = async_engine_from_config(
config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolclass=pool.NullPool,

Check failure on line 68 in alembic/env.py

View workflow job for this annotation

GitHub Actions / Check Spelling

`poolclass` is not a recognized word. (unrecognized-spelling)
)

async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)

await connectable.dispose()


def run_migrations_online():

Check failure on line 77 in alembic/env.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Ruff (ANN201)

alembic/env.py:77:5: ANN201 Missing return type annotation for public function `run_migrations_online`
"""Run migrations in 'online' mode."""
asyncio.run(run_async_migrations())


if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
28 changes: 28 additions & 0 deletions alembic/script.py.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""${message}

Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
${imports if imports else ""}

# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}


def upgrade() -> None:
"""Upgrade schema."""
${upgrades if upgrades else "pass"}


def downgrade() -> None:
"""Downgrade schema."""
${downgrades if downgrades else "pass"}
38 changes: 38 additions & 0 deletions alembic/versions/6419d2d130f6_add_owner_to_task.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
"""add_owner_to_task

Check failure on line 1 in alembic/versions/6419d2d130f6_add_owner_to_task.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Ruff (INP001)

alembic/versions/6419d2d130f6_add_owner_to_task.py:1:1: INP001 File `alembic/versions/6419d2d130f6_add_owner_to_task.py` is part of an implicit namespace package. Add an `__init__.py`.

Revision ID: 6419d2d130f6
Revises:
Create Date: 2026-02-17 09:23:06.758085

"""

Check failure on line 7 in alembic/versions/6419d2d130f6_add_owner_to_task.py

View workflow job for this annotation

GitHub Actions / Lint Code Base

Ruff (D415)

alembic/versions/6419d2d130f6_add_owner_to_task.py:1:1: D415 First line should end with a period, question mark, or exclamation point

from collections.abc import Sequence

import sqlalchemy as sa

from alembic import op


# revision identifiers, used by Alembic.
revision: str = '6419d2d130f6'
down_revision: str | Sequence[str] | None = None
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
"""Upgrade schema."""
op.add_column(
'tasks',
sa.Column(
'owner',
sa.String(255),
nullable=False,
server_default='unknown', # Set your desired default value here
),
)


def downgrade() -> None:
"""Downgrade schema."""
op.drop_column('tasks', 'owner')
86 changes: 86 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -323,3 +323,89 @@ docstring-code-format = true
docstring-code-line-length = "dynamic"
quote-style = "single"
indent-style = "space"


[tool.alembic]
Comment thread
sokoliva marked this conversation as resolved.

# path to migration scripts.
# this is typically a path given in POSIX (e.g. forward slashes)
# format, relative to the token %(here)s which refers to the location of this
# ini file
script_location = "%(here)s/alembic"

# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = "%%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s"
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
# file_template = "%%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s"

# additional paths to be prepended to sys.path. defaults to the current working directory.
prepend_sys_path = [
"."
]

# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the tzdata library which can be installed by adding
# `alembic[tz]` to the pip requirements.
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =

# max length of characters to apply to the "slug" field
# truncate_slug_length = 40

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false

# version location specification; This defaults
# to <script_location>/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# version_locations = [
# "%(here)s/alembic/versions",
# "%(here)s/foo/bar"
# ]


# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false

# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = "utf-8"

# This section defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# [[tool.alembic.post_write_hooks]]
# format using "black" - use the console_scripts runner,
# against the "black" entrypoint
# name = "black"
# type = "console_scripts"
# entrypoint = "black"
# options = "-l 79 REVISION_SCRIPT_FILENAME"
#
# [[tool.alembic.post_write_hooks]]
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
# name = "ruff"
# type = "module"
# module = "ruff"
# options = "check --fix REVISION_SCRIPT_FILENAME"
#
# [[tool.alembic.post_write_hooks]]
# Alternatively, use the exec runner to execute a binary found on your PATH
# name = "ruff"
# type = "exec"
# executable = "ruff"
# options = "check --fix REVISION_SCRIPT_FILENAME"

Comment thread
sokoliva marked this conversation as resolved.
Outdated
18 changes: 17 additions & 1 deletion src/a2a/server/models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import datetime

from typing import TYPE_CHECKING, Any, Generic, TypeVar


Expand All @@ -16,7 +18,7 @@ def override(func): # noqa: ANN001, ANN201


try:
from sqlalchemy import JSON, Dialect, LargeBinary, String
from sqlalchemy import JSON, Dialect, Index, LargeBinary, String
Comment thread
sokoliva marked this conversation as resolved.
Outdated
from sqlalchemy.orm import (
DeclarativeBase,
Mapped,
Expand Down Expand Up @@ -127,6 +129,8 @@ class TaskMixin:
kind: Mapped[str] = mapped_column(
String(16), nullable=False, default='task'
)
owner: Mapped[str] = mapped_column(String(255), nullable=False, index=True)
last_updated: Mapped[datetime] = mapped_column(String(22), nullable=True)
Comment thread
sokoliva marked this conversation as resolved.
Outdated

# Properly typed Pydantic fields with automatic serialization
status: Mapped[TaskStatus] = mapped_column(PydanticType(TaskStatus))
Expand All @@ -152,6 +156,17 @@ def __repr__(self) -> str:
f'context_id="{self.context_id}", status="{self.status}")>'
)

@declared_attr
@classmethod
def __table_args__(cls) -> tuple[Any, ...]:
"""Define a unique index (owner, last_updated) for each table that uses the mixin."""
tablename = getattr(cls, '__tablename__', 'tasks')
return (
Index(
f'idx_{tablename}_owner_last_updated', 'owner', 'last_updated'
),
)


def create_task_model(
table_name: str = 'tasks', base: type[DeclarativeBase] = Base
Expand Down Expand Up @@ -212,6 +227,7 @@ class PushNotificationConfigMixin:
task_id: Mapped[str] = mapped_column(String(36), primary_key=True)
config_id: Mapped[str] = mapped_column(String(255), primary_key=True)
config_data: Mapped[bytes] = mapped_column(LargeBinary, nullable=False)
owner: Mapped[str] = mapped_column(String(255), nullable=False, index=True)

@override
def __repr__(self) -> str:
Expand Down
Loading
Loading