agentforge-memory-postgres 0.2.3__py3-none-any.whl
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.
- agentforge_memory_postgres/__init__.py +19 -0
- agentforge_memory_postgres/_migrator.py +153 -0
- agentforge_memory_postgres/_runner.py +135 -0
- agentforge_memory_postgres/memory.py +296 -0
- agentforge_memory_postgres/migrations/0000_migrations_table.sql +6 -0
- agentforge_memory_postgres/migrations/0001_initial.sql +13 -0
- agentforge_memory_postgres/migrations/vector/0000_migrations_table.sql +6 -0
- agentforge_memory_postgres/migrations/vector/0100_vectors.sql +14 -0
- agentforge_memory_postgres/py.typed +0 -0
- agentforge_memory_postgres/vector.py +293 -0
- agentforge_memory_postgres-0.2.3.dist-info/METADATA +92 -0
- agentforge_memory_postgres-0.2.3.dist-info/RECORD +15 -0
- agentforge_memory_postgres-0.2.3.dist-info/WHEEL +4 -0
- agentforge_memory_postgres-0.2.3.dist-info/entry_points.txt +5 -0
- agentforge_memory_postgres-0.2.3.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""AgentForge — Postgres + pgvector memory and vector drivers.
|
|
2
|
+
|
|
3
|
+
Implements `MemoryStore` (claim audit log) and `VectorStore` (semantic
|
|
4
|
+
search via pgvector) over Postgres via the official `asyncpg` driver.
|
|
5
|
+
Sister package to `agentforge-memory-sqlite`; same locked contracts,
|
|
6
|
+
same conformance suites.
|
|
7
|
+
|
|
8
|
+
Per ADR-0014 every code path is async — uses `asyncpg`, never the
|
|
9
|
+
sync `psycopg`, in agent code paths.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from agentforge_memory_postgres.memory import PostgresMemoryStore
|
|
15
|
+
from agentforge_memory_postgres.vector import PostgresVectorStore
|
|
16
|
+
|
|
17
|
+
__version__ = "0.2.3"
|
|
18
|
+
|
|
19
|
+
__all__ = ["PostgresMemoryStore", "PostgresVectorStore", "__version__"]
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""`PostgresMigrator` — Postgres-side implementation of the feat-024
|
|
2
|
+
:class:`agentforge_core.Migrator` Protocol.
|
|
3
|
+
|
|
4
|
+
Migrations ship at
|
|
5
|
+
``agentforge_memory_postgres/migrations/NNNN_<name>.sql``. The first
|
|
6
|
+
migration (``0000_migrations_table.sql``) creates the
|
|
7
|
+
``agentforge_migrations`` tracking table; subsequent migrations carry
|
|
8
|
+
the actual schema deltas. Each migration is executed inside its own
|
|
9
|
+
asyncpg transaction so a partial failure rolls back cleanly.
|
|
10
|
+
|
|
11
|
+
The migrator consumes the existing :class:`PostgresRunner` Protocol
|
|
12
|
+
so unit tests can inject the same fake the rest of the package uses.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from agentforge_core.contracts.migrator import (
|
|
21
|
+
Migration,
|
|
22
|
+
MigrationChecksumError,
|
|
23
|
+
MigrationStatus,
|
|
24
|
+
)
|
|
25
|
+
from agentforge_core.migrations import discover_migrations, render_migration_up
|
|
26
|
+
|
|
27
|
+
from agentforge_memory_postgres._runner import PostgresRunner
|
|
28
|
+
|
|
29
|
+
_MIGRATIONS_TABLE = "agentforge_migrations"
|
|
30
|
+
|
|
31
|
+
_SELECT_APPLIED_SQL = (
|
|
32
|
+
f"SELECT id, name, checksum, applied_at " # noqa: S608 # nosec B608
|
|
33
|
+
f" FROM {_MIGRATIONS_TABLE} ORDER BY id"
|
|
34
|
+
)
|
|
35
|
+
_INSERT_APPLIED_SQL = (
|
|
36
|
+
f"INSERT INTO {_MIGRATIONS_TABLE} (id, name, checksum) " # noqa: S608 # nosec B608
|
|
37
|
+
f"VALUES ($1, $2, $3)"
|
|
38
|
+
)
|
|
39
|
+
_TABLE_EXISTS_SQL = "SELECT to_regclass($1) IS NOT NULL AS exists_" # type checker hint
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _default_migrations_path() -> Path:
|
|
43
|
+
"""Return the in-package migrations directory."""
|
|
44
|
+
return Path(__file__).parent / "migrations"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class PostgresMigrator:
|
|
48
|
+
"""Postgres implementation of :class:`agentforge_core.Migrator`.
|
|
49
|
+
|
|
50
|
+
Args:
|
|
51
|
+
runner: Live `PostgresRunner` (production or fake) — the
|
|
52
|
+
same one the rest of the driver uses.
|
|
53
|
+
migrations_path: Override for the in-package migrations
|
|
54
|
+
directory (test fixtures use this).
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
def __init__(
|
|
58
|
+
self,
|
|
59
|
+
runner: PostgresRunner,
|
|
60
|
+
*,
|
|
61
|
+
variables: dict[str, str] | None = None,
|
|
62
|
+
migrations_path: Path | None = None,
|
|
63
|
+
) -> None:
|
|
64
|
+
self._r = runner
|
|
65
|
+
self._path = migrations_path or _default_migrations_path()
|
|
66
|
+
self._variables = variables
|
|
67
|
+
self._migrations: list[Migration] = discover_migrations(self._path, suffix="sql")
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def migrations(self) -> list[Migration]:
|
|
71
|
+
return list(self._migrations)
|
|
72
|
+
|
|
73
|
+
async def current_version(self) -> str | None:
|
|
74
|
+
if not await self._tracking_table_exists():
|
|
75
|
+
return None
|
|
76
|
+
rows = await self._r.fetch(_SELECT_APPLIED_SQL)
|
|
77
|
+
if not rows:
|
|
78
|
+
return None
|
|
79
|
+
return str(max(row["id"] for row in rows))
|
|
80
|
+
|
|
81
|
+
async def status(self) -> list[MigrationStatus]:
|
|
82
|
+
applied = await self._fetch_applied()
|
|
83
|
+
results: list[MigrationStatus] = []
|
|
84
|
+
for migration in self._migrations:
|
|
85
|
+
record = applied.get(migration.id)
|
|
86
|
+
if record is None:
|
|
87
|
+
results.append(
|
|
88
|
+
MigrationStatus(
|
|
89
|
+
migration=migration,
|
|
90
|
+
applied=False,
|
|
91
|
+
applied_at=None,
|
|
92
|
+
checksum_match=False,
|
|
93
|
+
)
|
|
94
|
+
)
|
|
95
|
+
continue
|
|
96
|
+
results.append(
|
|
97
|
+
MigrationStatus(
|
|
98
|
+
migration=migration,
|
|
99
|
+
applied=True,
|
|
100
|
+
applied_at=record["applied_at"],
|
|
101
|
+
checksum_match=record["checksum"] == migration.checksum,
|
|
102
|
+
)
|
|
103
|
+
)
|
|
104
|
+
return results
|
|
105
|
+
|
|
106
|
+
async def apply_pending(self) -> list[Migration]:
|
|
107
|
+
applied = await self._fetch_applied()
|
|
108
|
+
|
|
109
|
+
# Verify previously-applied migrations' checksums haven't drifted
|
|
110
|
+
# before applying anything new.
|
|
111
|
+
for migration in self._migrations:
|
|
112
|
+
record = applied.get(migration.id)
|
|
113
|
+
if record is not None and record["checksum"] != migration.checksum:
|
|
114
|
+
msg = (
|
|
115
|
+
f"Postgres migration {migration.id}_{migration.name} "
|
|
116
|
+
f"checksum drift: recorded {record['checksum']!r} but "
|
|
117
|
+
f"file is now {migration.checksum!r}."
|
|
118
|
+
)
|
|
119
|
+
raise MigrationChecksumError(msg)
|
|
120
|
+
|
|
121
|
+
new_applied: list[Migration] = []
|
|
122
|
+
for migration in self._migrations:
|
|
123
|
+
if migration.id in applied:
|
|
124
|
+
continue
|
|
125
|
+
rendered = render_migration_up(migration.up, self._variables)
|
|
126
|
+
await self._r.execute(rendered)
|
|
127
|
+
await self._r.execute(
|
|
128
|
+
_INSERT_APPLIED_SQL,
|
|
129
|
+
migration.id,
|
|
130
|
+
migration.name,
|
|
131
|
+
migration.checksum,
|
|
132
|
+
)
|
|
133
|
+
new_applied.append(migration)
|
|
134
|
+
return new_applied
|
|
135
|
+
|
|
136
|
+
async def _tracking_table_exists(self) -> bool:
|
|
137
|
+
row = await self._r.fetchrow(_TABLE_EXISTS_SQL, _MIGRATIONS_TABLE)
|
|
138
|
+
if row is None:
|
|
139
|
+
return False
|
|
140
|
+
return bool(row["exists_"])
|
|
141
|
+
|
|
142
|
+
async def _fetch_applied(self) -> dict[str, dict[str, Any]]:
|
|
143
|
+
if not await self._tracking_table_exists():
|
|
144
|
+
return {}
|
|
145
|
+
rows = await self._r.fetch(_SELECT_APPLIED_SQL)
|
|
146
|
+
return {
|
|
147
|
+
str(row["id"]): {
|
|
148
|
+
"name": row["name"],
|
|
149
|
+
"checksum": row["checksum"],
|
|
150
|
+
"applied_at": row["applied_at"],
|
|
151
|
+
}
|
|
152
|
+
for row in rows
|
|
153
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""Internal asyncpg-runner abstraction.
|
|
2
|
+
|
|
3
|
+
Production stores wrap an `asyncpg.Pool`; unit tests inject a
|
|
4
|
+
`PostgresFakeRunner` that interprets the SQL vocabulary the drivers
|
|
5
|
+
emit and routes operations to in-memory backings. Every `*Store` in
|
|
6
|
+
this package goes through the runner — never the pool directly — so
|
|
7
|
+
the test boundary is a single interface.
|
|
8
|
+
|
|
9
|
+
Per ADR-0014 every code path is async. Callers must `await close()`
|
|
10
|
+
at shutdown to release the pool's pooled connections.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from typing import Any, Protocol
|
|
16
|
+
|
|
17
|
+
from pgvector.asyncpg import register_vector
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class PostgresRunner(Protocol):
|
|
21
|
+
"""Internal protocol — every SQL statement goes through one of these.
|
|
22
|
+
|
|
23
|
+
Mirrors a thin slice of `asyncpg.Connection` / `asyncpg.Pool`:
|
|
24
|
+
|
|
25
|
+
- `fetch` returns a list of rows (`asyncpg.Record`-like)
|
|
26
|
+
- `fetchrow` returns a single row or None
|
|
27
|
+
- `execute` runs a statement that doesn't return rows
|
|
28
|
+
- `executemany` runs a statement with a list of parameter tuples
|
|
29
|
+
- `close` releases the pool
|
|
30
|
+
|
|
31
|
+
The vector store also needs a `register_vector(conn)` hook on
|
|
32
|
+
each pooled connection so pgvector's codec is set up; the
|
|
33
|
+
production runner handles that on acquisition.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
async def fetch(self, sql: str, *params: Any) -> list[Any]: ...
|
|
37
|
+
|
|
38
|
+
async def fetchrow(self, sql: str, *params: Any) -> Any | None: ...
|
|
39
|
+
|
|
40
|
+
async def execute(self, sql: str, *params: Any) -> None: ...
|
|
41
|
+
|
|
42
|
+
async def executemany(self, sql: str, args: list[tuple[Any, ...]]) -> None: ...
|
|
43
|
+
|
|
44
|
+
async def execute_returning_count(self, sql: str, *params: Any) -> int: ...
|
|
45
|
+
|
|
46
|
+
async def close(self) -> None: ...
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class _AsyncpgPoolRunner:
|
|
50
|
+
"""Production runner — wraps an `asyncpg.Pool`.
|
|
51
|
+
|
|
52
|
+
Each call acquires a connection from the pool, runs the
|
|
53
|
+
statement, and releases. Mutating calls (`execute`,
|
|
54
|
+
`executemany`) wrap in an `async with conn.transaction():` block
|
|
55
|
+
so a failed statement doesn't leave partial state.
|
|
56
|
+
|
|
57
|
+
`setup_pgvector` should be True when this runner serves a
|
|
58
|
+
`PostgresVectorStore`, so each pooled connection registers the
|
|
59
|
+
pgvector codec on first acquisition.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
def __init__(self, pool: Any, *, setup_pgvector: bool = False) -> None:
|
|
63
|
+
# `pool` is `asyncpg.Pool`; typed as Any because asyncpg ships
|
|
64
|
+
# without py.typed and the workspace mypy override strips its
|
|
65
|
+
# types.
|
|
66
|
+
self._pool = pool
|
|
67
|
+
self._setup_pgvector = setup_pgvector
|
|
68
|
+
|
|
69
|
+
async def fetch(self, sql: str, *params: Any) -> list[Any]:
|
|
70
|
+
async with self._pool.acquire() as conn:
|
|
71
|
+
await self._maybe_register_vector(conn)
|
|
72
|
+
return list(await conn.fetch(sql, *params))
|
|
73
|
+
|
|
74
|
+
async def fetchrow(self, sql: str, *params: Any) -> Any | None:
|
|
75
|
+
async with self._pool.acquire() as conn:
|
|
76
|
+
await self._maybe_register_vector(conn)
|
|
77
|
+
return await conn.fetchrow(sql, *params)
|
|
78
|
+
|
|
79
|
+
async def execute(self, sql: str, *params: Any) -> None:
|
|
80
|
+
async with self._pool.acquire() as conn:
|
|
81
|
+
await self._maybe_register_vector(conn)
|
|
82
|
+
async with conn.transaction():
|
|
83
|
+
await conn.execute(sql, *params)
|
|
84
|
+
|
|
85
|
+
async def executemany(self, sql: str, args: list[tuple[Any, ...]]) -> None:
|
|
86
|
+
async with self._pool.acquire() as conn:
|
|
87
|
+
await self._maybe_register_vector(conn)
|
|
88
|
+
async with conn.transaction():
|
|
89
|
+
await conn.executemany(sql, args)
|
|
90
|
+
|
|
91
|
+
async def execute_returning_count(self, sql: str, *params: Any) -> int:
|
|
92
|
+
"""Execute a mutating statement and return the affected-row count.
|
|
93
|
+
|
|
94
|
+
asyncpg's `conn.execute` returns a status tag like
|
|
95
|
+
``"DELETE 3"``; we parse the trailing integer. Used by
|
|
96
|
+
`MemoryStore.delete` to surface the deleted-row count back to
|
|
97
|
+
callers.
|
|
98
|
+
"""
|
|
99
|
+
async with self._pool.acquire() as conn:
|
|
100
|
+
await self._maybe_register_vector(conn)
|
|
101
|
+
async with conn.transaction():
|
|
102
|
+
tag = await conn.execute(sql, *params)
|
|
103
|
+
return _parse_count(tag)
|
|
104
|
+
|
|
105
|
+
async def close(self) -> None:
|
|
106
|
+
await self._pool.close()
|
|
107
|
+
|
|
108
|
+
async def _maybe_register_vector(self, conn: Any) -> None:
|
|
109
|
+
"""Register the pgvector codec on this connection (idempotent).
|
|
110
|
+
|
|
111
|
+
pgvector ships an asyncpg helper that teaches the codec how
|
|
112
|
+
to encode `list[float]` as the `vector` type and decode it
|
|
113
|
+
back. We call it lazily on first use of each pooled
|
|
114
|
+
connection — asyncpg caches type codecs per-connection so
|
|
115
|
+
this is cheap on subsequent calls.
|
|
116
|
+
"""
|
|
117
|
+
if not self._setup_pgvector:
|
|
118
|
+
return
|
|
119
|
+
await register_vector(conn)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _parse_count(tag: Any) -> int:
|
|
123
|
+
"""Extract the affected-row count from an asyncpg status tag."""
|
|
124
|
+
if not isinstance(tag, str):
|
|
125
|
+
return 0
|
|
126
|
+
parts = tag.rsplit(maxsplit=1)
|
|
127
|
+
if not parts:
|
|
128
|
+
return 0
|
|
129
|
+
try:
|
|
130
|
+
return int(parts[-1])
|
|
131
|
+
except ValueError:
|
|
132
|
+
return 0
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
__all__ = ["PostgresRunner"]
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
"""`PostgresMemoryStore` — `MemoryStore` over Postgres via asyncpg.
|
|
2
|
+
|
|
3
|
+
Single-table schema: every claim is one row keyed by `id` with
|
|
4
|
+
project / agent / category / run_id / supersedes columns and a JSONB
|
|
5
|
+
payload. Queries hit composite indices on the common filter
|
|
6
|
+
combinations.
|
|
7
|
+
|
|
8
|
+
`init_schema()` creates the table + indices via
|
|
9
|
+
`CREATE TABLE IF NOT EXISTS`. Idempotent. No migration framework —
|
|
10
|
+
the schema shape is pinned for v0.1; a future delta lands alongside
|
|
11
|
+
schema-migrations support.
|
|
12
|
+
|
|
13
|
+
Per ADR-0014 every code path is async (asyncpg, not psycopg).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
from collections.abc import AsyncIterator
|
|
20
|
+
from datetime import datetime
|
|
21
|
+
from types import TracebackType
|
|
22
|
+
from typing import Any, Self
|
|
23
|
+
|
|
24
|
+
import asyncpg
|
|
25
|
+
from agentforge_core.contracts.memory import MemoryStore
|
|
26
|
+
from agentforge_core.production.exceptions import ModuleError
|
|
27
|
+
from agentforge_core.values.claim import Claim
|
|
28
|
+
|
|
29
|
+
from agentforge_memory_postgres._migrator import PostgresMigrator
|
|
30
|
+
from agentforge_memory_postgres._runner import PostgresRunner, _AsyncpgPoolRunner
|
|
31
|
+
|
|
32
|
+
# Table names are framework constants — never derived from user input.
|
|
33
|
+
# All SQL composed from these constants is parameterised via asyncpg's
|
|
34
|
+
# `$1, $2, ...` placeholders (no user input in f-strings). The S608 /
|
|
35
|
+
# B608 noqa annotations below are explicit acknowledgements of that
|
|
36
|
+
# fact, not relaxations of the lint surface.
|
|
37
|
+
_CLAIMS_TABLE = "claims"
|
|
38
|
+
|
|
39
|
+
_UPSERT_CLAIM_SQL = (
|
|
40
|
+
f"INSERT INTO {_CLAIMS_TABLE} " # noqa: S608 # nosec B608
|
|
41
|
+
"(id, project, agent, run_id, category, payload, supersedes, created_at) "
|
|
42
|
+
"VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7, $8) "
|
|
43
|
+
"ON CONFLICT (id) DO UPDATE SET "
|
|
44
|
+
" project = EXCLUDED.project, agent = EXCLUDED.agent, "
|
|
45
|
+
" run_id = EXCLUDED.run_id, category = EXCLUDED.category, "
|
|
46
|
+
" payload = EXCLUDED.payload, supersedes = EXCLUDED.supersedes, "
|
|
47
|
+
" created_at = EXCLUDED.created_at"
|
|
48
|
+
)
|
|
49
|
+
_SELECT_CLAIM_BY_ID = f"SELECT * FROM {_CLAIMS_TABLE} WHERE id = $1" # noqa: S608 # nosec B608
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class PostgresMemoryStore(MemoryStore):
|
|
53
|
+
"""Persistent `MemoryStore` backed by Postgres.
|
|
54
|
+
|
|
55
|
+
Use `from_dsn(dsn)` for ergonomic construction; the bare
|
|
56
|
+
constructor accepts an injected `PostgresRunner` so unit tests can
|
|
57
|
+
fake asyncpg without spinning up Postgres.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
def __init__(self, *, runner: PostgresRunner) -> None:
|
|
61
|
+
self._r = runner
|
|
62
|
+
|
|
63
|
+
# ------------------------------------------------------------------
|
|
64
|
+
# Construction / lifecycle
|
|
65
|
+
# ------------------------------------------------------------------
|
|
66
|
+
|
|
67
|
+
@classmethod
|
|
68
|
+
async def from_dsn(
|
|
69
|
+
cls,
|
|
70
|
+
dsn: str,
|
|
71
|
+
*,
|
|
72
|
+
min_size: int = 1,
|
|
73
|
+
max_size: int = 10,
|
|
74
|
+
) -> Self:
|
|
75
|
+
"""Open an asyncpg pool against `dsn` and return a store."""
|
|
76
|
+
pool = await asyncpg.create_pool(dsn=dsn, min_size=min_size, max_size=max_size)
|
|
77
|
+
return cls(runner=_AsyncpgPoolRunner(pool))
|
|
78
|
+
|
|
79
|
+
async def __aenter__(self) -> Self:
|
|
80
|
+
return self
|
|
81
|
+
|
|
82
|
+
async def __aexit__(
|
|
83
|
+
self,
|
|
84
|
+
exc_type: type[BaseException] | None,
|
|
85
|
+
exc: BaseException | None,
|
|
86
|
+
tb: TracebackType | None,
|
|
87
|
+
) -> None:
|
|
88
|
+
await self.close()
|
|
89
|
+
|
|
90
|
+
def migrator(self) -> PostgresMigrator:
|
|
91
|
+
"""Return a `PostgresMigrator` configured against the
|
|
92
|
+
package's bundled migrations directory (feat-024)."""
|
|
93
|
+
return PostgresMigrator(self._r)
|
|
94
|
+
|
|
95
|
+
async def init_schema(self) -> None:
|
|
96
|
+
"""Apply every bundled migration (idempotent). Opt-in.
|
|
97
|
+
|
|
98
|
+
Delegates to the feat-024 migration framework — schema
|
|
99
|
+
provisioning is now versioned + checksum-tracked. Older
|
|
100
|
+
deployments that previously called this method continue to
|
|
101
|
+
work; subsequent calls only apply pending migrations.
|
|
102
|
+
|
|
103
|
+
Skip for read-only workloads or when the schema is managed
|
|
104
|
+
externally; required before first write for full correctness.
|
|
105
|
+
"""
|
|
106
|
+
await self.migrator().apply_pending()
|
|
107
|
+
|
|
108
|
+
async def close(self) -> None:
|
|
109
|
+
await self._r.close()
|
|
110
|
+
|
|
111
|
+
# ------------------------------------------------------------------
|
|
112
|
+
# MemoryStore contract
|
|
113
|
+
# ------------------------------------------------------------------
|
|
114
|
+
|
|
115
|
+
async def put(self, claim: Claim) -> str:
|
|
116
|
+
await self._r.execute(
|
|
117
|
+
_UPSERT_CLAIM_SQL,
|
|
118
|
+
claim.id,
|
|
119
|
+
claim.project,
|
|
120
|
+
claim.agent,
|
|
121
|
+
claim.run_id,
|
|
122
|
+
claim.category,
|
|
123
|
+
json.dumps(claim.payload),
|
|
124
|
+
claim.supersedes,
|
|
125
|
+
claim.created_at,
|
|
126
|
+
)
|
|
127
|
+
return claim.id
|
|
128
|
+
|
|
129
|
+
async def get(self, claim_id: str) -> Claim | None:
|
|
130
|
+
row = await self._r.fetchrow(_SELECT_CLAIM_BY_ID, claim_id)
|
|
131
|
+
if row is None:
|
|
132
|
+
return None
|
|
133
|
+
return _row_to_claim(row)
|
|
134
|
+
|
|
135
|
+
async def query(
|
|
136
|
+
self,
|
|
137
|
+
*,
|
|
138
|
+
project: str | None = None,
|
|
139
|
+
agent: str | None = None,
|
|
140
|
+
category: str | None = None,
|
|
141
|
+
run_id: str | None = None,
|
|
142
|
+
limit: int = 100,
|
|
143
|
+
) -> list[Claim]:
|
|
144
|
+
sql, params = _build_filter_sql(
|
|
145
|
+
project=project,
|
|
146
|
+
agent=agent,
|
|
147
|
+
category=category,
|
|
148
|
+
run_id=run_id,
|
|
149
|
+
limit=limit,
|
|
150
|
+
)
|
|
151
|
+
rows = await self._r.fetch(sql, *params)
|
|
152
|
+
return [_row_to_claim(r) for r in rows]
|
|
153
|
+
|
|
154
|
+
async def supersede(self, old_id: str, new_claim: Claim) -> str:
|
|
155
|
+
existing = await self.get(old_id)
|
|
156
|
+
if existing is None:
|
|
157
|
+
msg = f"Cannot supersede unknown claim id: {old_id!r}"
|
|
158
|
+
raise ModuleError(msg)
|
|
159
|
+
if new_claim.supersedes is None:
|
|
160
|
+
new_claim = new_claim.model_copy(update={"supersedes": old_id})
|
|
161
|
+
elif new_claim.supersedes != old_id:
|
|
162
|
+
msg = f"new_claim.supersedes={new_claim.supersedes!r} does not match old_id={old_id!r}"
|
|
163
|
+
raise ModuleError(msg)
|
|
164
|
+
return await self.put(new_claim)
|
|
165
|
+
|
|
166
|
+
def stream(
|
|
167
|
+
self,
|
|
168
|
+
*,
|
|
169
|
+
project: str | None = None,
|
|
170
|
+
agent: str | None = None,
|
|
171
|
+
category: str | None = None,
|
|
172
|
+
run_id: str | None = None,
|
|
173
|
+
) -> AsyncIterator[Claim]:
|
|
174
|
+
sql, params = _build_filter_sql(
|
|
175
|
+
project=project,
|
|
176
|
+
agent=agent,
|
|
177
|
+
category=category,
|
|
178
|
+
run_id=run_id,
|
|
179
|
+
limit=None,
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
async def _agen() -> AsyncIterator[Claim]:
|
|
183
|
+
rows = await self._r.fetch(sql, *params)
|
|
184
|
+
for r in rows:
|
|
185
|
+
yield _row_to_claim(r)
|
|
186
|
+
|
|
187
|
+
return _agen()
|
|
188
|
+
|
|
189
|
+
async def delete(
|
|
190
|
+
self,
|
|
191
|
+
*,
|
|
192
|
+
run_id: str | None = None,
|
|
193
|
+
older_than: datetime | None = None,
|
|
194
|
+
category: str | None = None,
|
|
195
|
+
) -> int:
|
|
196
|
+
if run_id is None and older_than is None and category is None:
|
|
197
|
+
msg = "delete() requires at least one filter; refusing to wipe every claim."
|
|
198
|
+
raise ModuleError(msg)
|
|
199
|
+
where: list[str] = []
|
|
200
|
+
params: list[Any] = []
|
|
201
|
+
next_idx = 1
|
|
202
|
+
if run_id is not None:
|
|
203
|
+
where.append(f"run_id = ${next_idx}")
|
|
204
|
+
params.append(run_id)
|
|
205
|
+
next_idx += 1
|
|
206
|
+
if category is not None:
|
|
207
|
+
where.append(f"category = ${next_idx}")
|
|
208
|
+
params.append(category)
|
|
209
|
+
next_idx += 1
|
|
210
|
+
if older_than is not None:
|
|
211
|
+
where.append(f"created_at < ${next_idx}")
|
|
212
|
+
params.append(older_than)
|
|
213
|
+
next_idx += 1
|
|
214
|
+
sql = f"DELETE FROM {_CLAIMS_TABLE} WHERE " + " AND ".join( # noqa: S608 # nosec B608
|
|
215
|
+
where,
|
|
216
|
+
)
|
|
217
|
+
return await self._r.execute_returning_count(sql, *params)
|
|
218
|
+
|
|
219
|
+
def capabilities(self) -> set[str]:
|
|
220
|
+
return {"transactions"}
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
# ----------------------------------------------------------------------
|
|
224
|
+
# Helpers
|
|
225
|
+
# ----------------------------------------------------------------------
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _row_to_claim(row: Any) -> Claim:
|
|
229
|
+
"""Convert an asyncpg row (dict-like) into a `Claim`.
|
|
230
|
+
|
|
231
|
+
asyncpg returns `Record` objects which support `row["col"]`. JSONB
|
|
232
|
+
payloads come back already-parsed when the column is declared
|
|
233
|
+
`jsonb`; for the dict-codec edge case we fall back to
|
|
234
|
+
`json.loads`.
|
|
235
|
+
"""
|
|
236
|
+
payload = row["payload"]
|
|
237
|
+
if isinstance(payload, str):
|
|
238
|
+
payload = json.loads(payload)
|
|
239
|
+
created = row["created_at"]
|
|
240
|
+
if isinstance(created, str):
|
|
241
|
+
created = datetime.fromisoformat(created)
|
|
242
|
+
return Claim(
|
|
243
|
+
id=row["id"],
|
|
244
|
+
project=row["project"],
|
|
245
|
+
agent=row["agent"],
|
|
246
|
+
run_id=row["run_id"],
|
|
247
|
+
category=row["category"],
|
|
248
|
+
payload=payload,
|
|
249
|
+
supersedes=row["supersedes"],
|
|
250
|
+
created_at=created,
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _build_filter_sql(
|
|
255
|
+
*,
|
|
256
|
+
project: str | None,
|
|
257
|
+
agent: str | None,
|
|
258
|
+
category: str | None,
|
|
259
|
+
run_id: str | None,
|
|
260
|
+
limit: int | None,
|
|
261
|
+
) -> tuple[str, tuple[Any, ...]]:
|
|
262
|
+
"""Compose a SELECT with conjunctive filters and an optional LIMIT.
|
|
263
|
+
|
|
264
|
+
Emits asyncpg's `$1, $2, ...` placeholders (numbered positionally,
|
|
265
|
+
not the `?` aiosqlite uses).
|
|
266
|
+
"""
|
|
267
|
+
where: list[str] = []
|
|
268
|
+
params: list[Any] = []
|
|
269
|
+
next_idx = 1
|
|
270
|
+
|
|
271
|
+
def _add(column: str, value: Any) -> None:
|
|
272
|
+
nonlocal next_idx
|
|
273
|
+
where.append(f"{column} = ${next_idx}")
|
|
274
|
+
params.append(value)
|
|
275
|
+
next_idx += 1
|
|
276
|
+
|
|
277
|
+
if project is not None:
|
|
278
|
+
_add("project", project)
|
|
279
|
+
if agent is not None:
|
|
280
|
+
_add("agent", agent)
|
|
281
|
+
if category is not None:
|
|
282
|
+
_add("category", category)
|
|
283
|
+
if run_id is not None:
|
|
284
|
+
_add("run_id", run_id)
|
|
285
|
+
|
|
286
|
+
sql = f"SELECT * FROM {_CLAIMS_TABLE}" # noqa: S608 # nosec B608
|
|
287
|
+
if where:
|
|
288
|
+
sql += " WHERE " + " AND ".join(where)
|
|
289
|
+
sql += " ORDER BY created_at"
|
|
290
|
+
if limit is not None:
|
|
291
|
+
sql += f" LIMIT ${next_idx}"
|
|
292
|
+
params.append(limit)
|
|
293
|
+
return sql, tuple(params)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
__all__ = ["PostgresMemoryStore"]
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
CREATE TABLE IF NOT EXISTS claims (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
project TEXT NOT NULL,
|
|
4
|
+
agent TEXT NOT NULL,
|
|
5
|
+
run_id TEXT NOT NULL,
|
|
6
|
+
category TEXT NOT NULL,
|
|
7
|
+
payload JSONB NOT NULL,
|
|
8
|
+
supersedes TEXT,
|
|
9
|
+
created_at TIMESTAMPTZ NOT NULL
|
|
10
|
+
);
|
|
11
|
+
CREATE INDEX IF NOT EXISTS idx_claims_project_agent ON claims(project, agent);
|
|
12
|
+
CREATE INDEX IF NOT EXISTS idx_claims_run_id ON claims(run_id);
|
|
13
|
+
CREATE INDEX IF NOT EXISTS idx_claims_category ON claims(category);
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
CREATE EXTENSION IF NOT EXISTS vector;
|
|
2
|
+
CREATE TABLE IF NOT EXISTS vectors (
|
|
3
|
+
id TEXT PRIMARY KEY,
|
|
4
|
+
embedding vector(${dimensions}) NOT NULL,
|
|
5
|
+
text TEXT NOT NULL,
|
|
6
|
+
metadata JSONB NOT NULL DEFAULT '{}'::jsonb
|
|
7
|
+
);
|
|
8
|
+
CREATE INDEX IF NOT EXISTS idx_vectors_embedding
|
|
9
|
+
ON vectors USING hnsw (embedding vector_cosine_ops);
|
|
10
|
+
ALTER TABLE vectors
|
|
11
|
+
ADD COLUMN IF NOT EXISTS embedding_tsv tsvector
|
|
12
|
+
GENERATED ALWAYS AS (to_tsvector('english', coalesce(text, ''))) STORED;
|
|
13
|
+
CREATE INDEX IF NOT EXISTS idx_vectors_tsv
|
|
14
|
+
ON vectors USING gin (embedding_tsv);
|
|
File without changes
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
"""`PostgresVectorStore` — `VectorStore` over Postgres + pgvector.
|
|
2
|
+
|
|
3
|
+
Vectors are stored in a `vectors` table with a typed `vector(N)`
|
|
4
|
+
column. With `init_schema()` provisioned, an HNSW index accelerates
|
|
5
|
+
similarity search via pgvector's cosine-distance operator `<=>`;
|
|
6
|
+
without bootstrap the driver still works (sequential cosine scan)
|
|
7
|
+
but doesn't claim `native_ann`.
|
|
8
|
+
|
|
9
|
+
Score conversion: pgvector's `<=>` returns cosine *distance* in
|
|
10
|
+
`[0, 2]` (0 = identical, 1 = orthogonal, 2 = anti-correlated).
|
|
11
|
+
The locked contract requires similarity in `[0, 1]` (1 = identical,
|
|
12
|
+
0 = orthogonal-or-anti-correlated). We compute
|
|
13
|
+
`GREATEST(0.0, 1.0 - (embedding <=> $1))` at the SQL boundary so
|
|
14
|
+
cross-driver comparisons remain meaningful.
|
|
15
|
+
|
|
16
|
+
Per ADR-0014 every code path is async (asyncpg, not psycopg).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import json
|
|
22
|
+
from types import TracebackType
|
|
23
|
+
from typing import Any, Self
|
|
24
|
+
|
|
25
|
+
import asyncpg
|
|
26
|
+
from agentforge_core.contracts.vector_store import VectorStore
|
|
27
|
+
from agentforge_core.values.vector import VectorItem, VectorMatch
|
|
28
|
+
|
|
29
|
+
from agentforge_memory_postgres._migrator import PostgresMigrator
|
|
30
|
+
from agentforge_memory_postgres._runner import PostgresRunner, _AsyncpgPoolRunner
|
|
31
|
+
|
|
32
|
+
# Table is a framework constant; all SQL composed from it is
|
|
33
|
+
# parameterised via asyncpg's `$1, $2, ...` placeholders. The S608 /
|
|
34
|
+
# B608 noqa annotations below are explicit acknowledgements of that.
|
|
35
|
+
_VECTORS_TABLE = "vectors"
|
|
36
|
+
|
|
37
|
+
_UPSERT_VECTOR_SQL = (
|
|
38
|
+
f"INSERT INTO {_VECTORS_TABLE} (id, embedding, text, metadata) " # noqa: S608 # nosec B608
|
|
39
|
+
"VALUES ($1, $2, $3, $4::jsonb) "
|
|
40
|
+
"ON CONFLICT (id) DO UPDATE SET "
|
|
41
|
+
" embedding = EXCLUDED.embedding, "
|
|
42
|
+
" text = EXCLUDED.text, "
|
|
43
|
+
" metadata = EXCLUDED.metadata"
|
|
44
|
+
)
|
|
45
|
+
_SELECT_EXISTING_IDS = f"SELECT id FROM {_VECTORS_TABLE} WHERE id = ANY($1::text[])" # noqa: S608 # nosec B608
|
|
46
|
+
_DELETE_VECTORS_BY_IDS = f"DELETE FROM {_VECTORS_TABLE} WHERE id = ANY($1::text[])" # noqa: S608 # nosec B608
|
|
47
|
+
_SEARCH_VECTORS_SQL = (
|
|
48
|
+
f"SELECT id, text, metadata, " # noqa: S608 # nosec B608
|
|
49
|
+
f" GREATEST(0.0, 1.0 - (embedding <=> $1)) AS score "
|
|
50
|
+
f" FROM {_VECTORS_TABLE} "
|
|
51
|
+
f" WHERE metadata @> $2::jsonb "
|
|
52
|
+
f" ORDER BY embedding <=> $1 "
|
|
53
|
+
f" LIMIT $3"
|
|
54
|
+
)
|
|
55
|
+
_LEXICAL_SEARCH_SQL = (
|
|
56
|
+
f"WITH ranked AS (" # noqa: S608 # nosec B608
|
|
57
|
+
f" SELECT id, text, metadata, "
|
|
58
|
+
f" ts_rank_cd(embedding_tsv, plainto_tsquery('english', $1)) AS raw "
|
|
59
|
+
f" FROM {_VECTORS_TABLE} "
|
|
60
|
+
f" WHERE embedding_tsv @@ plainto_tsquery('english', $1) "
|
|
61
|
+
f" AND metadata @> $2::jsonb "
|
|
62
|
+
f" ORDER BY raw DESC "
|
|
63
|
+
f" LIMIT $3"
|
|
64
|
+
f") "
|
|
65
|
+
f"SELECT id, text, metadata, "
|
|
66
|
+
f" CASE WHEN MAX(raw) OVER () > 0 "
|
|
67
|
+
f" THEN raw / MAX(raw) OVER () "
|
|
68
|
+
f" ELSE 0.0 "
|
|
69
|
+
f" END AS score "
|
|
70
|
+
f" FROM ranked "
|
|
71
|
+
f" ORDER BY raw DESC"
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class PostgresVectorStore(VectorStore):
|
|
76
|
+
"""`VectorStore` over Postgres + pgvector. Dimensions pinned at
|
|
77
|
+
construction.
|
|
78
|
+
|
|
79
|
+
Use `from_dsn(dsn, dimensions=N)` for ergonomic construction; the
|
|
80
|
+
bare constructor accepts an injected `PostgresRunner` so unit tests
|
|
81
|
+
can fake asyncpg without spinning up Postgres.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
def __init__(
|
|
85
|
+
self,
|
|
86
|
+
*,
|
|
87
|
+
runner: PostgresRunner,
|
|
88
|
+
dimensions: int,
|
|
89
|
+
ann_indexed: bool = False,
|
|
90
|
+
) -> None:
|
|
91
|
+
if dimensions < 1:
|
|
92
|
+
msg = f"dimensions must be >= 1, got {dimensions}"
|
|
93
|
+
raise ValueError(msg)
|
|
94
|
+
self._r = runner
|
|
95
|
+
self._dim = dimensions
|
|
96
|
+
self._ann = ann_indexed
|
|
97
|
+
|
|
98
|
+
# ------------------------------------------------------------------
|
|
99
|
+
# Construction / lifecycle
|
|
100
|
+
# ------------------------------------------------------------------
|
|
101
|
+
|
|
102
|
+
@classmethod
|
|
103
|
+
async def from_dsn(
|
|
104
|
+
cls,
|
|
105
|
+
dsn: str,
|
|
106
|
+
*,
|
|
107
|
+
dimensions: int,
|
|
108
|
+
min_size: int = 1,
|
|
109
|
+
max_size: int = 10,
|
|
110
|
+
) -> Self:
|
|
111
|
+
"""Open an asyncpg pool and return a vector store with the
|
|
112
|
+
pgvector codec registered on every pooled connection."""
|
|
113
|
+
pool = await asyncpg.create_pool(dsn=dsn, min_size=min_size, max_size=max_size)
|
|
114
|
+
return cls(
|
|
115
|
+
runner=_AsyncpgPoolRunner(pool, setup_pgvector=True),
|
|
116
|
+
dimensions=dimensions,
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
async def __aenter__(self) -> Self:
|
|
120
|
+
return self
|
|
121
|
+
|
|
122
|
+
async def __aexit__(
|
|
123
|
+
self,
|
|
124
|
+
exc_type: type[BaseException] | None,
|
|
125
|
+
exc: BaseException | None,
|
|
126
|
+
tb: TracebackType | None,
|
|
127
|
+
) -> None:
|
|
128
|
+
await self.close()
|
|
129
|
+
|
|
130
|
+
def migrator(self) -> PostgresMigrator:
|
|
131
|
+
"""Return a `PostgresMigrator` pre-configured with the
|
|
132
|
+
``dimensions`` template variable + the vector-store
|
|
133
|
+
migrations subdirectory (feat-024 v0.3 follow-up).
|
|
134
|
+
|
|
135
|
+
The vector migrations use ``vector(${dimensions})`` placeholders
|
|
136
|
+
that the migrator renders at apply time. Checksums are
|
|
137
|
+
computed over the un-substituted template, so re-deploying
|
|
138
|
+
with a different `dimensions` value doesn't trigger drift
|
|
139
|
+
detection.
|
|
140
|
+
|
|
141
|
+
Migration files live under
|
|
142
|
+
``migrations/vector/`` (vector-store specific; id range
|
|
143
|
+
0100-0199); the shared ``0000_migrations_table`` bootstraps
|
|
144
|
+
the tracking table the first time any store applies it.
|
|
145
|
+
"""
|
|
146
|
+
from pathlib import Path # noqa: PLC0415
|
|
147
|
+
|
|
148
|
+
path = Path(__file__).parent / "migrations" / "vector"
|
|
149
|
+
return PostgresMigrator(
|
|
150
|
+
self._r,
|
|
151
|
+
variables={"dimensions": str(self._dim)},
|
|
152
|
+
migrations_path=path,
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
async def init_schema(self) -> None:
|
|
156
|
+
"""Provision the vectors table + HNSW index + feat-022
|
|
157
|
+
tsvector column via the migration framework (feat-024).
|
|
158
|
+
Idempotent.
|
|
159
|
+
|
|
160
|
+
After this returns, the store declares the `"native_ann"`
|
|
161
|
+
and `"hybrid_search"` capabilities — the indexes are in
|
|
162
|
+
place. Skip this for read-only workloads or when the schema
|
|
163
|
+
is managed externally.
|
|
164
|
+
"""
|
|
165
|
+
await self.migrator().apply_pending()
|
|
166
|
+
self._ann = True
|
|
167
|
+
|
|
168
|
+
async def close(self) -> None:
|
|
169
|
+
await self._r.close()
|
|
170
|
+
|
|
171
|
+
def dimensions(self) -> int:
|
|
172
|
+
return self._dim
|
|
173
|
+
|
|
174
|
+
# ------------------------------------------------------------------
|
|
175
|
+
# VectorStore contract
|
|
176
|
+
# ------------------------------------------------------------------
|
|
177
|
+
|
|
178
|
+
async def upsert(self, items: list[VectorItem]) -> None:
|
|
179
|
+
for item in items:
|
|
180
|
+
if len(item.vector) != self._dim:
|
|
181
|
+
msg = (
|
|
182
|
+
f"vector for id={item.id!r} has length {len(item.vector)} "
|
|
183
|
+
f"but store dimensions={self._dim}"
|
|
184
|
+
)
|
|
185
|
+
raise ValueError(msg)
|
|
186
|
+
await self._r.execute(
|
|
187
|
+
_UPSERT_VECTOR_SQL,
|
|
188
|
+
item.id,
|
|
189
|
+
list(item.vector),
|
|
190
|
+
item.text,
|
|
191
|
+
json.dumps(dict(item.metadata)),
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
async def search(
|
|
195
|
+
self,
|
|
196
|
+
query_vector: tuple[float, ...],
|
|
197
|
+
*,
|
|
198
|
+
limit: int = 5,
|
|
199
|
+
filter_metadata: dict[str, Any] | None = None,
|
|
200
|
+
) -> list[VectorMatch]:
|
|
201
|
+
if limit < 1:
|
|
202
|
+
msg = f"limit must be >= 1, got {limit}"
|
|
203
|
+
raise ValueError(msg)
|
|
204
|
+
if len(query_vector) != self._dim:
|
|
205
|
+
msg = f"query vector has length {len(query_vector)} but store dimensions={self._dim}"
|
|
206
|
+
raise ValueError(msg)
|
|
207
|
+
|
|
208
|
+
# The `metadata @> $2::jsonb` predicate is conjunctive: every
|
|
209
|
+
# key/value in `filter_metadata` must be present in the row's
|
|
210
|
+
# JSONB. Empty filter (`{}`) matches everything.
|
|
211
|
+
rows = await self._r.fetch(
|
|
212
|
+
_SEARCH_VECTORS_SQL,
|
|
213
|
+
list(query_vector),
|
|
214
|
+
json.dumps(dict(filter_metadata or {})),
|
|
215
|
+
limit,
|
|
216
|
+
)
|
|
217
|
+
return [
|
|
218
|
+
VectorMatch(
|
|
219
|
+
id=str(row["id"]),
|
|
220
|
+
text=str(row["text"]),
|
|
221
|
+
metadata=_ensure_dict(row["metadata"]),
|
|
222
|
+
score=float(row["score"]),
|
|
223
|
+
)
|
|
224
|
+
for row in rows
|
|
225
|
+
]
|
|
226
|
+
|
|
227
|
+
async def lexical_search(
|
|
228
|
+
self,
|
|
229
|
+
query: str,
|
|
230
|
+
*,
|
|
231
|
+
limit: int = 5,
|
|
232
|
+
filter_metadata: dict[str, Any] | None = None,
|
|
233
|
+
) -> list[VectorMatch]:
|
|
234
|
+
if limit < 1:
|
|
235
|
+
msg = f"limit must be >= 1, got {limit}"
|
|
236
|
+
raise ValueError(msg)
|
|
237
|
+
if not self._ann:
|
|
238
|
+
msg = (
|
|
239
|
+
"PostgresVectorStore.lexical_search requires init_schema() "
|
|
240
|
+
"to have run (the embedding_tsv column + GIN index live "
|
|
241
|
+
"alongside the HNSW vector index)."
|
|
242
|
+
)
|
|
243
|
+
raise RuntimeError(msg)
|
|
244
|
+
rows = await self._r.fetch(
|
|
245
|
+
_LEXICAL_SEARCH_SQL,
|
|
246
|
+
query,
|
|
247
|
+
json.dumps(dict(filter_metadata or {})),
|
|
248
|
+
limit,
|
|
249
|
+
)
|
|
250
|
+
return [
|
|
251
|
+
VectorMatch(
|
|
252
|
+
id=str(row["id"]),
|
|
253
|
+
text=str(row["text"]),
|
|
254
|
+
metadata=_ensure_dict(row["metadata"]),
|
|
255
|
+
score=float(row["score"]),
|
|
256
|
+
)
|
|
257
|
+
for row in rows
|
|
258
|
+
]
|
|
259
|
+
|
|
260
|
+
async def delete(self, ids: list[str]) -> int:
|
|
261
|
+
if not ids:
|
|
262
|
+
return 0
|
|
263
|
+
existing_rows = await self._r.fetch(_SELECT_EXISTING_IDS, list(ids))
|
|
264
|
+
existing = {str(r["id"]) for r in existing_rows}
|
|
265
|
+
if not existing:
|
|
266
|
+
return 0
|
|
267
|
+
await self._r.execute(_DELETE_VECTORS_BY_IDS, list(existing))
|
|
268
|
+
return len(existing)
|
|
269
|
+
|
|
270
|
+
def capabilities(self) -> set[str]:
|
|
271
|
+
"""`native_ann` + `hybrid_search` are both declared **only**
|
|
272
|
+
after `init_schema()` provisions the HNSW + GIN indexes.
|
|
273
|
+
Without bootstrap the driver still does cosine search as a
|
|
274
|
+
brute-force fallback, but lexical search would fail — so the
|
|
275
|
+
capability vocabulary stays honest per ADR-0009."""
|
|
276
|
+
caps: set[str] = set()
|
|
277
|
+
if self._ann:
|
|
278
|
+
caps.add("native_ann")
|
|
279
|
+
caps.add("hybrid_search")
|
|
280
|
+
return caps
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _ensure_dict(value: Any) -> dict[str, Any]:
|
|
284
|
+
"""asyncpg returns JSONB as parsed Python objects via its codec;
|
|
285
|
+
str fallback covers the (uncommon) raw-text path."""
|
|
286
|
+
if isinstance(value, dict):
|
|
287
|
+
return value
|
|
288
|
+
if isinstance(value, str):
|
|
289
|
+
return dict(json.loads(value)) if value else {}
|
|
290
|
+
return {}
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
__all__ = ["PostgresVectorStore"]
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agentforge-memory-postgres
|
|
3
|
+
Version: 0.2.3
|
|
4
|
+
Summary: Postgres + pgvector-backed MemoryStore and VectorStore for AgentForge
|
|
5
|
+
Project-URL: Homepage, https://github.com/Scaffoldic/agentforge-py
|
|
6
|
+
Project-URL: Repository, https://github.com/Scaffoldic/agentforge-py
|
|
7
|
+
Project-URL: Documentation, https://github.com/Scaffoldic/agentforge-py
|
|
8
|
+
Project-URL: Changelog, https://github.com/Scaffoldic/agentforge-py/blob/main/CHANGELOG.md
|
|
9
|
+
Project-URL: Issues, https://github.com/Scaffoldic/agentforge-py/issues
|
|
10
|
+
Author: The AgentForge Authors
|
|
11
|
+
License-Expression: Apache-2.0
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: agent,ai,memory,pgvector,postgres,rag,vector
|
|
14
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Database
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.13
|
|
23
|
+
Requires-Dist: agentforge-core~=0.2.3
|
|
24
|
+
Requires-Dist: asyncpg>=0.30
|
|
25
|
+
Requires-Dist: pgvector>=0.3
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# agentforge-memory-postgres
|
|
29
|
+
|
|
30
|
+
Postgres + [pgvector](https://github.com/pgvector/pgvector)-backed
|
|
31
|
+
`MemoryStore` and `VectorStore` for the AgentForge framework.
|
|
32
|
+
|
|
33
|
+
## What this is
|
|
34
|
+
|
|
35
|
+
Sister package to `agentforge-memory-sqlite`. Same locked contracts,
|
|
36
|
+
same conformance suites — but backed by Postgres with `asyncpg` for
|
|
37
|
+
real-world scale, multi-writer concurrency, and managed-database
|
|
38
|
+
guarantees (RDS, Neon, Supabase, etc.).
|
|
39
|
+
|
|
40
|
+
- **`PostgresMemoryStore`** — claim audit log over a single `claims`
|
|
41
|
+
table with composite indices on common filter combinations
|
|
42
|
+
(`project, agent`, `run_id`, `category`).
|
|
43
|
+
- **`PostgresVectorStore`** — semantic search over a `vectors` table
|
|
44
|
+
with a pgvector HNSW index (`vector_cosine_ops`). Cosine distance
|
|
45
|
+
is converted to clamped `[0, 1]` similarity at the SQL boundary
|
|
46
|
+
per the locked `VectorStore` contract.
|
|
47
|
+
|
|
48
|
+
Both pass `agentforge_core.testing.run_memory_conformance` and
|
|
49
|
+
`run_vector_conformance` against a real Postgres (gated on
|
|
50
|
+
`RUN_LIVE_POSTGRES=1` in CI; always on locally via docker compose).
|
|
51
|
+
|
|
52
|
+
## Usage
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
from agentforge_memory_postgres import PostgresMemoryStore, PostgresVectorStore
|
|
56
|
+
|
|
57
|
+
dsn = "postgresql://postgres:postgres@localhost:5432/agentforge"
|
|
58
|
+
|
|
59
|
+
async with PostgresMemoryStore.from_dsn(dsn) as memory:
|
|
60
|
+
await memory.init_schema() # idempotent
|
|
61
|
+
...
|
|
62
|
+
|
|
63
|
+
async with PostgresVectorStore.from_dsn(dsn, dimensions=1024) as vectors:
|
|
64
|
+
await vectors.init_schema() # provisions HNSW index
|
|
65
|
+
...
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
`init_schema()` is opt-in (idempotent `CREATE TABLE / EXTENSION /
|
|
69
|
+
INDEX IF NOT EXISTS`). Skip it for read-only workloads or when the
|
|
70
|
+
schema is managed externally; required before first write for full
|
|
71
|
+
correctness.
|
|
72
|
+
|
|
73
|
+
## Local development
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
docker compose -f docker-compose.dev.yml up -d
|
|
77
|
+
RUN_LIVE_POSTGRES=1 \
|
|
78
|
+
POSTGRES_URL=postgresql://postgres:postgres@localhost:5432/agentforge \
|
|
79
|
+
uv run pytest packages/agentforge-memory-postgres/tests/integration -v
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
The compose file ships `pgvector/pgvector:pg16`, which bundles
|
|
83
|
+
Postgres 16 with the pgvector extension preinstalled.
|
|
84
|
+
|
|
85
|
+
## Capabilities
|
|
86
|
+
|
|
87
|
+
- **Memory**: `{"transactions"}` — every `put` / `supersede` runs
|
|
88
|
+
inside an asyncpg transaction.
|
|
89
|
+
- **Vector**: `{"native_ann"}` is declared **only** after
|
|
90
|
+
`init_schema()` provisions the HNSW index. Without bootstrap the
|
|
91
|
+
driver still works (sequential cosine scan), but it doesn't claim
|
|
92
|
+
ANN — the capability vocabulary is honest per ADR-0009.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
agentforge_memory_postgres/__init__.py,sha256=liNKxye7Ytd3JJmOZu3_njqM59UDjSl-9r_2ACK1ASI,676
|
|
2
|
+
agentforge_memory_postgres/_migrator.py,sha256=1IbtqvtUFRWhVX-3tbkAi-Jw8pKcuFfa_zkfVXx0W3o,5374
|
|
3
|
+
agentforge_memory_postgres/_runner.py,sha256=BtFTmDjJelNhfUIcDmVUgu3ojzfv92TGcO49Ea8TjD8,4994
|
|
4
|
+
agentforge_memory_postgres/memory.py,sha256=5rL_wT0Qct8Gl5mmCMXjwQi0Je5S2g1woEX_7t_p7ec,9765
|
|
5
|
+
agentforge_memory_postgres/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
agentforge_memory_postgres/vector.py,sha256=vF46PdYENZFYc60LTnVTgOfM1bEmyIZZXyUEq1SgecM,10323
|
|
7
|
+
agentforge_memory_postgres/migrations/0000_migrations_table.sql,sha256=VoCG5tsQp7pBTaLXqshq2NwB-Tf-jh2gjQi8jxx9ec0,201
|
|
8
|
+
agentforge_memory_postgres/migrations/0001_initial.sql,sha256=sjcximXWjCitCTvZcF6asKvq3xIGzig35smioEwcuUM,491
|
|
9
|
+
agentforge_memory_postgres/migrations/vector/0000_migrations_table.sql,sha256=VoCG5tsQp7pBTaLXqshq2NwB-Tf-jh2gjQi8jxx9ec0,201
|
|
10
|
+
agentforge_memory_postgres/migrations/vector/0100_vectors.sql,sha256=exodIYuVSclbmgpZKgBD0HRjHu99sa-OhCYPJdMcIt8,575
|
|
11
|
+
agentforge_memory_postgres-0.2.3.dist-info/METADATA,sha256=mIrXu31h0vEPbdAtr57lI7Fw67ciEviuFTlW8yzbdN8,3643
|
|
12
|
+
agentforge_memory_postgres-0.2.3.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
13
|
+
agentforge_memory_postgres-0.2.3.dist-info/entry_points.txt,sha256=LQBCkv2EKz3L2dsQgTKPbrh7AYq4KjL5HlPPXpvA5O4,178
|
|
14
|
+
agentforge_memory_postgres-0.2.3.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
15
|
+
agentforge_memory_postgres-0.2.3.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|