Skip to content

Commit 2602d44

Browse files
authored
Serve blob reads on the Postgres tier (#218)
`{"blob": {"read": true}}` (#106) is what lets a wasm32-areev-io module read the attachment a trigger's connector already filed -- by address, read-only, every read journaled as a blob_read Observation. On PostgreSQL the broker answered 501: the read is lock-free because it goes to the .blobs sidecar without opening the database, and that sidecar is an embedded-backend thing. So on the tier the server product actually runs on, the whole class of attachment-parsing capability tools was unavailable -- and the documented alternative, letting the tool open the memory itself, means handing it a credential to that memory, which is the thing a capability tool exists to avoid. read_blob_offline now serves a postgres://...?schema=... locator too: its own short-lived connection, one schema-qualified SELECT against the in-schema blobs table, closed on return. It still never opens the memory, so it cannot contend with the run holding it -- and here there is no exclusive lock to avoid in the first place, which makes this cheaper than the embedded case rather than harder. Qualifying the table (#181) keeps it independent of search_path, so it is safe behind a pooler. Blobs are never sealed on this backend, because the blob key derives from the page cipher Postgres refuses, so that branch cannot arise. The broker's 501 is deleted rather than narrowed: its call site is unchanged, because widening the function was the smaller change than adding a second one. `areev blob get` carried the same restriction -- it skipped the lock-free path for a DSN, a workaround for the limitation this removes. Lifted, so the two blob-reading surfaces behave identically instead of diverging for a reason that no longer holds. Two things cleaned up on the way. The "is this a DSN?" test existed in four copies (CLI, both bindings, and the one this change would have added); it now lives once in the store, which owns the concept, and the other three call it. And the row read uses try_get rather than get, so a column whose type ever surprises us is an error the broker reports instead of a panic that takes the serving thread with it. Conformance gains a case that puts a blob in, holds the memory OPEN, and reads it by address; it runs against both backends and is registered in one place. The Backend trait gains `locator` for it -- a file path or a DSN, the seam any case needs when the API under test takes an address rather than a handle. 83 postgres conformance cases and 69 embedded against a real pgvector:pg16, 2,702 workspace tests, 124 pytest, 72 node --test, clippy -D warnings clean including --features postgres. The Postgres path was mutation-checked, and `areev blob get` was driven end-to-end against a live schema while another handle held the memory. Docs moved with it: run.md's "Embedded backend only" warning, mcp-reference's sidecar claim, and the store crate notes.
1 parent 20bcd2f commit 2602d44

11 files changed

Lines changed: 138 additions & 47 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,32 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
88

99
### Added
1010

11+
- **`areev::blob_get` works on the Postgres tier** — the whole class of
12+
attachment-parsing capability tools was unavailable on the backend the
13+
server tier actually runs on. `{"blob": {"read": true}}` (#106) is what lets
14+
a `wasm32-areev-io` module read the attachment a trigger's connector already
15+
filed, by address, read-only, every read journaled as a `blob_read`
16+
Observation. On PostgreSQL the broker answered `501`: the read is lock-free
17+
because it goes to the `.blobs` sidecar without opening the database, and
18+
that sidecar is an embedded-backend thing. The documented alternative — the
19+
tool opens the memory itself — needs handing the tool a credential to the
20+
memory, which is exactly what a capability tool exists to avoid.
21+
22+
`read_blob_offline` now serves a `postgres://…?schema=…` locator too: one
23+
short-lived connection of its own, one schema-qualified `SELECT` against the
24+
in-schema `blobs` table, closed on return. It still never opens the memory,
25+
so it cannot contend with the run holding it — and on this backend there is
26+
no exclusive lock to avoid in the first place, which makes it cheaper than
27+
the embedded case rather than harder. Qualifying the table (#181) keeps it
28+
independent of `search_path`, so it is safe behind a pooler. Blobs are never
29+
sealed here (the blob key derives from the page cipher, which Postgres
30+
refuses), so the sealed branch cannot arise.
31+
32+
`areev blob get` lifts the same restriction: it skipped the lock-free path
33+
for a DSN, a workaround for the limitation this removes, so the two
34+
blob-reading surfaces now behave identically
35+
([#202](https://github.com/AreevAI/areev/issues/202)).
36+
1137
- **CAL can summarise by frequency, extract from text, and navigate a JSON
1238
payload** (#209, #210, #211) — three reads that could only be done by
1339
over-fetching and finishing the job in host code, which also defeated

‎crates/areev-cli/src/main.rs‎

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use std::process::ExitCode;
1313
use areev_cal::{CalExecutor, CalExecutorConfig, AreevFacade};
1414
use areev_core::error::Hash;
1515
use areev_core::types::{ContentBlock, Event, Fact, Grain, TokenUsage, Tool};
16-
use areev_store::{Axis, Areev, Direction};
16+
use areev_store::{is_pg_dsn, Axis, Areev, Direction};
1717
use areev_loop_adapter::{now_ms, AreevSubstrate};
1818
use areev_loop::{Decision, Engine, ObserverType, Policy, RecStatus, RunOptions, ScopeSet, Severity};
1919

@@ -811,11 +811,6 @@ fn report_meta_warnings(facade: &areev_cal::AreevFacade) {
811811
}
812812
}
813813

814-
/// A `--mount` target is a postgres DSN rather than a file path.
815-
fn is_pg_dsn(target: &str) -> bool {
816-
target.starts_with("postgres://") || target.starts_with("postgresql://")
817-
}
818-
819814
/// Would this mount point at the SAME memory as the primary?
820815
///
821816
/// The embedded backend refuses that by construction — a second handle on one
@@ -1773,12 +1768,13 @@ Nothing was written — apply the snippet yourself (or rerun with your own paths
17731768
// attachment out of reach of the very `--tool-cmd` subprocess the run
17741769
// spawned to process it. Blobs are immutable, live beside the file, and
17751770
// carry their checksum as their address, so reading one needs neither the
1776-
// database nor a lock. A sealed blob still needs the memory's derived key,
1777-
// so that case falls through to the normal open below.
1778-
if cmd == "blob" && positional.first().map(String::as_str) == Some("get") && !is_pg_url {
1771+
// database nor a lock — on postgres, one connection of its own and a
1772+
// schema-qualified SELECT. A sealed blob still needs the memory's derived
1773+
// key, so that case falls through to the normal open below.
1774+
if cmd == "blob" && positional.first().map(String::as_str) == Some("get") {
17791775
let uri = positional
17801776
.get(1)
1781-
.ok_or("usage: areev blob get <cas-uri> --db <file>")?;
1777+
.ok_or("usage: areev blob get <cas-uri> --db <file|dsn>")?;
17821778
if let Some(bytes) = areev_store::read_blob_offline(&db, uri).map_err(|e| e.to_string())? {
17831779
use std::io::Write;
17841780
std::io::stdout().write_all(&bytes).map_err(|e| e.to_string())?;

‎crates/areev-conformance/src/cases/blobs_hybrid.rs‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,27 @@ pub fn cas_blob_roundtrip_and_gc(b: &dyn Backend) {
2323
assert!(m.get_blob(&uri).is_err(), "reclaimed blob is gone");
2424
}
2525

26+
/// `read_blob_offline` reaches a blob by address without opening the memory,
27+
/// on either backend (#202) — which is what lets a sandboxed tool read the
28+
/// attachment its own run filed while that run still holds the memory.
29+
pub fn blob_reads_without_opening_the_memory(b: &dyn Backend) {
30+
let uri = {
31+
let mut m = b.open_named("offline_blob");
32+
m.put_blob(b"attachment bytes").unwrap()
33+
};
34+
let locator = b.locator("offline_blob");
35+
let _held_open_throughout = b.open_named("offline_blob");
36+
37+
let got = areev_store::read_blob_offline(&locator, &uri)
38+
.expect("a stored blob is readable by address")
39+
.expect("a plaintext blob is not sealed");
40+
assert_eq!(got, b"attachment bytes");
41+
42+
let absent = format!("cas://sha256:{}", "b".repeat(64));
43+
assert!(areev_store::read_blob_offline(&locator, &absent).is_err());
44+
assert!(areev_store::read_blob_offline(&locator, "cas://sha256:zz").is_err());
45+
}
46+
2647
pub fn bm25_leg_finds_text(b: &dyn Backend) {
2748
let mut m = b.open();
2849
m.add(&fact("caller", "john", "allergic_to", "peanuts")).unwrap();

‎crates/areev-conformance/src/lib.rs‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,11 @@ pub trait Backend {
5252
self.try_open_named_with(name, opts).expect("open store")
5353
}
5454

55+
/// What a host names this memory by: a file path on the embedded backend,
56+
/// a `postgres://…?schema=<name>` DSN on postgres. For cases exercising an
57+
/// API that takes the memory's address rather than a handle.
58+
fn locator(&self, name: &str) -> String;
59+
5560
/// A scratch directory for interchange files (bundles). Backend-neutral:
5661
/// bundles are files regardless of where the store lives.
5762
fn scratch(&self) -> &Path;
@@ -98,6 +103,10 @@ impl Backend for TursoBackend {
98103
Areev::open_with(path.to_str().expect("utf8 path"), opts)
99104
}
100105

106+
fn locator(&self, name: &str) -> String {
107+
self.path_for(name).to_str().expect("utf8 path").to_string()
108+
}
109+
101110
fn scratch(&self) -> &Path {
102111
self.dir.path()
103112
}
@@ -163,6 +172,10 @@ impl Backend for PgBackend {
163172
Areev::open_postgres_with(&self.url, &schema, opts)
164173
}
165174

175+
fn locator(&self, name: &str) -> String {
176+
format!("{}?schema={}_{}", self.url, self.prefix, name)
177+
}
178+
166179
fn scratch(&self) -> &Path {
167180
self.scratch.path()
168181
}
@@ -239,6 +252,7 @@ macro_rules! for_each_conformance_case {
239252
// CAS blobs + hybrid legs
240253
$per_case!(cas_blob_roundtrip_and_gc);
241254
$per_case!(forget_reclaims_sole_referenced_blob);
255+
$per_case!(blob_reads_without_opening_the_memory);
242256
$per_case!(bm25_leg_finds_text);
243257
$per_case!(vector_leg_roundtrip);
244258
$per_case!(external_vectors_need_no_embedder);

‎crates/areev-js/src/lib.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -692,7 +692,7 @@ impl Areev {
692692
// leaving a handle behind — which on Node would need an explicit
693693
// close() nobody has a reference to.
694694
let anon = anon_key.as_deref().map(parse_anon_key).transpose()?;
695-
let is_pg = path.starts_with("postgres://") || path.starts_with("postgresql://");
695+
let is_pg = areev_store::is_pg_dsn(&path);
696696
let store = match (is_pg, passphrase) {
697697
(true, Some(_)) => {
698698
return Err(err(

‎crates/areev-py/src/lib.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -488,7 +488,7 @@ impl Areev {
488488
.detach(|| {
489489
// A postgres://…?schema=<name> DSN selects the server-tier
490490
// backend — same API, the memory lives in a Postgres schema.
491-
if path.starts_with("postgres://") || path.starts_with("postgresql://") {
491+
if areev_store::is_pg_dsn(&path) {
492492
return open_postgres_from_dsn(
493493
&path,
494494
tel,

‎crates/areev-run/src/broker.rs‎

Lines changed: 7 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -983,11 +983,13 @@ impl Broker {
983983

984984
/// Serve `POST /blob` from this memory's CAS store (#106).
985985
///
986-
/// The path, not a handle: [`areev_store::read_blob_offline`] reads the
987-
/// `.blobs` sidecar without opening the database, so serving a blob never
988-
/// contends with the driver's exclusive write lock on the same file. That
989-
/// is the same property that lets a `--tool-cmd` subprocess run
990-
/// `areev blob get` mid-run.
986+
/// The path, not a handle: [`areev_store::read_blob_offline`] never opens
987+
/// the memory, so serving a blob cannot contend with the run holding it.
988+
/// On the embedded backend it reads the `.blobs` sidecar beside the file,
989+
/// avoiding the driver's exclusive write lock; on postgres it opens its
990+
/// own short-lived connection and reads the in-schema `blobs` table, which
991+
/// takes no lock at all. That is the same property that lets a
992+
/// `--tool-cmd` subprocess run `areev blob get` mid-run.
991993
///
992994
/// Until a host calls this, blob reads are refused whatever a module
993995
/// declared — declaring is not granting here either.
@@ -1229,24 +1231,6 @@ fn serve_blob(
12291231
);
12301232
};
12311233

1232-
// The lock-free door is the `.blobs` sidecar, which is an EMBEDDED-backend
1233-
// thing: on Postgres a blob lives in-schema and reaching it means opening
1234-
// the memory. Said plainly and up front rather than letting the sidecar
1235-
// read miss and report "blob missing", which would send someone hunting
1236-
// for an attachment that is present and simply not reachable this way.
1237-
if db_path.starts_with("postgres://") || db_path.starts_with("postgresql://") {
1238-
return respond(
1239-
stream,
1240-
501,
1241-
&serde_json::json!({
1242-
"error": "blob reads from a sandboxed tool are not supported on the postgres \
1243-
backend: the lock-free path is the .blobs sidecar, which only the \
1244-
embedded backend has"
1245-
})
1246-
.to_string(),
1247-
);
1248-
}
1249-
12501234
match areev_store::read_blob_offline(&db_path, &req.uri) {
12511235
Ok(Some(bytes)) => {
12521236
note_blob_read(

‎crates/areev-store/CLAUDE.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,11 @@ Pg-only multi-writer race cases); extend it whenever store semantics change.
195195
instead of mixing vector spaces. Host config is never persisted here —
196196
the file describes itself, the host supplies capabilities.
197197
`tests/meta_tests.rs` covers persistence/reconciliation.
198+
- `read_blob_offline(locator, uri)` reads a blob by ADDRESS without opening the
199+
memory, on either backend (#202): the sidecar on embedded, a short-lived
200+
connection and a schema-qualified `SELECT blobs` on postgres. It takes no
201+
lock and no session state, which is what lets a sandboxed tool — or
202+
`areev blob get` — read an attachment while a run holds the memory.
198203
- CAS blob sidecar at `"{path}.blobs"`, git-style `hex[..2]/hex[2..]` fan-out:
199204
`put_blob` (idempotent, tmp+rename), `get_blob` (re-verifies sha256),
200205
`gc_blobs` (ref-count from live grains' `content_refs`). Free fn

‎crates/areev-store/src/lib.rs‎

Lines changed: 47 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1714,9 +1714,13 @@ fn projected_text(view: &DeserializedGrain) -> Option<String> {
17141714
pub fn read_blob_offline(db_path: &str, uri: &str) -> Result<Option<Vec<u8>>> {
17151715
use sha2::{Digest, Sha256};
17161716
let hex = Areev::cas_hex(uri)?;
1717-
let dir = std::path::PathBuf::from(format!("{db_path}.blobs"));
1718-
let raw = std::fs::read(fs_blob_path(&dir, hex))
1719-
.map_err(|_| AreevError::Storage(format!("blob missing: {uri}")))?;
1717+
let raw = if is_pg_dsn(db_path) {
1718+
read_blob_pg(db_path, hex, uri)?
1719+
} else {
1720+
let dir = std::path::PathBuf::from(format!("{db_path}.blobs"));
1721+
std::fs::read(fs_blob_path(&dir, hex))
1722+
.map_err(|_| AreevError::Storage(format!("blob missing: {uri}")))?
1723+
};
17201724
if blobcrypt::is_sealed(&raw) {
17211725
return Ok(None);
17221726
}
@@ -1726,6 +1730,46 @@ pub fn read_blob_offline(db_path: &str, uri: &str) -> Result<Option<Vec<u8>>> {
17261730
Ok(Some(raw))
17271731
}
17281732

1733+
/// Whether a memory locator names the postgres backend rather than a file.
1734+
///
1735+
/// One spelling, because every surface that takes a `--db`-shaped string has
1736+
/// to make this decision: the CLI, both bindings, and the blob read below.
1737+
pub fn is_pg_dsn(locator: &str) -> bool {
1738+
locator.starts_with("postgres://") || locator.starts_with("postgresql://")
1739+
}
1740+
1741+
/// The postgres half of [`read_blob_offline`]: its own short-lived connection,
1742+
/// one schema-qualified `SELECT`, closed on return.
1743+
///
1744+
/// No lock and no session state, so it cannot contend with the run holding the
1745+
/// schema. Qualifying the table (#181) is what keeps it independent of
1746+
/// `search_path`, so it is safe behind a pooler too.
1747+
#[cfg(feature = "postgres")]
1748+
fn read_blob_pg(dsn: &str, hex: &str, uri: &str) -> Result<Vec<u8>> {
1749+
let (url, schema) = pg::split_schema_url(dsn)?;
1750+
let raw = hex::decode(hex).map_err(|e| AreevError::Storage(e.to_string()))?;
1751+
let rt = tokio::runtime::Builder::new_current_thread()
1752+
.enable_all()
1753+
.build()
1754+
.map_err(|e| AreevError::Storage(e.to_string()))?;
1755+
let client = pgtls::connect(&rt, &url)?;
1756+
let sql = pg::qualify_tables("SELECT body FROM blobs WHERE hash = $1", &schema);
1757+
let rows = rt
1758+
.block_on(client.query(sql.as_str(), &[&raw]))
1759+
.map_err(pg::pg_err)?;
1760+
let row = rows
1761+
.first()
1762+
.ok_or_else(|| AreevError::Storage(format!("blob missing: {uri}")))?;
1763+
row.try_get::<_, Vec<u8>>(0).map_err(pg::pg_err)
1764+
}
1765+
1766+
#[cfg(not(feature = "postgres"))]
1767+
fn read_blob_pg(_dsn: &str, _hex: &str, _uri: &str) -> Result<Vec<u8>> {
1768+
Err(AreevError::Storage(
1769+
"this build lacks the postgres backend — rebuild with --features postgres-tls".into(),
1770+
))
1771+
}
1772+
17291773
/// Where the CAS blob payloads live: a `.blobs` fan-out directory next to
17301774
/// the memory file (embedded backend), or an in-schema `blobs` table
17311775
/// (postgres backend — a connection string has no "next to").

‎docs/mcp-reference.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -533,8 +533,9 @@ media is referenced rather than carried.
533533

534534
A tool that needs the bytes should take the `cas://` URI from the grain's
535535
`content_refs` (which `areev_recall` already returns) and fetch them out of
536-
band with `areev blob get`, which reads the sidecar without opening the memory
537-
and therefore works even while a run holds the writer. See
536+
band with `areev blob get`, which reads the blob by address without opening the
537+
memory — the `.blobs` sidecar on the embedded backend, one short-lived
538+
connection on postgres — and therefore works even while a run holds the writer. See
538539
[cookbook §17](cookbook.md).
539540

540541
---

0 commit comments

Comments
 (0)