Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion .agents/project.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@

- `CHANGELOG.md`: release-please writes the `## [x.y.z](…)` sections; never edit them. A user-visible change adds a hand-written section `## x.y.z — <one-line headline>` at the top of the entries, in the same pull request, with `x.y.z` the version it will ship in (#87, #89, #94). release-please then puts its own section above it. CONTRIBUTING.md and the pull request template say the same; the file has not used an `[Unreleased]` heading since 1.3.0.
- The version lives in `pg_partsmith/__version__.py`, on the line marked `# x-release-please-version`, and in `.release-please-manifest.json`; release-please bumps both. Never change them by hand. To force a version, add a `Release-As: x.y.z` footer to a commit.
- `pg_partsmith/sync/` is generated from `pg_partsmith/aio/` by `scripts/sync_mirror.py`. The exceptions are maintained by hand: the lock managers, `maintainer.py`, `command_hooks.py`, `python_hooks.py` and `repositories/{resolver,fk_manager,timeouts,pin}.py`. `tests/integration/sync/` is generated from `tests/integration/aio/` by `scripts/sync_tests_mirror.py`, except `test_concurrency.py`. Edit the aio side, regenerate, run `ruff check --fix` and `ruff format` on the output, then review the diff (CONTRIBUTING.md, "Keeping aio and sync in sync"). CI does not check the mirror.
- `pg_partsmith/sync/` is generated from `pg_partsmith/aio/` by `scripts/sync_mirror.py`. The exceptions are maintained by hand: the lock managers, `maintainer.py`, `command_hooks.py`, `python_hooks.py` and `repositories/{resolver,fk_manager,timeouts,pin}.py`. `tests/integration/sync/` is generated from `tests/integration/aio/` by `scripts/sync_tests_mirror.py`, except `test_concurrency.py`, and `test_cli.py` has no sync twin (the CLI runs the aio service itself). Edit the aio side, regenerate, run `ruff check --fix` and `ruff format` on the output, then review the diff (CONTRIBUTING.md, "Keeping aio and sync in sync"). CI does not check the mirror.
- `docs/agents.md` is part of the public API: it changes in the same pull request as the API (CONTRIBUTING.md, "The agents page").
- `docs/changelog.md` is a copy of `CHANGELOG.md` made by the docs build, and git ignores it.
- Files from the engineering-assets hub (`AGENTS.md` explains how it works): the copy-page files (`docs/assets/javascripts/copy-page.js`, `docs/assets/stylesheets/copy-page.css`, `overrides/main.html`, `scripts/emit_markdown.py`), `.github/workflows/docs.yml`, `.github/workflows/release-please.yml`, `.editorconfig` and `CODE_OF_CONDUCT.md`. Change them in the hub; a change here makes the file this repository's own. `.github/dependabot.yml` already belongs to this repository: it adds the `docker` ecosystem for the Dockerfile's base images.
Expand Down
1 change: 1 addition & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ uv run ruff check --fix tests/integration/sync && uv run ruff format tests/integ
A test that drives two coroutines at once cannot be mirrored mechanically: put a
`# sync-mirror: skip` line right above it and write its thread-based twin in
`tests/integration/sync/test_concurrency.py`, the one hand-written module of that suite.
`tests/integration/aio/test_cli.py` has no sync twin: the CLI runs the aio service itself.
`tests/unit/sync/` mirrors `tests/unit/` by hand — only the modules touching the aio package
have a sync twin.

Expand Down
42 changes: 33 additions & 9 deletions scripts/sync_tests_mirror.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@
concurrently, say) is marked in the aio suite with a ``# sync-mirror: skip``
line right above it (above its decorators, if any) and is left out of the sync
suite; its thread-based twin lives in ``tests/integration/sync/test_concurrency.py``,
the one module of the sync suite that is written by hand. A module the aio
suite no longer has is removed from the sync suite, that one excepted.
the one module of the sync suite that is written by hand. ``test_cli.py`` has
no sync twin: the CLI runs the aio service on an event loop of its own, so a
mirror would run the same code again. A module the aio suite no longer has is
removed from the sync suite, the hand-written one excepted.
"""

from __future__ import annotations
Expand All @@ -28,9 +30,11 @@
SYNC = ROOT / "tests" / "integration" / "sync"

HANDWRITTEN = frozenset({"test_concurrency.py"})
AIO_ONLY = frozenset({"test_cli.py"})
SKIP_MARKER = "# sync-mirror: skip"
TOP_LEVEL = re.compile(r"^(async def |def |class |@|# ──)")
DEFINITION = re.compile(r"^(async )?def ")
SECTION = "# ──"
TOP_LEVEL = re.compile(rf"^(async def |def |class |@|{SECTION})")
DEFINITION = re.compile(r"^((async )?def |class )")
FOR_LOOP = re.compile(r"^(?P<indent>\s*)for (?P<var>\w+) in (?P<rest>.*)$")

RULES: list[tuple[str, str]] = [
Expand Down Expand Up @@ -89,19 +93,18 @@

def transform(text: str) -> str:
"""Turn one aio test module into its sync twin."""
text = "\n".join(_without_skipped(text.split("\n")))
text = "\n".join(_without_empty_sections(_without_skipped(text.split("\n"))))
for pattern, repl in RULES:
text = re.sub(pattern, repl, text)
text = text.replace("import asyncio\n", "")
return "\n".join(_yield_from(text.split("\n")))


def _without_skipped(lines: list[str]) -> list[str]:
"""Leave out every function under a ``# sync-mirror: skip`` line.
"""Leave out every function or class under a ``# sync-mirror: skip`` line.

The marker sits right above the function -- above its decorators when it
has any -- and the function ends at the next top-level definition,
decorator or section heading.
The marker sits right above it -- above its decorators when it has any --
and it ends at the next top-level definition, decorator or section heading.
"""
kept: list[str] = []
state = "keep"
Expand All @@ -126,6 +129,25 @@ def _without_skipped(lines: list[str]) -> list[str]:
return kept


def _without_empty_sections(lines: list[str]) -> list[str]:
"""Drop a section heading, and the comments under it, when no code is left in its section."""
kept: list[str] = []
i = 0
while i < len(lines):
if lines[i].startswith(SECTION):
end = i + 1
while end < len(lines) and (
not lines[end].strip() or (lines[end].startswith("#") and not lines[end].startswith(SECTION))
):
end += 1
if end == len(lines) or lines[end].startswith(SECTION):
i = end
continue
kept.append(lines[i])
i += 1
return kept


def _yield_from(lines: list[str]) -> list[str]:
"""Spell ``for x in gen(...): yield x`` -- what an ``async for`` becomes -- as ``yield from``."""
out: list[str] = []
Expand Down Expand Up @@ -160,6 +182,8 @@ def main() -> None:
SYNC.mkdir(parents=True, exist_ok=True)
generated: set[str] = set()
for source in sorted(AIO.glob("*.py")):
if source.name in AIO_ONLY:
continue
target = SYNC / source.name
target.write_text(transform(source.read_text(encoding="utf-8")), encoding="utf-8")
generated.add(target.name)
Expand Down
1 change: 1 addition & 0 deletions tests/integration/sync/test_lifecycle_policies.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,7 @@ def test__detach_mode_auto__with_a_default_partition__is_planned_as_the_blocking
detach = result.maintenance_plan.detaches[0]
assert detach.mode is DetachMode.BLOCKING
assert "DEFAULT partition" in detach.detail
assert "ACCESS EXCLUSIVE on the parent" in detach.capabilities.lock


def test__detach_mode_auto__without_a_default_partition__stays_concurrent(sync_db_engine: Engine, table: str) -> None:
Expand Down
6 changes: 0 additions & 6 deletions tests/integration/sync/test_maintainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,12 +279,6 @@ def test__maintainer__run_maintenance_safe__never_raises_and_reports_the_error(
assert result.created_count == 0


# ── Two maintainers on the same table ────────────────────────────────────────────


# ── An interrupted DETACH CONCURRENTLY ──────────────────────────────────────────


# ── A hook must not be able to redirect a detach ────────────────────────────────


Expand Down
3 changes: 0 additions & 3 deletions tests/integration/sync/test_safe_drop.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,3 @@ def test__drop_partition__expected_oid_of_another_relation__refused_and_the_tabl
# The right identity still drops it
repo.drop_partition(name, expected_oid=real_oid)
assert not metadata.partition_exists(name)


# ── retry on lock contention ──────────────────────────────────────────────────────
127 changes: 127 additions & 0 deletions tests/unit/test_sync_tests_mirror.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
"""The generator of the sync integration suite: what it leaves out and what it must keep.

CI does not compare the sync suite with the aio one, so a test the generator
drops by mistake just stops running, with nothing to say so.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

import pytest

from scripts import sync_tests_mirror
from scripts.sync_tests_mirror import transform

if TYPE_CHECKING:
from pathlib import Path

pytestmark = pytest.mark.unit


def test__transform__a_skipped_class__keeps_the_heading_and_the_test_after_it() -> None:
# Arrange
source = """\
# sync-mirror: skip
class _Writer:
async def write(self) -> None:
await self.conn.execute(self.sql)


# ── partition_data ──────────────────────────────────────────────────────────────


async def test__drains(db_engine: AsyncEngine) -> None:
assert await count(db_engine) == 0
"""

expected = """\
# ── partition_data ──────────────────────────────────────────────────────────────


def test__drains(sync_db_engine: Engine) -> None:
assert count(sync_db_engine) == 0
"""

# Act
mirrored = transform(source)

# Assert
assert mirrored == expected


def test__transform__a_skipped_decorated_test__keeps_the_test_after_it() -> None:
# Arrange
source = """\
# sync-mirror: skip
@pytest.mark.parametrize("n", [1, 2])
async def test__races(db_engine: AsyncEngine, n: int) -> None:
await asyncio.gather(work(db_engine), work(db_engine))


async def test__plain(db_engine: AsyncEngine) -> None:
assert await count(db_engine) == 0
"""

expected = """\
def test__plain(sync_db_engine: Engine) -> None:
assert count(sync_db_engine) == 0
"""

# Act
mirrored = transform(source)

# Assert
assert mirrored == expected


def test__transform__a_section_whose_tests_are_all_skipped__loses_its_heading_and_comment() -> None:
# Arrange
source = """\
# ── under a live writer ─────────────────────────────────────────────────────────
#
# Why these tests need two coroutines at once.


# sync-mirror: skip
async def test__races(db_engine: AsyncEngine) -> None:
await asyncio.gather(work(db_engine), work(db_engine))


# ── retry ───────────────────────────────────────────────────────────────────────


async def test__retries(db_engine: AsyncEngine) -> None:
assert await count(db_engine) == 0
"""

expected = """\
# ── retry ───────────────────────────────────────────────────────────────────────


def test__retries(sync_db_engine: Engine) -> None:
assert count(sync_db_engine) == 0
"""

# Act
mirrored = transform(source)

# Assert
assert mirrored == expected


def test__main__the_cli_module__gets_no_sync_twin(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
# Arrange
aio, sync = tmp_path / "aio", tmp_path / "sync"
aio.mkdir()
(aio / "test_cli.py").write_text("async def test__cli() -> None:\n pass\n", encoding="utf-8")
(aio / "test_plan.py").write_text("async def test__plan() -> None:\n pass\n", encoding="utf-8")
monkeypatch.setattr(sync_tests_mirror, "ROOT", tmp_path)
monkeypatch.setattr(sync_tests_mirror, "AIO", aio)
monkeypatch.setattr(sync_tests_mirror, "SYNC", sync)

# Act
sync_tests_mirror.main()

# Assert
assert sorted(path.name for path in sync.iterdir()) == ["test_plan.py"]
Loading