Repository navigation
Description
Today the library is reachable only from a Python process that can import pg_partsmith and hand it a SQLAlchemy engine. That is the right core, but it means the addressable audience is Python applications — and partition lifecycle is not a Python problem. Go, Ruby, Node and Java services run partitioned PostgreSQL and have the same create-ahead/retention/reconciliation work to do, with no way to use any of this.
Two deliverables, in order: a CLI that exposes the plan/apply cycle over a config file and a DSN, and a container image that runs it as a Kubernetes CronJob, a Docker Compose service, an init container, or a CI/CD maintenance step — without the host application taking a Python dependency at all.
This is an epic. The pieces below are separable and should ship as their own PRs.
The one design constraint that matters
The CLI must expose the library's real semantics, not a convenience wrapper around one use case. Concretely: plan and apply stay separable, with a serialized plan as the artifact between them.
pg-partsmith plan -c partitions.yaml -o plan.json # zero DDL
# read it, diff it, gate it on a human or a CI approval
pg-partsmith apply -c partitions.yaml --plan plan.json
That is the whole reason an operator would trust an external tool to DROP a table, and it is something the library already supports and most partitioning tools do not: every operation is a pydantic model with a reason on it (MaintenancePlan, CreatePartition, DetachPartition, DropPartition in pg_partsmith/plan.py are all BaseModel), so JSON serialization is essentially free, and apply() already revalidates every destructive operation against the catalog before running it — a stale plan cannot drop the wrong relation.
If this ends up as a single pg-partsmith run-everything command, we have built a marketing artifact rather than a tool, and it should not ship.
Part 1 — CLI
What already exists
pg_partsmith/settings.py—PartitionTableSettings(pydantic-settings) already maps env vars onto aTablePartitionConfig, includingscheme/lifecycle/leavesas nested JSON. Single table, one env prefix.- The plan and every operation are pydantic models — serialization and pretty-printing are a formatting question, not a modelling one.
What is missing
- Multi-table configuration. A real deployment maintains several tables in one run.
PartitionTableSettingsdescribes one. Needs a top-level document — a list of table configs plus shared defaults — with the existing settings model as the per-table element rather than a parallel model. - A file format. Env-only does not survive a nested
scheme. TOML is stdlib (tomllib, 3.11+, no dependency); YAML is what operators expect in a Compose file or a ConfigMap but costspyyaml. See the decisions below. - Connection handling. DSN from
--dsn/PG_PARTSMITH_DSN/ the config file, in that precedence. Driver choice for the image (asyncpg vs psycopg) is part 2's problem but the CLI should not care. - Command surface, mapped onto what the library actually does:
inspect— read the real tree from the catalog and print it. No DDL, no config strictly required beyond the table.plan— the maintenance plan, zero DDL, with the reason on each operation and findings surfaced.apply— execute a plan, either freshly computed or read from--plan.validate— config parses, connects, the described scheme is coherent against the catalog. Exits non-zero on a problem. This is the one people put in CI.
- Exit codes, because a CronJob and a CI step read them and nothing else. At minimum: converged/no-op, drift found (for
plan --check), and failure must be distinguishable. Aplan --checkthat exits non-zero on pending operations is what lets someone alert on "maintenance has not been running". - Output formats. Human-readable by default;
--output jsonfor anything that will be piped. The JSON must be the model dump, not a hand-rolled shape that drifts from the library. - Logging to stderr, structured optional, so stdout stays parseable.
Deliberately out of scope
No scheduler of its own. The library's README says "no scheduler" and that stays true — cron, a CronJob, or a CI schedule owns timing. Concurrency between two racing runs is already solved by the advisory lock manager and should simply be on by default in the CLI.
Part 2 — Container image
ghcr.io/bedrock-python/pg-partsmith:<version>, so a non-Python stack can write:
partition-maintenance:
image: ghcr.io/bedrock-python/pg-partsmith:1.1
command: ["maintain", "-c", "/etc/partitions.yaml"]
environment:
PG_PARTSMITH_DSN: postgresql://…
volumes: ["./partitions.yaml:/etc/partitions.yaml:ro"]Requirements:
- Size and footprint are the product here. A Go team evaluating this reads the image size first. Current runtime tree is pydantic (+pydantic-core, annotated-types, typing-extensions), python-dateutil (+six), sqlalchemy (+greenlet, compiled), a driver, and whatever the config format costs. Set a size target before building, and treat a regression in it as a bug.
- Non-root, no shell if practical, pinned base, reproducible.
- Published per release from the existing release workflow, tagged with the exact version and a moving minor tag. Never a
latestthat a CronJob could silently follow across a major. - Security scanning in CI, and a documented answer to "what does this container have permission to do to my database" — it issues DDL, so the docs must state the minimum grants and recommend a dedicated role.
- Both a one-shot mode (CronJob/CI) and an init-container mode (create-only, no destructive operations) — the second matters because running retention at application startup is a bad idea and someone will otherwise do it.
Part 3 — hooks reachable from a config file
Hooks are where the destructive half of this becomes usable. The module docstring names the case itself: "exporting data before a partition is dropped, publishing events to Kafka after a partition is created, or archiving rows before detachment." An operator who cannot run anything before DROP will not point this tool at production. Today hooks require writing a Python class and constructing the service by hand — unreachable from a CLI, and doubly unreachable for the non-Python teams this epic exists to serve.
Two mechanisms, serving different audiences. They are complementary, not alternatives.
3a. Inline Python blocks (the authentik model)
Like authentik's expression policies: a snippet in the config, evaluated with a prepared namespace.
hooks:
before_drop: |
if ctx.partition.row_count > 0:
log.warning("exporting %s before drop", ctx.partition.name)
export_to_s3(ctx.partition.name, ctx.partition.bounds)Expressive, no build step, and the natural fit for the Python-adjacent audience. Notes:
- Raising from a hook already aborts the operation and leaves it for the next run — the semantics exist, they just need documenting at config level.
- Inline blocks get unreadable past a few lines and lose editor support, so a file reference (
before_drop: !file ./hooks/export.py, or a plain path) should work everywhere a block does. validatemust compile every snippet without executing it. ASyntaxErrordiscovered at 03:00 by a CronJob is the failure mode to design out.- Hooks must not fire during
plan.planissues zero DDL and must stay side-effect free, or the artifact-review model in the header is a lie.
3b. Command hooks (the language-neutral one)
hooks:
before_drop:
command: ["/usr/local/bin/archive-partition"]The partition context arrives as JSON on stdin (and/or env vars); a non-zero exit aborts the operation exactly as a raised exception does. This is what a Go or Ruby team actually wants — they already own an archiver, they just need it invoked at the right moment with the right metadata. Given that the whole point of parts 1 and 2 is reaching non-Python stacks, handing that audience a Python snippet and nothing else would miss the target. It also composes with the image: the command lives in a sidecar or a mounted binary, no Python involved.
This forces a decision on #27
The six hooks do not agree on what they receive:
before_create(config: TablePartitionConfig, partition: PartitionInfo)
after_create (config: TablePartitionConfig, partition: PartitionInfo)
before_detach(table_name: str, partition: PartitionInfo)
after_detach (table_name: str, partition_name: str)
before_drop (table_name: str, partition_name: str)
after_drop (table_name: str, partition_name: str)In Python that is an inconvenience. As a config-level contract it is untenable: the variables in scope would silently change per hook, and before_drop — the single most important one, the export-before-destroy case — is the one that gets only a string. A snippet there cannot see the partition's bounds or size without re-querying the catalog by hand.
So exposing hooks through config makes the hook context a public, documented, versioned surface, and it should be one shape for all six. That is #27's Option A (PartitionHookContext), and this epic is the argument that settles it: #27 should be resolved before 3a/3b are implemented, not after, because the alternative is shipping a config contract we immediately have to break.
Worth remembering while designing the context: hooks fire once per lifecycle unit — the partition directly under the root — never per leaf. A snippet author needs that stated plainly, since ctx.partition for a RANGE → HASH table is the week, not the bucket.
Security — state it honestly, do not oversell it
Executing configured code is arbitrary code execution in a process holding DDL credentials. The honest framing:
- The config file already authorizes dropping tables. Code in that same file is not a new privilege boundary as long as the config comes from the same trust domain as the DSN. That is the argument that makes this acceptable, and it is the one to write in the docs.
- It stops holding the moment the config is assembled from somewhere less trusted — a ConfigMap another team can edit, a templated file, anything user-supplied. Say so explicitly.
- Therefore code hooks should be off unless enabled (an explicit flag or config key), so a hardened deployment can prove they are not running.
- No sandboxing claims.
execwith a filtered__builtins__is not a security boundary and is trivially escapable; documenting it as a sandbox would be worse than not having one. authentik does not claim otherwise either. If real isolation is ever wanted, 3b plus a container boundary is the answer, not a restricted namespace.
Versioning — one number for all three
The library, the CLI and the image ship the same version, always. pg-partsmith 1.4.2, pg-partsmith --version → 1.4.2, ghcr.io/bedrock-python/pg-partsmith:1.4.2 contains exactly that. Nobody should ever have to work out which CLI version pairs with which library version, and an image tag should be a complete answer to "what is running".
What this implies, and it settles decision 2 below:
- The CLI ships inside the existing distribution (as an extra for the optional dependencies), not as a separate
pg-partsmith-clipackage. Release Please already manages a single-package manifest (.release-please-manifest.jsonis{".": "…"}); a second distribution means a second version line and the drift this section exists to prevent. Keeping one package makes lockstep the default rather than something to enforce. --versionreadspg_partsmith.__version__. That file is the release-managed source of truth (pg_partsmith/__version__.py, stamped by Release Please). A separate constant for the CLI is exactly how two numbers start disagreeing — there must not be one.- The image is built from the released artifact in the same release workflow, pinned to that exact version rather than to whatever the index serves at build time. It should carry
org.opencontainers.image.versionmatching, so the label, the tag and--versioninside the container cannot disagree. - Every library release produces an image, including patch releases that touch nothing the CLI uses. That is the cost of lockstep and it is worth paying — it is also how base-image CVE patches reach users on a predictable cadence.
One wrinkle to decide: a base-image security rebuild has no library change to hang a version on. Retagging an existing tag is out (a mutable tag under a CronJob is exactly what part 2 says to avoid). The options are a no-op patch release of the library, or an image-only revision suffix on an unchanged semantic version (1.4.2-r1), keeping 1.4.2 itself pointing at the newest revision. The suffix keeps the library changelog honest; the no-op release keeps the "one number" promise absolutely literal.
Why this is worth the maintenance cost
Without it, the projects that can adopt this library are Python projects. With it, any stack can run partition maintenance as a deployment concern. That is a larger and, judging by the OSS survey, more underserved audience than the Python one — several Go and Node projects run partitioned tables with no lifecycle management at all.
It also has to be honest work on its own merits: if the CLI does not stand up as a tool someone would choose without knowing or caring about the Python library behind it, it has failed.
Decisions to make before implementation starts
- Config format — TOML only (stdlib, zero dependency, unfamiliar to k8s operators), YAML only (expected in a ConfigMap, costs
pyyamlin the image), or both with one canonical and the other a convenience? Distribution — extra or separate package?Settled by the versioning section: the extra, in the same distribution. What remains is the extra's name and whether the CLI's own dependencies (a config parser, a driver) are required by it or left to the image.applysafety — should destructive operations require--yes(or a--allow-destructive) when stdin is not a TTY, or is a plan artifact plus the library's revalidation enough?- Driver in the image — asyncpg or psycopg3? Affects size and the async/sync entrypoint choice.
- Scope of the first release — is
inspect/plan/apply/validatethe 1.x surface, or does the first cut shipplan/applyonly and grow? - 3a, 3b, or both — and if both, which ships first? (My read: 3b is more on-mission for the container story, 3a is more useful to the Python audience that exists today.)
- What goes in the snippet namespace — context and a logger only, or also a read-only database handle? A handle makes "skip the drop if rows still match X" possible, which is a real operator need, but it widens the surface considerably and needs its own read-only guarantees.
- Hook failure policy at the run level — does one failing hook abort the whole run or only its own partition? The library isolates per operation today; the CLI needs to say which it does and make it configurable if the answer is "depends".
Order
- Multi-table config model, reusing
PartitionTableSettings. plan+inspect, JSON output, exit codes. No DDL yet — reviewable and testable on its own.applywith--plan, andvalidate.- Resolve Still open after 1.0.0: a construction helper, and what hooks are handed #27 (one hook context for all six hooks), then hooks in config.
- Docs: an operator page, not an API page. What grants it needs, what happens when it fails, how to roll back.
- Release.
- Image, published from that release.
Only after step 6 is any of this usable as an argument to another project — an upstream proposal should depend on a published version, never a VCS reference.
Activity
AlexeyShalaev commentedon Sep 1, 2026
Parts 1, 2 and 3b are implemented, as a stack of seven PRs into
feat/cli-and-container: #33 → #34 → #35 → #36 → #37 → #38 → #39. Each is a reviewable unit; the epic branch is the integration target and nothing has gone nearmaster.The blocker in the header is gone
The epic says #27 must be resolved before 3a/3b, or we ship a config contract we immediately have to break. That already happened in 1.1: Option A shipped — one
PartitionEventfor all eight phases (before_attach/after_attachwere added too), withon_eventas a catch-all and pre-1.1 hook signatures refused at wiring time rather than at first fire.Two consequences the plan above did not anticipate:
event.model_dump_json(by_alias=True)— no context design at all. feat: a command at every lifecycle moment, for teams that write no Python #39 is the whole feature.Two more things the plan assumed that turned out not to hold:
planis not free of configured code. ASqlPredicatein a retention rule is executed while planning. Read-only, but it is the operator's statement running with DDL credentials, and the security section should say so rather than only "hooks do not fire during plan" (which is true, and now tested).apply()was the one that configuration produced — reachable the moment a plan is a file and a document describes several tables. feat: refuse a plan the configuration did not produce #33 fixes it; that is why it is first.Decisions, as taken
schemereads badly in TOML. The document model is the contract, not the syntax.cli, in the same distribution. It carries PyYAML and asyncpg:pip install "pg-partsmith[cli]"that cannot connect to anything is not an install.applysafety — not TTY-gated: a container has no TTY, so that gate is either meaningless or dangerous. Insteadapplywithholds every destructive operation unless--allow-destructive. This collapses part 2's two modes into one flag — the init container is justapplywith nothing extra.postgresql://is upgraded to it automatically; a DSN naming its own driver is left alone.inspect/plan/validateshipped as one PR (feat: a command line for the read-only half #36) andapplyas the next (feat: apply, and the artifact between plan and apply #37), so the read-only half is reviewable and deployable on its own.PG_PARTSMITH_*variables; no database handle, because "read-only" is not something a connection with DDL rights can promise.continue_on_erroralready decides run-level abort versus per-partition isolation; the CLI just exposes it.Exit codes
0converged ·2drift underplan --check·3findings or run issues ·4configuration ·5connection ·6lock held ·1unexpected.3outranks2deliberately: drift is what a run fixes, a finding is what it cannot. And6is not a failure — two runs overlapping is ordinary operation, and reporting it as an error is the first false page every deployment gets.Image
244 MB on
python:3.13-slim, budget 280 MB, checked on every PR with a regression failing the build. Alpine would be roughly half that and I did not take it: the suite runs on glibc, and shipping operators a musl build nothing in CI exercises is not worth the megabytes. Tags are the exact version and a moving minor, neverlatest; CI refuses to publish an image whose--versiondisagrees with its tag.The base-image-rebuild wrinkle (
1.4.2-r1versus a no-op release) is not decided — nothing needs it until the first CVE, but it should be settled before then. My read: the suffix, since a no-op release pollutes the changelog and PyPI and needs an empty-commit dance in Release Please every time.Not done
--output metrics(node_exporter textfile — the OSS survey says most of these projects have no partition monitoring at all, and this is a CronJob away from having some), andplan --sqlto print the DDL, which is what gets a change past a review board. The second needs a render/execute split in the repository layer, so its cost should be measured before it is promised.Every PR is green locally: 2630 unit tests, 550 integration tests against real PostgreSQL, ruff and mypy clean.
AlexeyShalaev commentedon Sep 1, 2026
Three more PRs on the same stack, after #39: #40 → #41 → #42. With them every part of the epic is implemented, and the two things I said I would measure before promising are settled.
#40 —
--output metricsNot in the epic. Prometheus text exposition from any command, for a node_exporter textfile collector: pending operations by kind and findings by severity from
plan, the tree size and the age of the oldest orphan frominspect,config_validfromvalidate, what was done fromapply. All gauges (a one-shot job cannot own a counter), a run timestamp so a stale file reads as stale, zeroes rather than nothing for a converged table. The numbers come off the same envelope the JSON does, so they cannot disagree with it.#41 — what a plan will lock, and why there is no
--sqlcapabilities(the heaviest lock, and whether the operation can run in a transaction block) andis_destructiveare now serialized on every operation, so a saved plan is reviewable for its locks without the CLI;plan --locksprints the same for a person.--sqlis deliberately not offered, and this is the measured answer rather than the guessed one: the DDL is built at execution time from decisions only made then — aDETACH CONCURRENTLYfalling back to the blocking form because a DEFAULT sibling exists, rows moved out of a DEFAULT partition for a new window, which orphan marker gets cleared, the lock timeout and retry loop around a drop. A faithful renderer means a render/execute split acrosscreator.pyandremover.pyand still cannot pre-render the runtime branches; a "representative" one would be read as a transcript in exactly the cases a review exists to catch. The plan is the contract: what, why, how big, what it locks.#42 — 3a, scoped to hooks
A phase takes a block of Python (
python, orpython_filerelative to the document) witheventandlogin scope; raising refuses. All four of the epic's notes on 3a are done: raising-aborts is documented and tested against a realDROP; file references work (a plain key, not a YAML tag, so JSON gets it too); every block is compiled byvalidate— inline ones the moment the document validates, file-backed ones before any connection is opened; and nothing fires duringplan. It sits behind the existing--allow-hooks, because a Python hook is a hook and the trust argument is the same one. No sandbox is claimed, and the docs say why claiming one would be worse than having none.Retention predicates as Python are not in it, on purpose: they would run during
plan, which is a different gate and a different promise about whatplanmay do. The compile/namespace machinery is what they would reuse.Decisions 6 and 7, updated
SqlPredicatealready answers "skip the drop if rows still match X", on the plan side where it belongs, and "read-only" is not something a connection with DDL rights can promise.Still open
Only the
-r1image-revision scheme, which needs deciding before the first base-image CVE and not before.Every branch is green locally (2664 unit tests, 551 integration on the branch before #42; #42's own integration run is in flight).
Merge pull request #43 from bedrock-python/feat/cli-and-container