diff --git a/README.md b/README.md index c721e08..9e42c29 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,8 @@ A production-grade Python library for [CockroachDB](https://www.cockroachlabs.com/) that provides automatic transaction retry handling, multi-region support, follower reads, CDC webhook handlers, vector search, and RAG pipelines. Part of the CockroachDB language-specific library family alongside the [Java Spring Boot Starter](https://github.com/cockroachlabs/cockroachdb-java-library), [.NET Library](https://github.com/cockroachlabs/cockroachdb-dotnet-library), and [Go Library](https://github.com/cockroachlabs/cockroachdb-go-library). +> **Using an AI coding agent?** A consumer guide for agents working in your app ships inside the installed package at `cockroachdb/AGENTS.md` (source: [`docs/agents/AGENTS.md`](docs/agents/AGENTS.md)) — it tells the agent which helpers to use and what not to hand-roll. + ## Architecture
diff --git a/docs/agents/AGENTS.md b/docs/agents/AGENTS.md new file mode 100644 index 0000000..cd991ab --- /dev/null +++ b/docs/agents/AGENTS.md @@ -0,0 +1,54 @@ +# CockroachDB Python Library — guide for coding agents + +You are editing a Python app that depends on the `cockroachdb` libraries. This library +already solves the hard CockroachDB-specific problems. Use its helpers; do not re-implement +them. Exact APIs and options live in the [README](../../README.md). + +## Already handled — do NOT rebuild + +- **Serialization retry (SQLSTATE `40001`)** is automatic. Wrap writes with `@crdb_retry` + (sync or async), or run them through `CockroachDBTemplate.transaction(...)` / + `CockroachDBSession`. Never hand-roll a retry loop or `while`/`except` on `40001`. +- **Multi-region topology check** runs at startup and validates `@global_table` / + `@regional_by_row` usage — don't reinvent it. If it blocks startup incorrectly, set the + region-check mode to `none` rather than deleting annotations. +- **Metrics, Continuum, and CDC plumbing** are provided. Don't write Prometheus wiring or a + changefeed webhook server by hand. + +## Which helper for each job + +| Job | Use | +|-----|-----| +| Auto-retry a write | `@crdb_retry(max_retries=...)` or `CockroachDBTemplate.transaction()` / `CockroachDBSession` | +| Stale read off nearest replica | `@follower_read(seconds_ago=...)` or `with FollowerReadContext.scoped(...)` | +| Pin work to a region | `@crdb_region("us-east1")`; scope with `RegionContext` | +| Regional-by-row / global tables | `@regional_by_row(default_region=...)`, `@global_table` | +| CDC webhook | `@changefeed_handler(table=..., operations=[...])` + `create_changefeed_router()` | +| Vector search / RAG | `@vector_search(...)`, `VectorSearchTemplate`, `RagPipeline`, `CockroachDBVectorStore` (`cockroachdb.ai`) | +| Cloud / MCP / Aegis | `make_cloud`, `make_mcp`, `McpAegisClient` (`cockroachdb.continuum`) | + +Homing a row to a region = writing the **`crdb_region` COLUMN** on the row (the decorators and +`RegionContext` do this). There is **no `SET crdb_region` session variable** — never emit it. + +## Config that matters + +Everything is `CockroachDBConfig` (Pydantic), overridable via `CRDB_`-prefixed env vars: +`CRDB_RETRY__MAX_RETRIES`, `CRDB_REGION__DEFAULT_REGION`, +`CRDB_REGION__REGION_HEADER` (default `X-CockroachDB-Region`, read by `CockroachDBMiddleware`), +`CRDB_FOLLOWER_READ__ENABLED`. See the README Configuration table. + +## Anti-patterns (don't do these) + +- Hand-rolled `40001` retry loops — the library owns this. +- Raw `SET crdb_region ...` — not a real session var; set the `crdb_region` column instead. +- Writing changefeed webhook plumbing by hand — use `@changefeed_handler` / the CDC router. +- Running transactions at **READ COMMITTED** so `40001` never surfaces and retry silently + no-ops — CockroachDB retry correctness assumes SERIALIZABLE. +- AI vector: `ensure_table()` runs DDL and needs **autocommit**; and do not open a result + reader/cursor and then `commit()` the same transaction — read fully (or use a separate + connection) first. + +## Testing + +Use `cockroachdb-testing`: `CockroachDBFixture` (Testcontainers-backed real CockroachDB) and +`RetrySimulator` (injects `40001` failures to prove retry works). Don't mock the driver. diff --git a/examples/ideas-board/README.md b/examples/ideas-board/README.md index aa77d2f..043c5eb 100644 --- a/examples/ideas-board/README.md +++ b/examples/ideas-board/README.md @@ -46,12 +46,12 @@ source .venv/bin/activate pip install -r requirements.txt ``` -`requirements.txt` pins the **published** `cockroachdb==0.1.2` (plus +`requirements.txt` pins the **published** `cockroachdb==0.1.3` (plus `cockroachdb-testing==0.1.1`) and carries the `--extra-index-url` line for the feed. A single-package install looks like: ```bash -pip install 'cockroachdb==0.1.2' \ +pip install 'cockroachdb==0.1.3' \ --extra-index-url https://cockroachlabs.github.io/cockroachdb-python-library/simple/ ``` diff --git a/examples/ideas-board/requirements.txt b/examples/ideas-board/requirements.txt index 4116d79..37763e7 100644 --- a/examples/ideas-board/requirements.txt +++ b/examples/ideas-board/requirements.txt @@ -4,7 +4,7 @@ # anonymous PEP 503 feed, NOT public PyPI. --extra-index-url https://cockroachlabs.github.io/cockroachdb-python-library/simple/ -cockroachdb==0.1.2 +cockroachdb==0.1.3 cockroachdb-core==0.3.0 # metrics (RetryEngine) + follower-read/region context cockroachdb-sqlalchemy==0.3.0 # multi-region schema check (verify_multiregion_schema + ORM mixins); pulls sqlalchemy>=2.0 cockroachdb-cdc==0.2.0 # changefeed handlers + webhook payload parsing diff --git a/packages/cockroachdb/pyproject.toml b/packages/cockroachdb/pyproject.toml index 7eaa128..c908b48 100644 --- a/packages/cockroachdb/pyproject.toml +++ b/packages/cockroachdb/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "cockroachdb" -version = "0.1.2" +version = "0.1.3" description = "CockroachDB Python Library — base decorators, types, and configuration" readme = "README.md" requires-python = ">=3.11" @@ -32,3 +32,13 @@ dev = [ [tool.hatch.build.targets.wheel] packages = ["src/cockroachdb"] + +# Bake the consumer-facing agent guide into the installed package so it lands at +# cockroachdb/AGENTS.md (readable via importlib.resources). Single source of truth +# is the shared docs/agents/AGENTS.md at the repo root. The sdist pulls it into the +# package dir; the wheel (built from the sdist by `uv build`) then includes it +# automatically alongside the package's .py files. (A wheel-level force-include +# can't be used here: it would have to reference a path valid only in the sdist, +# which breaks editable/source wheel builds used by `uv sync`.) +[tool.hatch.build.targets.sdist.force-include] +"../../docs/agents/AGENTS.md" = "src/cockroachdb/AGENTS.md" diff --git a/tests/test_agents_md_packaged.py b/tests/test_agents_md_packaged.py new file mode 100644 index 0000000..2f5a4d8 --- /dev/null +++ b/tests/test_agents_md_packaged.py @@ -0,0 +1,37 @@ +"""Teeth test: the consumer AGENTS.md is baked into the base `cockroachdb` wheel. + +The file is injected at wheel-build time via force-include in +packages/cockroachdb/pyproject.toml, so an editable `uv sync` install does not +expose it — we build the wheel and inspect it directly. Fails if the guide is +missing or empty (i.e. the force-include regressed). +""" + +from __future__ import annotations + +import shutil +import subprocess +import zipfile +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).resolve().parent.parent +BASE_PKG = REPO_ROOT / "packages" / "cockroachdb" + + +@pytest.mark.skipif(shutil.which("uv") is None, reason="uv required to build the wheel") +def test_agents_md_packaged_in_base_wheel(tmp_path: Path) -> None: + subprocess.run( + ["uv", "build", "-o", str(tmp_path)], + cwd=BASE_PKG, + check=True, + capture_output=True, + ) + wheels = list(tmp_path.glob("cockroachdb-*.whl")) + assert wheels, "no base cockroachdb wheel was built" + + with zipfile.ZipFile(wheels[0]) as zf: + assert "cockroachdb/AGENTS.md" in zf.namelist(), ( + "AGENTS.md missing from wheel — force-include regressed" + ) + assert zf.getinfo("cockroachdb/AGENTS.md").file_size > 0, "AGENTS.md is empty"