Metadata-Version: 2.5
Name: pg-partsmith
Version: 1.3.0
Summary: PostgreSQL partition lifecycle management with extensible hooks
Project-URL: Repository, https://github.com/bedrock-python/pg-partsmith
Project-URL: Documentation, https://bedrock-python.github.io/pg-partsmith/
Project-URL: Changelog, https://github.com/bedrock-python/pg-partsmith/blob/master/CHANGELOG.md
Project-URL: Bug Tracker, https://github.com/bedrock-python/pg-partsmith/issues
Author-email: Alex Shalaev <shalaevad.alexey@gmail.com>
License: Apache License
        Version 2.0, January 2004
        http://www.apache.org/licenses/
        
        TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
        1. Definitions.
        
        "License" shall mean the terms and conditions for use, reproduction,
        and distribution as defined by Sections 1 through 9 of this document.
        
        "Licensor" shall mean the copyright owner or entity authorized by
        the copyright owner that is granting the License.
        
        "Legal Entity" shall mean the union of the acting entity and all
        other entities that control, are controlled by, or are under common
        control with that entity. For the purposes of this definition,
        "control" means (i) the power, direct or indirect, to cause the
        direction or management of such entity, whether by contract or
        otherwise, or (ii) ownership of fifty percent (50%) or more of the
        outstanding shares, or (iii) beneficial ownership of such entity.
        
        "You" (or "Your") shall mean an individual or Legal Entity
        exercising permissions granted by this License.
        
        "Source" form shall mean the preferred form for making modifications,
        including but not limited to software source code, documentation
        source, and configuration files.
        
        "Object" form shall mean any form resulting from mechanical
        transformation or translation of a Source form, including but
        not limited to compiled object code, generated documentation,
        and conversions to other media types.
        
        "Work" shall mean the work of authorship, whether in Source or
        Object form, made available under the License, as indicated by a
        copyright notice that is included in or attached to the work
        (an example is provided in the Appendix below).
        
        "Derivative Works" shall mean any work, whether in Source or Object
        form, that is based on (or derived from) the Work and for which the
        editorial revisions, annotations, elaborations, or other modifications
        represent, as a whole, an original work of authorship. For the purposes
        of this License, Derivative Works shall not include works that remain
        separable from, or merely link (or bind by name) to the interfaces of,
        the Work and Derivative Works thereof.
        
        "Contribution" shall mean any work of authorship, including
        the original version of the Work and any modifications or additions
        to that Work or Derivative Works thereof, that is intentionally
        submitted to Licensor for inclusion in the Work by the copyright owner
        or by an individual or Legal Entity authorized to submit on behalf of
        the copyright owner. For the purposes of this definition, "submitted"
        means any form of electronic, verbal, or written communication sent
        to the Licensor or its representatives, including but not limited to
        communication on electronic mailing lists, source code control systems,
        and issue tracking systems that are managed by, or on behalf of, the
        Licensor for the purpose of discussing and improving the Work, but
        excluding communication that is conspicuously marked or otherwise
        designated in writing by the copyright owner as "Not a Contribution."
        
        "Contributor" shall mean Licensor and any individual or Legal Entity
        on behalf of whom a Contribution has been received by Licensor and
        subsequently incorporated within the Work.
        
        2. Grant of Copyright License. Subject to the terms and conditions of
        this License, each Contributor hereby grants to You a perpetual,
        worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        copyright license to reproduce, prepare Derivative Works of,
        publicly display, publicly perform, sublicense, and distribute the
        Work and such Derivative Works in Source or Object form.
        
        3. Grant of Patent License. Subject to the terms and conditions of
        this License, each Contributor hereby grants to You a perpetual,
        worldwide, non-exclusive, no-charge, royalty-free, irrevocable
        (except as stated in this section) patent license to make, have made,
        use, offer to sell, sell, import, and otherwise transfer the Work,
        where such license applies only to those patent claims licensable
        by such Contributor that are necessarily infringed by their
        Contribution(s) alone or by combination of their Contribution(s)
        with the Work to which such Contribution(s) was submitted. If You
        institute patent litigation against any entity (including a
        cross-claim or counterclaim in a lawsuit) alleging that the Work
        or a Contribution incorporated within the Work constitutes direct
        or contributory patent infringement, then any patent licenses
        granted to You under this License for that Work shall terminate
        as of the date such litigation is filed.
        
        4. Redistribution. You may reproduce and distribute copies of the
        Work or Derivative Works thereof in any medium, with or without
        modifications, and in Source or Object form, provided that You
        meet the following conditions:
        
        (a) You must give any other recipients of the Work or
        Derivative Works a copy of this License; and
        
        (b) You must cause any modified files to carry prominent notices
        stating that You changed the files; and
        
        (c) You must retain, in the Source form of any Derivative Works
        that You distribute, all copyright, patent, trademark, and
        attribution notices from the Source form of the Work,
        excluding those notices that do not pertain to any part of
        the Derivative Works; and
        
        (d) If the Work includes a "NOTICE" text file as part of its
        distribution, then any Derivative Works that You distribute must
        include a readable copy of the attribution notices contained
        within such NOTICE file, excluding those notices that do not
        pertain to any part of the Derivative Works, in at least one
        of the following places: within a NOTICE text file distributed
        as part of the Derivative Works; within the Source form or
        documentation, if provided along with the Derivative Works; or,
        within a display generated by the Derivative Works, if and
        wherever such third-party notices normally appear. The contents
        of the NOTICE file are for informational purposes only and
        do not modify the License. You may add Your own attribution
        notices within Derivative Works that You distribute, alongside
        or as an addendum to the NOTICE text from the Work, provided
        that such additional attribution notices cannot be construed
        as modifying the License.
        
        You may add Your own copyright statement to Your modifications and
        may provide additional or different license terms and conditions
        for use, reproduction, or distribution of Your modifications, or
        for any such Derivative Works as a whole, provided Your use,
        reproduction, and distribution of the Work otherwise complies with
        the conditions stated in this License.
        
        5. Submission of Contributions. Unless You explicitly state otherwise,
        any Contribution intentionally submitted for inclusion in the Work
        by You to the Licensor shall be under the terms and conditions of
        this License, without any additional terms or conditions.
        Notwithstanding the above, nothing herein shall supersede or modify
        the terms of any separate license agreement you may have executed
        with Licensor regarding such Contributions.
        
        6. Trademarks. This License does not grant permission to use the trade
        names, trademarks, service marks, or product names of the Licensor,
        except as required for reasonable and customary use in describing the
        origin of the Work and reproducing the content of the NOTICE file.
        
        7. Disclaimer of Warranty. Unless required by applicable law or
        agreed to in writing, Licensor provides the Work (and each
        Contributor provides its Contributions) on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
        implied, including, without limitation, any warranties or conditions
        of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
        PARTICULAR PURPOSE. You are solely responsible for determining the
        appropriateness of using or redistributing the Work and assume any
        risks associated with Your exercise of permissions under this License.
        
        8. Limitation of Liability. In no event and under no legal theory,
        whether in tort (including negligence), contract, or otherwise,
        unless required by applicable law (such as deliberate and grossly
        negligent acts) or agreed to in writing, shall any Contributor be
        liable to You for damages, including any direct, indirect, special,
        incidental, or consequential damages of any character arising as a
        result of this License or out of the use or inability to use the
        Work (including but not limited to damages for loss of goodwill,
        work stoppage, computer failure or malfunction, or any and all
        other commercial damages or losses), even if such Contributor
        has been advised of the possibility of such damages.
        
        9. Accepting Warranty or Additional Liability. While redistributing
        the Work or Derivative Works thereof, You may choose to offer,
        and charge a fee for, acceptance of support, warranty, indemnity,
        or other liability obligations and/or rights consistent with this
        License. However, in accepting such obligations, You may act only
        on Your own behalf and on Your sole responsibility, not on behalf
        of any other Contributor, and only if You agree to indemnify,
        defend, and hold each Contributor harmless for any liability
        incurred by, or claims asserted against, such Contributor by reason
        of your accepting any such warranty or additional liability.
        
        END OF TERMS AND CONDITIONS
        
        APPENDIX: How to apply the Apache License to your work.
        
        To apply the Apache License to your work, attach the following
        boilerplate notice, with the fields enclosed by brackets "[]"
        replaced with your own identifying information. (Don't include
        the brackets!) The text should be enclosed in the appropriate
        comment syntax for the file format. We also recommend that a
        file or class name and description of purpose be included on the
        same "printed page" as the copyright notice for easier
        identification within third-party archives.
        
        Copyright 2026 Alex Shalaev
        
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
        
        http://www.apache.org/licenses/LICENSE-2.0
        
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
License-File: LICENSE
Keywords: asyncio,database,partition-management,partitioning,postgresql
Classifier: Development Status :: 5 - Production/Stable
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Database
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: pydantic<3.0.0,>=2.6.0
Requires-Dist: python-dateutil<3.0.0,>=2.7.0
Requires-Dist: sqlalchemy[asyncio]<3.0.0,>=2.0.0
Provides-Extra: cli
Requires-Dist: asyncpg>=0.29.0; extra == 'cli'
Requires-Dist: pyyaml<7.0,>=6.0; extra == 'cli'
Requires-Dist: typer<1.0,>=0.17; extra == 'cli'
Provides-Extra: pydantic-settings
Requires-Dist: pydantic-settings<3.0.0,>=2.0.0; extra == 'pydantic-settings'
Provides-Extra: redis-locks
Requires-Dist: redis>=4.2.0; extra == 'redis-locks'
Description-Content-Type: text/markdown

# pg-partsmith

PostgreSQL partition lifecycle management with a plan you can read before it runs.

[![PyPI](https://img.shields.io/pypi/v/pg-partsmith?color=blue)](https://pypi.org/project/pg-partsmith/)
[![Python](https://img.shields.io/pypi/pyversions/pg-partsmith)](https://pypi.org/project/pg-partsmith/)
[![License](https://img.shields.io/github/license/bedrock-python/pg-partsmith)](LICENSE)
[![CI](https://github.com/bedrock-python/pg-partsmith/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/bedrock-python/pg-partsmith/actions/workflows/ci.yml)
[![codecov](https://codecov.io/gh/bedrock-python/pg-partsmith/graph/badge.svg)](https://codecov.io/gh/bedrock-python/pg-partsmith)
[![Docs](https://img.shields.io/badge/docs-online-blue)](https://bedrock-python.github.io/pg-partsmith/)

A plain-Python engine for native PostgreSQL declarative partitioning. It understands a
table's partition **scheme** (`RANGE`, `LIST`, `HASH`, nested to any depth), its
**lifecycle policy** (what to create ahead, what has expired, when to drop), reads the
tree that actually exists from the catalog, and turns the difference into a
**maintenance plan** — typed operations with a reason on each — that you can inspect,
serialize, filter and apply. No extension, no superuser, no scheduler of its own.

Three ways in, one version number:

| | | |
|---|---|---|
| **Library** | `pip install pg-partsmith` | Python, `asyncio` or sync, on any SQLAlchemy 2 engine. [Getting started](https://bedrock-python.github.io/pg-partsmith/getting-started/installation/) |
| **Command line** | `pip install "pg-partsmith[cli]"` | `pg-partsmith plan`, `apply` and `validate` over a YAML document, with exit codes a CronJob can read. [The CLI](https://bedrock-python.github.io/pg-partsmith/guide/cli/) |
| **Container image** | `ghcr.io/bedrock-python/pg-partsmith:latest` | The command line with no Python of your own: a Job, a CronJob, an init container. [The image](https://bedrock-python.github.io/pg-partsmith/guide/container/) |

> [!TIP]
> **Building this with an AI assistant?** Hand it
> **[one page](https://bedrock-python.github.io/pg-partsmith/agents/)** instead of the
> whole site: the complete API surface, the rules that break code when they are broken,
> the mistakes models actually make, and a map of which page to fetch for the rest. Every
> docs page is also served as raw Markdown at its own URL, and a **Copy page** button at
> the top of each one hands it straight to a chat window.

## Features

- **Any topology** — `RANGE(time)`, `RANGE(id)`, root `HASH`, root `LIST`, a sliding
  `LIST` rotated by application state, `RANGE → HASH`, `RANGE → LIST → HASH`,
  `LIST → RANGE`; composite keys
- **Any axis** — calendar periods over timestamps, or over encoded keys (UUIDv7, epoch
  integers, your own codec); fixed-width integer windows for id-partitioned queues
- **Lifecycle policies** — create ahead by count, until a horizon or when the newest
  partition says so; expire by count, age or distance, or by a predicate (size, rows,
  foreign-key references, SQL); detach now, drop after a grace period
- **Leaf backends** — local tables with a tablespace, storage parameters and the parent's
  grants, or foreign tables on an FDW server (`postgres_fdw`, ClickHouse)
- **Batched data movement** — drain a DEFAULT partition into lifecycle partitions
  (`partition_data`), or move everything back into one table (`unpartition`)
- **Plan → apply** — `plan()` issues zero DDL and tells you *what*, *why* and *how big*;
  `apply()` revalidates every destructive operation against the catalog before running it
- **Convergent and safe** — a converged tree costs zero DDL; gaps in hash sets are repaired
  at their own modulus; partitions the scheme did not produce are reported, never touched;
  foreign tables are inspected, never dropped
- **Async and sync** — `pg_partsmith.aio` on `AsyncEngine`, `pg_partsmith.sync` on `Engine`
- **A command line** — `pg-partsmith inspect / plan / validate / apply` over a YAML or
  JSON document, with a saved plan as the artifact between plan and apply, and exit codes
  a CronJob and a CI step can read
- **A container image** — `ghcr.io/bedrock-python/pg-partsmith`, for stacks with no Python
  in them; documented shapes for plain Docker, Compose, Swarm, Kubernetes Pod / Job /
  CronJob / init container, CI and systemd
- **Examples that are tested** — every document under `examples/` validates in CI, the hook
  scripts parse, and `pg-partsmith schema` gives an editor the JSON Schema
- **Hooks, locks, schemas** — eight lifecycle hooks, in Python or as commands named in a
  config file; PostgreSQL advisory or Redis locks; schema-qualified everything
- **Type-safe, tested** — Pydantic models, full mypy, real PostgreSQL 15 through 18 via testcontainers

## Installation

```bash
pip install pg-partsmith

# The pg-partsmith command, for a config file and a CronJob instead of Python
pip install "pg-partsmith[cli]"

# With Redis distributed locks
pip install "pg-partsmith[redis-locks]"
```

**Requirements:** Python 3.11+, PostgreSQL 15+

## Quick start

```python
from sqlalchemy.ext.asyncio import create_async_engine

from pg_partsmith import PartitionGranularity, TablePartitionConfig
from pg_partsmith.aio import (
    PartitionLifecycleService,
    PartitionMaintainer,
    PostgresAdvisoryLockManager,
    PostgresMetadataProvider,
    PostgresPartitionRepository,
)

engine = create_async_engine("postgresql+asyncpg://user:pass@host/db")

config = TablePartitionConfig(
    schema="public",
    table_name="events",
    partition_column="created_at",
    granularity=PartitionGranularity.MONTH,
    create_ahead_count=3,  # current month + next 2
    retention_count=12,
)

service = PartitionLifecycleService(
    repo=PostgresPartitionRepository(engine),
    metadata=PostgresMetadataProvider(engine),
    locks=PostgresAdvisoryLockManager(engine),
)


async def maintain() -> None:
    plan = await service.plan(config)          # read-only: what would happen, and why
    print(plan.describe())
    result = await PartitionMaintainer(service).run_maintenance_safe(config)
    print(result.created_count, result.detached_count, result.dropped_count, result.issues)
```

`plan.describe()` on a fresh table:

```text
plan for public.events at 2026-08-28T00:00:00+00:00
  CREATE public.events__2026_08 (create_ahead)
  CREATE public.events__2026_09 (create_ahead)
  CREATE public.events__2026_10 (create_ahead)
```

> **Transaction semantics** — every DDL statement runs in its own connection and commits
> immediately. A partition that has a subtree is built detached and attached last, so an
> interrupted run leaves an unreachable table rather than a live partition that rejects
> part of its keyspace. Use `AsyncEngine`, not `AsyncSession`.

## The composed form

The flat fields above are sugar for a **scheme** and a **lifecycle policy**. Spell them out
for anything beyond a time-partitioned root:

```python
from datetime import timedelta

from pg_partsmith import (
    CreateAhead, DropAfter, HashPartitioning, KeepNewest, LifecyclePolicy,
    RangePartitioning, TimeBoundaries, UUIDv7BoundaryCodec,
)

config = TablePartitionConfig(
    table_name="issue_events",
    scheme=RangePartitioning(
        key="id",                                                   # a UUIDv7 column
        boundaries=TimeBoundaries(granularity=PartitionGranularity.WEEK, codec=UUIDv7BoundaryCodec()),
        child=HashPartitioning(key="organization_id", modulus=4),   # each week split by tenant
    ),
    lifecycle=LifecyclePolicy(
        creation=CreateAhead(count=3),
        retention=KeepNewest(count=12),          # twelve weeks, not twelve leaves
        drop=DropAfter(grace=timedelta(days=7)), # detach now, drop a week later
    ),
)
```

```text
issue_events                          PARTITION BY RANGE (id)
├── issue_events__2026_w35            PARTITION BY HASH (organization_id)
│   ├── issue_events__2026_w35__h0    MODULUS 4, REMAINDER 0
│   └── …
└── issue_events__2026_w36 …
```

More shapes, each a one-liner:

```python
# a queue partitioned every 100 000 message ids, keeping ten million behind the newest
RangePartitioning(key="msg_id", boundaries=NumericBoundaries(step=100_000))
LifecyclePolicy(creation=CreateAhead(count=4), retention=KeepBehind(distance=10_000_000))

# a task table hashed for parallel workers: a fixed set, never created ahead, never expired
HashPartitioning(key="task_id", modulus=8)

# partitions through the end of next year, dropped 90 days after their last row could arrive
LifecyclePolicy(creation=CreateUntil(datetime(2028, 1, 1, tzinfo=UTC)), retention=KeepFor(timedelta(days=90)))

# detach when nothing is pending any more, whatever the calendar says
LifecyclePolicy(retention=ExpireIf(AllOf((KeepNewest(count=2),
    SqlPredicate("SELECT NOT EXISTS (SELECT 1 FROM {partition} WHERE status = 'pending')")))))
```

## What maintenance does

1. **Inspect** — one catalog round-trip reads the whole tree (`pg_partition_tree`), the
   marker-tagged detached orphans, and — only when a policy asks — sizes and row estimates.
2. **Plan** — the planner walks the scheme and the tree together. At a `RANGE` level it
   decides which windows must exist ahead of the cursor (the clock, or `max(key)` for an
   integer axis) and which existing ones have expired; at a `HASH`/`LIST` level it fills the
   gaps in the member set. Everything it refuses to do is a **finding** with a reason.
3. **Apply** — under the table's lock, in order: creations (subtree first, attach last),
   re-attachments, detaches (`CONCURRENTLY` where PostgreSQL allows), drops (revalidated by
   OID and ownership marker).

Repeated on a converged table, maintenance issues **zero DDL** — that is an integration
test, not a promise.

## Ownership and safety

- An attached partition whose bounds are a window of the scheme's grid (or lie inside one)
  is a lifecycle partition. One whose bounds are not — a DBA's hand-attached
  `events_archive_2000_2019` — is reported as `unmanaged_partition` and never detached or
  dropped, no matter how old.
- Only tables carrying the library's `COMMENT` marker are ever dropped. The marker is
  written before the `DETACH` and records when it happened, which is what a grace period is
  measured from. Legacy detached tables are adopted with `repo.adopt_partition(...)`.
- A hash set at a modulus the config no longer uses is preserved if complete and repaired
  *at its own modulus* if not; mixed moduli leaving a gap are reported, never guessed at.
- A plan made at 10:00 and applied at 10:05 refuses to drop a table that was recreated in
  between (`PlanStaleError`, reported as an issue).

## Sync usage

Every class in `pg_partsmith.aio` has a synchronous twin in `pg_partsmith.sync` with the
same name and API, built on the classic SQLAlchemy `Engine`:

```python
from sqlalchemy import create_engine

from pg_partsmith.sync import (
    PartitionLifecycleService, PartitionMaintainer,
    PostgresAdvisoryLockManager, PostgresMetadataProvider, PostgresPartitionRepository,
)

engine = create_engine("postgresql+psycopg2://user:pass@host/db")
service = PartitionLifecycleService(
    repo=PostgresPartitionRepository(engine),
    metadata=PostgresMetadataProvider(engine),
    locks=PostgresAdvisoryLockManager(engine),
)
result = PartitionMaintainer(service).run_maintenance_safe(config)
```

Two behavioural differences: `ddl_timeout_seconds` is enforced server-side via
`statement_timeout` per statement, and the Redis lock renews from a background thread.

## Hooks

```python
from pg_partsmith import PartitionEvent
from pg_partsmith.aio import BasePartitionLifecycleHooks


class ColdStorageHooks(BasePartitionLifecycleHooks):
    async def before_drop(self, event: PartitionEvent) -> None:
        await export_to_object_storage(event.partition.name, covering=event.window)
        # raising aborts the drop; retried next tick


service = PartitionLifecycleService(repo, metadata, locks, hooks=[ColdStorageHooks()])
```

Every method takes one `PartitionEvent`: the `phase`, the `config`, the `partition`, the
`window` it covers, and the `operation` being carried out — with the `reason` it was
planned and the size the policy measured, when it asked for one.

| Method | When |
|--------|------|
| `before_create` / `after_create` | around the creation of a partition directly under the root (its subtree included) |
| `before_attach` / `after_attach` | around bringing a detached partition back into the tree |
| `before_detach` / `after_detach` | around a detach |
| `before_drop` / `after_drop` | around a drop — `before_drop` is the last chance to read the data |
| `on_event` | every one of the above, for an audit trail or metrics in one method |

`before_*` exceptions abort that operation; `after_*` exceptions are logged.

## Documentation

[bedrock-python.github.io/pg-partsmith](https://bedrock-python.github.io/pg-partsmith/)

- [Getting started](https://bedrock-python.github.io/pg-partsmith/getting-started/installation/) — install, your first partitioned table, running it in production, a multi-tenant event store
- [Concepts](https://bedrock-python.github.io/pg-partsmith/concepts/overview/) — how it works: schemes, boundaries, lifecycle policies, the plan, ownership, executing DDL, leaf backends
- [How-to guides](https://bedrock-python.github.io/pg-partsmith/guide/configuration/) — scheduling, monitoring, querying, backfilling, partitioning an existing table, migrating from pg_partman, changing a scheme, archiving, foreign keys, cold tiering, troubleshooting, recipes
- [Reference](https://bedrock-python.github.io/pg-partsmith/reference/) — the API, every configuration field, every finding and error
- [Design](https://bedrock-python.github.io/pg-partsmith/design/rfc-0001-partition-schemes/) — RFC 0001, the OSS research, PostgreSQL semantics verified on real servers, and the final report on what 1.0 changed
- [For AI agents](https://bedrock-python.github.io/pg-partsmith/agents/) — the whole API
  surface, the rules that break code when broken and a map of the rest, on one page to hand
  to a coding assistant

## Development

```bash
make install          # uv sync --group dev
make check            # ruff + mypy
make test-unit        # unit tests (no Docker)
make test-integration # integration tests (Docker required)
make test             # all tests with coverage
make docs-serve       # local docs preview
```

See [CONTRIBUTING.md](CONTRIBUTING.md).

## License

[Apache 2.0](LICENSE)
