render-lab-tasks-render-postgres 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. render_lab_tasks_render_postgres-0.1.0/.gitignore +11 -0
  2. render_lab_tasks_render_postgres-0.1.0/LICENSE +21 -0
  3. render_lab_tasks_render_postgres-0.1.0/PKG-INFO +54 -0
  4. render_lab_tasks_render_postgres-0.1.0/README.md +41 -0
  5. render_lab_tasks_render_postgres-0.1.0/pyproject.toml +22 -0
  6. render_lab_tasks_render_postgres-0.1.0/src/render_lab_tasks_render_postgres/__init__.py +1 -0
  7. render_lab_tasks_render_postgres-0.1.0/src/render_lab_tasks_render_postgres/_app.py +3 -0
  8. render_lab_tasks_render_postgres-0.1.0/src/render_lab_tasks_render_postgres/client.py +250 -0
  9. render_lab_tasks_render_postgres-0.1.0/src/render_lab_tasks_render_postgres/database.py +92 -0
  10. render_lab_tasks_render_postgres-0.1.0/src/render_lab_tasks_render_postgres/delete_vectors.py +18 -0
  11. render_lab_tasks_render_postgres-0.1.0/src/render_lab_tasks_render_postgres/execute.py +18 -0
  12. render_lab_tasks_render_postgres-0.1.0/src/render_lab_tasks_render_postgres/migrate.py +18 -0
  13. render_lab_tasks_render_postgres-0.1.0/src/render_lab_tasks_render_postgres/py.typed +0 -0
  14. render_lab_tasks_render_postgres-0.1.0/src/render_lab_tasks_render_postgres/query.py +18 -0
  15. render_lab_tasks_render_postgres-0.1.0/src/render_lab_tasks_render_postgres/retry.py +3 -0
  16. render_lab_tasks_render_postgres-0.1.0/src/render_lab_tasks_render_postgres/search_vectors.py +18 -0
  17. render_lab_tasks_render_postgres-0.1.0/src/render_lab_tasks_render_postgres/setup_vector_store.py +20 -0
  18. render_lab_tasks_render_postgres-0.1.0/src/render_lab_tasks_render_postgres/tasks.py +32 -0
  19. render_lab_tasks_render_postgres-0.1.0/src/render_lab_tasks_render_postgres/transaction.py +18 -0
  20. render_lab_tasks_render_postgres-0.1.0/src/render_lab_tasks_render_postgres/types.py +123 -0
  21. render_lab_tasks_render_postgres-0.1.0/src/render_lab_tasks_render_postgres/upsert.py +18 -0
  22. render_lab_tasks_render_postgres-0.1.0/src/render_lab_tasks_render_postgres/upsert_vectors.py +18 -0
  23. render_lab_tasks_render_postgres-0.1.0/tests/test_contract.py +125 -0
@@ -0,0 +1,11 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.py[cod]
4
+ .pytest_cache/
5
+ .mypy_cache/
6
+ .ruff_cache/
7
+ dist/
8
+ *.egg-info/
9
+ .env
10
+ .env.*
11
+ !.env.example
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Render Lab
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,54 @@
1
+ Metadata-Version: 2.5
2
+ Name: render-lab-tasks-render-postgres
3
+ Version: 0.1.0
4
+ Summary: render-postgres tasks for Render Workflows
5
+ Project-URL: Repository, https://github.com/render-lab/render-tasks-python
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.12
9
+ Requires-Dist: psycopg[binary]<4,>=3.2
10
+ Requires-Dist: render-lab-tasks-core<0.2,>=0.1.1
11
+ Requires-Dist: render==1.0.1
12
+ Description-Content-Type: text/markdown
13
+
14
+ # render-lab-tasks-render-postgres
15
+
16
+ Nine tasks: `postgres.query`, `execute`, `upsert`, `transaction`, `migrate`,
17
+ `setupVectorStore`, `upsertVectors`, `searchVectors`, and `deleteVectors`.
18
+ Import `render_lab_tasks_render_postgres.tasks` for explicit registration.
19
+ Each operation exports an injectable async `*_impl(ctx, input, *, deps=...)`.
20
+
21
+ Environment, read at first use:
22
+
23
+ | Variable | Meaning |
24
+ | --- | --- |
25
+ | DATABASE_URL | PostgreSQL URL, required; linked Render Postgres private URL is supported |
26
+ | DATABASE_SSL | `true`/`require` verifies TLS certificates, `no-verify` encrypts without verification; unset uses URL/driver options |
27
+
28
+ The async psycopg driver uses native `$1` positional placeholders. Each invocation
29
+ closes its connection. Transactions roll back on exceptions and cancellation;
30
+ there are no driver retries. Durable tasks retry three times with 1s exponential
31
+ backoff. Arbitrary SQL writes can repeat after an ambiguous commit failure.
32
+
33
+ Generated upserts validate and quote identifiers, an intentional tightening from
34
+ TypeScript's trusted-identifier interpolation. Schema-qualified table names are
35
+ not accepted by generated operations; use explicit SQL in query/execute instead.
36
+ Vector operations preserve the canonical id/content/metadata/embedding schema,
37
+ finite-vector validation, bounded search limits, and guarded delete selectors.
38
+
39
+ Migration SQL and ledger inserts run in one transaction. Concurrent callers can
40
+ race on the ledger read; PostgreSQL rolls back the losing transaction. Migration
41
+ names must be unique. DDL requiring autocommit (such as CREATE INDEX CONCURRENTLY)
42
+ does not belong in a migration transaction.
43
+
44
+ Results are JSON values: decimal/UUID values become strings, dates/times ISO
45
+ strings, and binary values become Node-compatible Buffer-shaped JSON. Unknown
46
+ custom driver objects and non-finite floats fail instead of escaping the task.
47
+ These mappings intentionally define Python serialization where raw node-postgres
48
+ objects were ambiguous. Live Postgres/pgvector/TLS checks remain in the backlog.
49
+
50
+ ## Installation
51
+
52
+ ```sh
53
+ pip install render-lab-tasks-render-postgres==0.1.0
54
+ ```
@@ -0,0 +1,41 @@
1
+ # render-lab-tasks-render-postgres
2
+
3
+ Nine tasks: `postgres.query`, `execute`, `upsert`, `transaction`, `migrate`,
4
+ `setupVectorStore`, `upsertVectors`, `searchVectors`, and `deleteVectors`.
5
+ Import `render_lab_tasks_render_postgres.tasks` for explicit registration.
6
+ Each operation exports an injectable async `*_impl(ctx, input, *, deps=...)`.
7
+
8
+ Environment, read at first use:
9
+
10
+ | Variable | Meaning |
11
+ | --- | --- |
12
+ | DATABASE_URL | PostgreSQL URL, required; linked Render Postgres private URL is supported |
13
+ | DATABASE_SSL | `true`/`require` verifies TLS certificates, `no-verify` encrypts without verification; unset uses URL/driver options |
14
+
15
+ The async psycopg driver uses native `$1` positional placeholders. Each invocation
16
+ closes its connection. Transactions roll back on exceptions and cancellation;
17
+ there are no driver retries. Durable tasks retry three times with 1s exponential
18
+ backoff. Arbitrary SQL writes can repeat after an ambiguous commit failure.
19
+
20
+ Generated upserts validate and quote identifiers, an intentional tightening from
21
+ TypeScript's trusted-identifier interpolation. Schema-qualified table names are
22
+ not accepted by generated operations; use explicit SQL in query/execute instead.
23
+ Vector operations preserve the canonical id/content/metadata/embedding schema,
24
+ finite-vector validation, bounded search limits, and guarded delete selectors.
25
+
26
+ Migration SQL and ledger inserts run in one transaction. Concurrent callers can
27
+ race on the ledger read; PostgreSQL rolls back the losing transaction. Migration
28
+ names must be unique. DDL requiring autocommit (such as CREATE INDEX CONCURRENTLY)
29
+ does not belong in a migration transaction.
30
+
31
+ Results are JSON values: decimal/UUID values become strings, dates/times ISO
32
+ strings, and binary values become Node-compatible Buffer-shaped JSON. Unknown
33
+ custom driver objects and non-finite floats fail instead of escaping the task.
34
+ These mappings intentionally define Python serialization where raw node-postgres
35
+ objects were ambiguous. Live Postgres/pgvector/TLS checks remain in the backlog.
36
+
37
+ ## Installation
38
+
39
+ ```sh
40
+ pip install render-lab-tasks-render-postgres==0.1.0
41
+ ```
@@ -0,0 +1,22 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27,<2"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "render-lab-tasks-render-postgres"
7
+ version = "0.1.0"
8
+ description = "render-postgres tasks for Render Workflows"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.12"
13
+ dependencies = ["render==1.0.1", "psycopg[binary]>=3.2,<4", "render-lab-tasks-core>=0.1.1,<0.2"]
14
+
15
+ [project.urls]
16
+ Repository = "https://github.com/render-lab/render-tasks-python"
17
+
18
+ [tool.uv.sources]
19
+ render-lab-tasks-core = { workspace = true }
20
+
21
+ [tool.hatch.build.targets.wheel]
22
+ packages = ["src/render_lab_tasks_render_postgres"]
@@ -0,0 +1 @@
1
+ """Import .tasks explicitly to register durable tasks."""
@@ -0,0 +1,3 @@
1
+ from render import Workflows
2
+
3
+ app = Workflows()
@@ -0,0 +1,250 @@
1
+ """Injected vendor interface and one-attempt async HTTP adapter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import re
8
+ from collections.abc import AsyncIterator
9
+ from contextlib import asynccontextmanager
10
+ from dataclasses import dataclass
11
+ from typing import Any, Protocol, cast
12
+
13
+ from render_lab_tasks_core.http import (
14
+ js_string,
15
+ nullish,
16
+ )
17
+
18
+ from . import types as t
19
+ from .database import DatabasePort, connect_database
20
+
21
+
22
+ def compact_json(value: Any) -> str:
23
+ return json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":"))
24
+
25
+
26
+ def quote_ident(name: str) -> str:
27
+ if not re.fullmatch(r"[a-zA-Z_][a-zA-Z0-9_]{0,62}", name):
28
+ raise ValueError(
29
+ f'Invalid SQL identifier "{name}": must match '
30
+ "/^[a-zA-Z_][a-zA-Z0-9_]{0,62}$/ "
31
+ "(letters, digits, underscore; not starting with a digit; max 63 chars)."
32
+ )
33
+ return f'"{name}"'
34
+
35
+
36
+ def vector_literal(values: list[float]) -> str:
37
+ if not values or any(
38
+ isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v)
39
+ for v in values
40
+ ):
41
+ raise ValueError("embedding must be a non-empty array of finite numbers")
42
+ return "[" + ",".join(js_string(v) for v in values) + "]"
43
+
44
+
45
+ class Port(Protocol):
46
+ async def delete_vectors(self, input: t.DeleteVectorsInput) -> t.DeleteVectorsResult: ...
47
+ async def execute(self, input: t.ExecuteInput) -> t.ExecuteResult: ...
48
+ async def migrate(self, input: t.MigrateInput) -> t.MigrateResult: ...
49
+ async def query(self, input: t.QueryInput) -> t.QueryResult: ...
50
+ async def search_vectors(self, input: t.SearchVectorsInput) -> t.SearchVectorsResult: ...
51
+ async def setup_vector_store(
52
+ self, input: t.SetupVectorStoreInput
53
+ ) -> t.SetupVectorStoreResult: ...
54
+ async def transaction(self, input: t.TransactionInput) -> t.TransactionResult: ...
55
+ async def upsert(self, input: t.UpsertInput) -> t.UpsertResult: ...
56
+ async def upsert_vectors(self, input: t.UpsertVectorsInput) -> t.UpsertVectorsResult: ...
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class Deps:
61
+ render_postgres: Port
62
+
63
+
64
+ class Client:
65
+ def __init__(self, db: DatabasePort) -> None:
66
+ self.db = db
67
+
68
+ async def query(self, input: t.QueryInput) -> t.QueryResult:
69
+ return await self.db.query(input["sql"], input.get("params"))
70
+
71
+ async def execute(self, input: t.ExecuteInput) -> t.ExecuteResult:
72
+ result = await self.db.query(input["sql"], input.get("params"))
73
+ return {"rowCount": result["rowCount"]}
74
+
75
+ async def transaction(self, input: t.TransactionInput) -> t.TransactionResult:
76
+ return await self.db.batch(input["statements"])
77
+
78
+ async def upsert(self, input: t.UpsertInput) -> t.UpsertResult:
79
+ if not input["rows"] or not input["rows"][0]:
80
+ return {"rowCount": 0}
81
+ columns = list(input["rows"][0])
82
+ table = quote_ident(input["table"])
83
+ quoted = {column: quote_ident(column) for column in columns}
84
+ values: list[Any] = []
85
+ tuples = []
86
+ for row in input["rows"]:
87
+ placeholders = []
88
+ for column in columns:
89
+ values.append(row.get(column))
90
+ placeholders.append(f"${len(values)}")
91
+ tuples.append("(" + ", ".join(placeholders) + ")")
92
+ updates = input.get(
93
+ "updateColumns", [c for c in columns if c not in input["conflictColumns"]]
94
+ )
95
+ conflict = "(" + ", ".join(quote_ident(c) for c in input["conflictColumns"]) + ")"
96
+ action = (
97
+ "DO NOTHING"
98
+ if not updates
99
+ else "DO UPDATE SET "
100
+ + ", ".join(f"{quote_ident(c)} = EXCLUDED.{quote_ident(c)}" for c in updates)
101
+ )
102
+ sql = (
103
+ f"INSERT INTO {table} ({', '.join(quoted.values())}) "
104
+ f"VALUES {', '.join(tuples)} ON CONFLICT {conflict} {action}"
105
+ )
106
+ return {"rowCount": (await self.db.query(sql, values))["rowCount"]}
107
+
108
+ async def migrate(self, input: t.MigrateInput) -> t.MigrateResult:
109
+ await self.db.query(
110
+ "CREATE TABLE IF NOT EXISTS _render_migrations "
111
+ "(name text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())"
112
+ )
113
+ rows = (await self.db.query("SELECT name FROM _render_migrations"))["rows"]
114
+ applied = {str(r["name"]) for r in rows}
115
+ pending = [m for m in input["migrations"] if m["name"] not in applied]
116
+ if not pending:
117
+ return {"applied": []}
118
+ statements: list[t.Statement] = []
119
+ for migration in pending:
120
+ statements.extend(
121
+ [
122
+ {"sql": migration["sql"]},
123
+ {
124
+ "sql": "INSERT INTO _render_migrations (name) VALUES ($1)",
125
+ "params": [migration["name"]],
126
+ },
127
+ ]
128
+ )
129
+ await self.db.batch(statements)
130
+ return {"applied": [m["name"] for m in pending]}
131
+
132
+ async def setup_vector_store(self, input: t.SetupVectorStoreInput) -> t.SetupVectorStoreResult:
133
+ table = quote_ident(input["table"])
134
+ dims = input["dimensions"]
135
+ if (
136
+ isinstance(dims, bool)
137
+ or not math.isfinite(dims)
138
+ or int(dims) != dims
139
+ or not 1 <= dims <= 16000
140
+ ):
141
+ raise ValueError(
142
+ f"dimensions must be an integer between 1 and 16000 (pgvector's limit), got {dims}"
143
+ )
144
+ index = nullish(input.get("index"), "hnsw")
145
+ if index not in ("hnsw", "ivfflat", "none"):
146
+ raise ValueError(f'index must be "hnsw", "ivfflat", or "none", got "{index}"')
147
+ index_name = quote_ident(input["table"][:49] + "_embedding_idx")
148
+
149
+ async def exists(quoted: str) -> bool:
150
+ rows = (await self.db.query("SELECT to_regclass($1) AS r", [quoted]))["rows"]
151
+ return bool(rows and rows[0].get("r") is not None)
152
+
153
+ await self.db.query("CREATE EXTENSION IF NOT EXISTS vector")
154
+ table_existed = await exists(table)
155
+ await self.db.query(
156
+ f"CREATE TABLE IF NOT EXISTS {table} ("
157
+ "id text PRIMARY KEY, content text, metadata jsonb, "
158
+ f"embedding vector({int(dims)}) NOT NULL, "
159
+ "created_at timestamptz NOT NULL DEFAULT now(), "
160
+ "updated_at timestamptz NOT NULL DEFAULT now())"
161
+ )
162
+ index_created = False
163
+ if index != "none":
164
+ index_existed = await exists(index_name)
165
+ await self.db.query(
166
+ f"CREATE INDEX IF NOT EXISTS {index_name} ON {table} "
167
+ f"USING {index} (embedding vector_cosine_ops)"
168
+ )
169
+ index_created = not index_existed
170
+ return {
171
+ "table": input["table"],
172
+ "extensionReady": True,
173
+ "tableCreated": not table_existed,
174
+ "indexCreated": index_created,
175
+ }
176
+
177
+ async def upsert_vectors(self, input: t.UpsertVectorsInput) -> t.UpsertVectorsResult:
178
+ table = quote_ident(input["table"])
179
+ if not input["rows"]:
180
+ return {"table": input["table"], "upserted": 0}
181
+ literals = [vector_literal(r["embedding"]) for r in input["rows"]]
182
+ sql = (
183
+ f"INSERT INTO {table} (id, content, metadata, embedding, updated_at) "
184
+ "VALUES ($1, $2, $3::jsonb, $4::vector, now()) "
185
+ "ON CONFLICT (id) DO UPDATE SET "
186
+ "content = EXCLUDED.content, metadata = EXCLUDED.metadata, "
187
+ "embedding = EXCLUDED.embedding, updated_at = now()"
188
+ )
189
+ statements: list[t.Statement] = [
190
+ {"sql": sql, "params": [r["id"], r.get("content"), r.get("metadata"), literal]}
191
+ for r, literal in zip(input["rows"], literals, strict=True)
192
+ ]
193
+ counts = (await self.db.batch(statements))["rowCounts"]
194
+ return {"table": input["table"], "upserted": sum(counts)}
195
+
196
+ async def search_vectors(self, input: t.SearchVectorsInput) -> t.SearchVectorsResult:
197
+ table = quote_ident(input["table"])
198
+ literal = vector_literal(input["embedding"])
199
+ limit = min(max(math.floor(nullish(input.get("limit"), 10)), 1), 1000)
200
+ serialized_filter = None
201
+ if "filter" in input:
202
+ if not input["filter"]:
203
+ raise ValueError(
204
+ "searchVectors: `filter` must contain at least one defined value "
205
+ "(an empty filter would match every row — omit `filter` to search unfiltered)"
206
+ )
207
+ serialized_filter = compact_json(input["filter"])
208
+ sql = (
209
+ "SELECT id, content, metadata, 1 - (embedding <=> $1::vector) AS similarity "
210
+ f"FROM {table} WHERE ($2::jsonb IS NULL OR metadata @> $2::jsonb) "
211
+ "AND ($3::float8 IS NULL OR (embedding <=> $1::vector) <= $3) "
212
+ "ORDER BY embedding <=> $1::vector LIMIT $4"
213
+ )
214
+ rows = (
215
+ await self.db.query(sql, [literal, serialized_filter, input.get("maxDistance"), limit])
216
+ )["rows"]
217
+ return {"rows": cast(list[t.VectorSearchRow], rows)}
218
+
219
+ async def delete_vectors(self, input: t.DeleteVectorsInput) -> t.DeleteVectorsResult:
220
+ table = quote_ident(input["table"])
221
+ if ("ids" in input) == ("filter" in input):
222
+ raise ValueError("deleteVectors requires exactly one of `ids` or `filter`")
223
+ if "ids" in input:
224
+ if not input["ids"]:
225
+ raise ValueError("deleteVectors: `ids` must be non-empty")
226
+ result = await self.db.query(f"DELETE FROM {table} WHERE id = ANY($1)", [input["ids"]])
227
+ else:
228
+ if not input["filter"]:
229
+ raise ValueError(
230
+ "deleteVectors: `filter` must contain at least one defined value "
231
+ "(an empty filter would delete every row)"
232
+ )
233
+ result = await self.db.query(
234
+ f"DELETE FROM {table} WHERE metadata @> $1::jsonb", [compact_json(input["filter"])]
235
+ )
236
+ return {"table": input["table"], "deleted": result["rowCount"]}
237
+
238
+
239
+ @asynccontextmanager
240
+ async def dependencies(deps: Deps | None) -> AsyncIterator[Deps]:
241
+ if deps is not None:
242
+ yield deps
243
+ else:
244
+ async with connect_database() as db:
245
+ yield Deps(render_postgres=Client(db))
246
+
247
+
248
+ RenderPostgresPort = Port
249
+ RenderPostgresClient = Client
250
+ RenderPostgresDeps = Deps
@@ -0,0 +1,92 @@
1
+ """Async PostgreSQL driver with native $1 placeholders and explicit transactions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import os
7
+ from collections.abc import AsyncIterator
8
+ from contextlib import asynccontextmanager
9
+ from datetime import date, datetime, time
10
+ from decimal import Decimal
11
+ from typing import Any, Protocol
12
+ from uuid import UUID
13
+
14
+ from psycopg import AsyncConnection, AsyncRawCursor
15
+ from psycopg.rows import dict_row
16
+ from psycopg.types.json import Jsonb
17
+
18
+ from . import types as t
19
+
20
+
21
+ class DatabasePort(Protocol):
22
+ async def query(self, sql: str, params: list[Any] | None = None) -> t.QueryResult: ...
23
+ async def batch(self, statements: list[t.Statement]) -> t.TransactionResult: ...
24
+
25
+
26
+ def json_value(value: Any) -> Any:
27
+ if value is None or isinstance(value, (str, bool, int)):
28
+ return value
29
+ if isinstance(value, float):
30
+ if not math.isfinite(value):
31
+ raise ValueError(
32
+ "Postgres returned a non-finite number that cannot cross a JSON boundary"
33
+ )
34
+ return value
35
+ if isinstance(value, (Decimal, UUID)):
36
+ return str(value)
37
+ if isinstance(value, (datetime, date, time)):
38
+ return value.isoformat()
39
+ if isinstance(value, (bytes, bytearray, memoryview)):
40
+ return {"type": "Buffer", "data": list(bytes(value))}
41
+ if isinstance(value, (list, tuple)):
42
+ return [json_value(item) for item in value]
43
+ if isinstance(value, dict):
44
+ return {str(key): json_value(item) for key, item in value.items()}
45
+ raise ValueError(f"Postgres returned an unsupported JSON value of type {type(value).__name__}")
46
+
47
+
48
+ def adapt_parameter(value: Any) -> Any:
49
+ if isinstance(value, dict):
50
+ return Jsonb(value)
51
+ if isinstance(value, list):
52
+ return [adapt_parameter(item) for item in value]
53
+ return value
54
+
55
+
56
+ class Database:
57
+ def __init__(self, connection: AsyncConnection[dict[str, Any]]) -> None:
58
+ self.connection = connection
59
+
60
+ async def query(self, sql: str, params: list[Any] | None = None) -> t.QueryResult:
61
+ adapted = None if params is None else [adapt_parameter(v) for v in params]
62
+ async with AsyncRawCursor(self.connection, row_factory=dict_row) as cursor:
63
+ await cursor.execute(sql, adapted)
64
+ rows = await cursor.fetchall() if cursor.description else []
65
+ return {"rows": [json_value(row) for row in rows], "rowCount": max(cursor.rowcount, 0)}
66
+
67
+ async def batch(self, statements: list[t.Statement]) -> t.TransactionResult:
68
+ async with self.connection.transaction():
69
+ counts = [(await self.query(s["sql"], s.get("params")))["rowCount"] for s in statements]
70
+ return {"rowCounts": counts}
71
+
72
+
73
+ @asynccontextmanager
74
+ async def connect_database() -> AsyncIterator[Database]:
75
+ url = os.environ.get("DATABASE_URL")
76
+ if not url:
77
+ raise ValueError(
78
+ "DATABASE_URL is required for the render-postgres tasks "
79
+ "(postgres.query, execute, upsert, transaction, migrate). "
80
+ "Render injects it for a linked Postgres instance, reachable over the private network."
81
+ )
82
+ options: dict[str, Any] = {}
83
+ ssl_mode = os.environ.get("DATABASE_SSL")
84
+ if ssl_mode in ("true", "require"):
85
+ options["sslmode"] = "verify-full"
86
+ options["sslrootcert"] = "system"
87
+ elif ssl_mode == "no-verify":
88
+ options["sslmode"] = "require"
89
+ async with await AsyncConnection.connect(
90
+ url, autocommit=True, row_factory=dict_row, connect_timeout=30, **options
91
+ ) as connection:
92
+ yield Database(connection)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import PG_RETRY
6
+ from .types import DeleteVectorsInput, DeleteVectorsResult
7
+
8
+
9
+ async def delete_vectors_impl(
10
+ ctx: TaskContext, input: DeleteVectorsInput, *, deps: Deps | None = None
11
+ ) -> DeleteVectorsResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.render_postgres.delete_vectors(input)
14
+
15
+
16
+ @app.task(name="postgres.deleteVectors", retry=PG_RETRY)
17
+ async def delete_vectors(ctx: TaskContext, input: DeleteVectorsInput) -> DeleteVectorsResult:
18
+ return await delete_vectors_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import PG_RETRY
6
+ from .types import ExecuteInput, ExecuteResult
7
+
8
+
9
+ async def execute_impl(
10
+ ctx: TaskContext, input: ExecuteInput, *, deps: Deps | None = None
11
+ ) -> ExecuteResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.render_postgres.execute(input)
14
+
15
+
16
+ @app.task(name="postgres.execute", retry=PG_RETRY)
17
+ async def execute(ctx: TaskContext, input: ExecuteInput) -> ExecuteResult:
18
+ return await execute_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import PG_RETRY
6
+ from .types import MigrateInput, MigrateResult
7
+
8
+
9
+ async def migrate_impl(
10
+ ctx: TaskContext, input: MigrateInput, *, deps: Deps | None = None
11
+ ) -> MigrateResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.render_postgres.migrate(input)
14
+
15
+
16
+ @app.task(name="postgres.migrate", retry=PG_RETRY)
17
+ async def migrate(ctx: TaskContext, input: MigrateInput) -> MigrateResult:
18
+ return await migrate_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import PG_RETRY
6
+ from .types import QueryInput, QueryResult
7
+
8
+
9
+ async def query_impl(
10
+ ctx: TaskContext, input: QueryInput, *, deps: Deps | None = None
11
+ ) -> QueryResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.render_postgres.query(input)
14
+
15
+
16
+ @app.task(name="postgres.query", retry=PG_RETRY)
17
+ async def query(ctx: TaskContext, input: QueryInput) -> QueryResult:
18
+ return await query_impl(ctx, input)
@@ -0,0 +1,3 @@
1
+ from render import Retry
2
+
3
+ PG_RETRY = Retry(max_retries=3, wait_duration_ms=1000, backoff_scaling=2)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import PG_RETRY
6
+ from .types import SearchVectorsInput, SearchVectorsResult
7
+
8
+
9
+ async def search_vectors_impl(
10
+ ctx: TaskContext, input: SearchVectorsInput, *, deps: Deps | None = None
11
+ ) -> SearchVectorsResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.render_postgres.search_vectors(input)
14
+
15
+
16
+ @app.task(name="postgres.searchVectors", retry=PG_RETRY)
17
+ async def search_vectors(ctx: TaskContext, input: SearchVectorsInput) -> SearchVectorsResult:
18
+ return await search_vectors_impl(ctx, input)
@@ -0,0 +1,20 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import PG_RETRY
6
+ from .types import SetupVectorStoreInput, SetupVectorStoreResult
7
+
8
+
9
+ async def setup_vector_store_impl(
10
+ ctx: TaskContext, input: SetupVectorStoreInput, *, deps: Deps | None = None
11
+ ) -> SetupVectorStoreResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.render_postgres.setup_vector_store(input)
14
+
15
+
16
+ @app.task(name="postgres.setupVectorStore", retry=PG_RETRY)
17
+ async def setup_vector_store(
18
+ ctx: TaskContext, input: SetupVectorStoreInput
19
+ ) -> SetupVectorStoreResult:
20
+ return await setup_vector_store_impl(ctx, input)
@@ -0,0 +1,32 @@
1
+ from ._app import app
2
+ from .delete_vectors import delete_vectors, delete_vectors_impl
3
+ from .execute import execute, execute_impl
4
+ from .migrate import migrate, migrate_impl
5
+ from .query import query, query_impl
6
+ from .search_vectors import search_vectors, search_vectors_impl
7
+ from .setup_vector_store import setup_vector_store, setup_vector_store_impl
8
+ from .transaction import transaction, transaction_impl
9
+ from .upsert import upsert, upsert_impl
10
+ from .upsert_vectors import upsert_vectors, upsert_vectors_impl
11
+
12
+ __all__ = [
13
+ "app",
14
+ "delete_vectors",
15
+ "delete_vectors_impl",
16
+ "execute",
17
+ "execute_impl",
18
+ "migrate",
19
+ "migrate_impl",
20
+ "query",
21
+ "query_impl",
22
+ "search_vectors",
23
+ "search_vectors_impl",
24
+ "setup_vector_store",
25
+ "setup_vector_store_impl",
26
+ "transaction",
27
+ "transaction_impl",
28
+ "upsert",
29
+ "upsert_impl",
30
+ "upsert_vectors",
31
+ "upsert_vectors_impl",
32
+ ]
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import PG_RETRY
6
+ from .types import TransactionInput, TransactionResult
7
+
8
+
9
+ async def transaction_impl(
10
+ ctx: TaskContext, input: TransactionInput, *, deps: Deps | None = None
11
+ ) -> TransactionResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.render_postgres.transaction(input)
14
+
15
+
16
+ @app.task(name="postgres.transaction", retry=PG_RETRY)
17
+ async def transaction(ctx: TaskContext, input: TransactionInput) -> TransactionResult:
18
+ return await transaction_impl(ctx, input)
@@ -0,0 +1,123 @@
1
+ """JSON contracts ported from the pinned TypeScript pack."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Literal, NotRequired, TypedDict
6
+
7
+ type JsonRow = dict[str, Any]
8
+
9
+
10
+ class Statement(TypedDict):
11
+ sql: str
12
+ params: NotRequired[list[Any]]
13
+
14
+
15
+ class QueryInput(TypedDict):
16
+ sql: str
17
+ params: NotRequired[list[Any]]
18
+
19
+
20
+ class QueryResult(TypedDict):
21
+ rows: list[JsonRow]
22
+ rowCount: float
23
+
24
+
25
+ class ExecuteInput(TypedDict):
26
+ sql: str
27
+ params: NotRequired[list[Any]]
28
+
29
+
30
+ class ExecuteResult(TypedDict):
31
+ rowCount: float
32
+
33
+
34
+ class UpsertInput(TypedDict):
35
+ table: str
36
+ rows: list[JsonRow]
37
+ conflictColumns: list[str]
38
+ updateColumns: NotRequired[list[str]]
39
+
40
+
41
+ class UpsertResult(TypedDict):
42
+ rowCount: float
43
+
44
+
45
+ class TransactionInput(TypedDict):
46
+ statements: list[Statement]
47
+
48
+
49
+ class TransactionResult(TypedDict):
50
+ rowCounts: list[float]
51
+
52
+
53
+ class Migration(TypedDict):
54
+ name: str
55
+ sql: str
56
+
57
+
58
+ class MigrateInput(TypedDict):
59
+ migrations: list[Migration]
60
+
61
+
62
+ class MigrateResult(TypedDict):
63
+ applied: list[str]
64
+
65
+
66
+ class SetupVectorStoreInput(TypedDict):
67
+ table: str
68
+ dimensions: float
69
+ index: NotRequired[Literal["hnsw"] | Literal["ivfflat"] | Literal["none"]]
70
+
71
+
72
+ class SetupVectorStoreResult(TypedDict):
73
+ table: str
74
+ extensionReady: bool
75
+ tableCreated: bool
76
+ indexCreated: bool
77
+
78
+
79
+ class VectorRowInput(TypedDict):
80
+ id: str
81
+ content: NotRequired[str | None]
82
+ metadata: NotRequired[dict[str, Any] | None]
83
+ embedding: list[float]
84
+
85
+
86
+ class UpsertVectorsInput(TypedDict):
87
+ table: str
88
+ rows: list[VectorRowInput]
89
+
90
+
91
+ class UpsertVectorsResult(TypedDict):
92
+ table: str
93
+ upserted: float
94
+
95
+
96
+ class SearchVectorsInput(TypedDict):
97
+ table: str
98
+ embedding: list[float]
99
+ limit: NotRequired[float]
100
+ maxDistance: NotRequired[float]
101
+ filter: NotRequired[dict[str, Any]]
102
+
103
+
104
+ class VectorSearchRow(TypedDict):
105
+ id: str
106
+ content: str | None
107
+ metadata: dict[str, Any] | None
108
+ similarity: float
109
+
110
+
111
+ class SearchVectorsResult(TypedDict):
112
+ rows: list[VectorSearchRow]
113
+
114
+
115
+ class DeleteVectorsInput(TypedDict):
116
+ table: str
117
+ ids: NotRequired[list[str]]
118
+ filter: NotRequired[dict[str, Any]]
119
+
120
+
121
+ class DeleteVectorsResult(TypedDict):
122
+ table: str
123
+ deleted: float
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import PG_RETRY
6
+ from .types import UpsertInput, UpsertResult
7
+
8
+
9
+ async def upsert_impl(
10
+ ctx: TaskContext, input: UpsertInput, *, deps: Deps | None = None
11
+ ) -> UpsertResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.render_postgres.upsert(input)
14
+
15
+
16
+ @app.task(name="postgres.upsert", retry=PG_RETRY)
17
+ async def upsert(ctx: TaskContext, input: UpsertInput) -> UpsertResult:
18
+ return await upsert_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import PG_RETRY
6
+ from .types import UpsertVectorsInput, UpsertVectorsResult
7
+
8
+
9
+ async def upsert_vectors_impl(
10
+ ctx: TaskContext, input: UpsertVectorsInput, *, deps: Deps | None = None
11
+ ) -> UpsertVectorsResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.render_postgres.upsert_vectors(input)
14
+
15
+
16
+ @app.task(name="postgres.upsertVectors", retry=PG_RETRY)
17
+ async def upsert_vectors(ctx: TaskContext, input: UpsertVectorsInput) -> UpsertVectorsResult:
18
+ return await upsert_vectors_impl(ctx, input)
@@ -0,0 +1,125 @@
1
+ import json
2
+ from pathlib import Path
3
+ from unittest.mock import AsyncMock, MagicMock
4
+
5
+ import pytest
6
+ from render_lab_tasks_render_postgres import tasks
7
+ from render_lab_tasks_render_postgres.client import Client, Deps
8
+ from render_lab_tasks_render_postgres.database import Database, connect_database, json_value
9
+
10
+ CASES = json.loads(
11
+ (Path(__file__).parents[3] / "scripts/fixtures/batch4-postgres.json").read_text()
12
+ )
13
+
14
+
15
+ @pytest.mark.parametrize("case", CASES, ids=lambda c: c["id"])
16
+ async def test_pinned_ts_sql(case, ctx):
17
+ db = AsyncMock()
18
+ for method in ("query", "batch"):
19
+ getattr(db, method).side_effect = [
20
+ s["result"] for s in case["sdk"] if s["method"] == method
21
+ ]
22
+ expected = case["expected"]
23
+ raw = getattr(tasks, case["pythonExport"] + "_impl")
24
+ if "error" in expected:
25
+ with pytest.raises(ValueError) as error:
26
+ await raw(ctx, case["input"], deps=Deps(Client(db)))
27
+ assert str(error.value) == expected["error"]
28
+ else:
29
+ assert await raw(ctx, case["input"], deps=Deps(Client(db))) == expected["output"]
30
+ got = [{"method": c[0], "args": list(c.args)} for c in db.mock_calls]
31
+ wanted = case["expected"]["sdkCalls"]
32
+ # Python supplies an explicit None for an absent optional query parameter.
33
+ for call in got:
34
+ if len(call["args"]) == 2 and call["args"][-1] is None:
35
+ call["args"].pop()
36
+ if case["pythonExport"] == "upsert" and got:
37
+ # Deliberate deviation: all generated identifiers are validated and quoted.
38
+ assert (
39
+ got[0]["args"][0] == 'INSERT INTO "users" ("id", "name") VALUES ($1, $2), ($3, $4) '
40
+ 'ON CONFLICT ("id") DO UPDATE SET "name" = EXCLUDED."name"'
41
+ )
42
+ assert got[0]["args"][1] == wanted[0]["args"][1]
43
+ else:
44
+ assert got == wanted
45
+
46
+
47
+ async def test_invalid_upsert_identifier_never_reaches_database():
48
+ db = AsyncMock()
49
+ with pytest.raises(ValueError, match="Invalid SQL identifier"):
50
+ await Client(db).upsert(
51
+ {"table": "users; DROP TABLE users", "rows": [{"id": 1}], "conflictColumns": ["id"]}
52
+ )
53
+ db.query.assert_not_called()
54
+
55
+
56
+ @pytest.mark.parametrize("error", [RuntimeError("broken"), __import__("asyncio").CancelledError()])
57
+ async def test_batch_failure_exits_transaction_without_retry(error):
58
+ transaction = AsyncMock()
59
+ transaction.__aexit__.return_value = False
60
+ connection = MagicMock()
61
+ connection.transaction.return_value = transaction
62
+ db = Database(connection)
63
+ db.query = AsyncMock(side_effect=[{"rowCount": 1, "rows": []}, error])
64
+ with pytest.raises(type(error)):
65
+ await db.batch([{"sql": "one"}, {"sql": "two"}, {"sql": "three"}])
66
+ assert db.query.call_count == 2
67
+ assert transaction.__aexit__.call_args.args[0] is type(error)
68
+
69
+
70
+ async def test_driver_parameters_rows_and_cursor_cleanup(monkeypatch):
71
+ from psycopg.types.json import Jsonb
72
+ from render_lab_tasks_render_postgres import database
73
+
74
+ cursor = AsyncMock()
75
+ cursor.__aenter__.return_value = cursor
76
+ cursor.description = ["value"]
77
+ cursor.rowcount = 1
78
+ cursor.fetchall.return_value = [{"value": __import__("decimal").Decimal("123.45")}]
79
+ monkeypatch.setattr(database, "AsyncRawCursor", lambda *args, **kwargs: cursor)
80
+ db = Database(MagicMock())
81
+ result = await db.query("SELECT $1::jsonb", [{"hello": "world"}])
82
+ assert result == {"rows": [{"value": "123.45"}], "rowCount": 1}
83
+ assert isinstance(cursor.execute.call_args.args[1][0], Jsonb)
84
+ cursor.__aexit__.assert_awaited_once()
85
+
86
+
87
+ async def test_lazy_credentials():
88
+ with pytest.raises(ValueError, match="DATABASE_URL is required"):
89
+ async with connect_database():
90
+ pass
91
+
92
+
93
+ def test_json_conversion():
94
+ from datetime import date
95
+ from decimal import Decimal
96
+ from uuid import UUID
97
+
98
+ assert json_value(
99
+ {
100
+ "decimal": Decimal("1.0001"),
101
+ "date": date(2026, 9, 4),
102
+ "bytes": b"\x01\xff",
103
+ "uuid": UUID(int=0),
104
+ }
105
+ ) == {
106
+ "decimal": "1.0001",
107
+ "date": "2026-09-04",
108
+ "bytes": {"type": "Buffer", "data": [1, 255]},
109
+ "uuid": "00000000-0000-0000-0000-000000000000",
110
+ }
111
+ for value in [float("nan"), float("inf"), object()]:
112
+ with pytest.raises(ValueError):
113
+ json_value(value)
114
+
115
+
116
+ def test_actual_driver_encodes_json_objects_nested_in_sql_arrays():
117
+ from psycopg.adapt import PyFormat, Transformer
118
+ from render_lab_tasks_render_postgres.database import adapt_parameter
119
+
120
+ value = [[{"x": 1}, None], [{"x": 2}, {"nested": [1, 2]}]]
121
+ encoded = Transformer().dump_sequence([adapt_parameter(value)], [PyFormat.TEXT])
122
+ assert encoded[0] is not None
123
+ wire = bytes(encoded[0])
124
+ assert b"NULL" in wire and b"nested" in wire
125
+ assert value[0][0] == {"x": 1} # No mutation of the caller's JSON input.