[Bug] v2.3.0 Postgres migration rewrites the table once per json column, and an escaped NUL in a json column aborts it
Description
Two problems in the v2.3.0 json -> jsonb step, which every PostgreSQL user going from agno 2.0 - 2.2 to 3.x runs before v3.0.0.
_convert_json_to_jsonb sends one ALTER TABLE ... ALTER COLUMN c TYPE JSONB per column (v2_3_0.py#L273-L303, async #L443). Every type change rewrites the whole table and its indexes, so a sessions table with its seven json columns is rewritten seven times, all in one transaction (#L147) that holds the ACCESS EXCLUSIVE lock from the first ALTER to the end.
And USING c::jsonb fails on a json value that holds an escaped NUL (U+0000): json accepts it, jsonb does not (unsupported Unicode escape sequence). agno only strips NUL on write since 2.3.22, so tables written by 2.0 - 2.2 can have them. The step then aborts, the transaction rolls back after the rewrites it already did, every column stays json, and every later up() fails the same way.
Steps to Reproduce
Sessions table in the 2.2 layout (seven json columns), 3,000 synthetic sessions, no stamp, await MigrationManager(db).up(target_version="2.3.0", table_type="sessions"), with and without one run holding an escaped NUL. Script below (needs PG_DSN to a scratch database; creates and drops its own schema).
# agno's v2.3.0 migration step (json -> jsonb) on a sessions table in the layout agno 2.0 - 2.2 created
# (seven json columns), with synthetic data:
# - how many ALTER TABLE statements it sends and how often PostgreSQL rewrites the table,
# - what it does with a json value holding an escaped NUL, which a json column accepts and jsonb rejects.
# Needs PG_DSN: a sync SQLAlchemy URL (postgresql+psycopg://...) to a scratch database. Creates and drops
# the schema agno_v230_demo. Run with the agno version to check, for example
# (NO_NUL=1 leaves the NUL row out)
# uv run --no-project --python 3.12 --with 'agno==3.0.11' --with 'sqlalchemy==2.0.52' \
# --with 'psycopg[binary]==3.3.5' python agno_v2_3_0_json_to_jsonb_repro.py
import asyncio
import base64
import json
import logging
import os
import random
import time
from importlib.metadata import version
from sqlalchemy import create_engine, event, text
from sqlalchemy.exc import DBAPIError
from agno.db.migrations.manager import MigrationManager
from agno.db.postgres import PostgresDb
S = "agno_v230_demo"
DSN = os.environ["PG_DSN"]
JSON_COLUMNS = ("session_data", "agent_data", "team_data", "workflow_data", "metadata", "runs", "summary")
eng = create_engine(DSN)
def blob(rng, n):
return base64.b64encode(rng.randbytes(n * 3 // 4)).decode()
def run(rng, sid, j, content=None):
return {"run_id": f"{sid}-r{j}", "agent_id": "demo-agent", "status": "COMPLETED", "created_at": 1_700_000_000 + j,
"content": content if content is not None else blob(rng, 400),
"messages": [{"role": r, "content": blob(rng, 280)} for r in ("user", "assistant", "user", "assistant")]}
def create_json_sessions(table, n):
rng = random.Random(n)
cols = ", ".join(f"{c} json" for c in JSON_COLUMNS)
rows = []
for i in range(n):
sid = f"s-{i:05d}"
runs = [run(rng, sid, j) for j in range(5)]
if i == 1 and not os.environ.get("NO_NUL"):
runs[0]["content"] = "tool output with a \x00 byte"
rows.append({"sid": sid, "sd": json.dumps({"session_name": f"demo {sid}"}), "runs": json.dumps(runs),
"md": json.dumps({"source": "synthetic"})})
with eng.begin() as c:
c.execute(text(f"CREATE TABLE {S}.{table} (session_id varchar PRIMARY KEY, session_type varchar NOT NULL, "
f"agent_id varchar, team_id varchar, workflow_id varchar, user_id varchar, {cols}, "
"created_at bigint NOT NULL, updated_at bigint)"))
c.execute(text(f"CREATE INDEX idx_{table}_created_at ON {S}.{table} (created_at)"))
c.execute(text(f"INSERT INTO {S}.{table} (session_id, session_type, session_data, metadata, runs, created_at) "
"VALUES (:sid, 'agent', CAST(:sd AS json), CAST(:md AS json), CAST(:runs AS json), 1700000000)"), rows)
def scalar(sql, **params):
with eng.connect() as c:
return c.execute(text(sql), params).scalar()
def main():
print(f"agno {version('agno')}, SQLAlchemy {version('sqlalchemy')}, psycopg {version('psycopg')}, "
f"PostgreSQL {scalar('SHOW server_version')}")
logging.getLogger("agno").setLevel(logging.INFO)
with eng.begin() as c:
c.execute(text(f"DROP SCHEMA IF EXISTS {S} CASCADE"))
c.execute(text(f"CREATE SCHEMA {S}"))
try:
table = "old_sessions"
create_json_sessions(table, 3000)
before = scalar(f"SELECT runs::text FROM {S}.{table} WHERE session_id = 's-00002'")
print(f"3,000 sessions, runs column {scalar(f'SELECT sum(octet_length(runs::text)) FROM {S}.{table}') / 2**20:.1f} MB "
"as text, 7 json columns" + ("" if os.environ.get("NO_NUL") else ", one run holding an escaped NUL"))
db = PostgresDb(db_url=DSN, db_schema=S, session_table=table)
alters, nodes = [], []
@event.listens_for(db.db_engine, "before_cursor_execute")
def _start(conn, cursor, statement, parameters, context, executemany):
conn.info["t0"] = time.perf_counter()
@event.listens_for(db.db_engine, "after_cursor_execute")
def _end(conn, cursor, statement, parameters, context, executemany):
if statement.lstrip().upper().startswith("ALTER TABLE") and "JSONB" in statement.upper():
alters.append(time.perf_counter() - conn.info["t0"])
nodes.append(cursor.connection.execute("SELECT pg_relation_filenode(%s::regclass)", (f"{S}.{table}",)).fetchone()[0])
start_node = scalar("SELECT pg_relation_filenode(to_regclass(:n))", n=f"{S}.{table}")
try:
asyncio.run(MigrationManager(db).up(target_version="2.3.0", table_type="sessions"))
except DBAPIError as e:
print(f"v2.3.0 failed: {e.orig.diag.message_primary}")
rewrites = sum(1 for prev, node in zip([start_node] + nodes, nodes) if node != prev)
json_left = scalar("SELECT count(*) FROM information_schema.columns WHERE table_schema = :s AND table_name = :t "
"AND data_type = 'json'", s=S, t=table)
print(f"ALTER TABLE statements: {len(alters)}, table rewrites: {rewrites}, {sum(alters):.2f} s in ALTERs, "
f"json columns left: {json_left} of 7")
if json_left == 0:
nul_run = scalar(f"SELECT runs->0->>'content' FROM {S}.{table} WHERE session_id = 's-00001'")
same = scalar(f"SELECT runs = CAST(:b AS jsonb) FROM {S}.{table} WHERE session_id = 's-00002'", b=before)
print(f"session s-00001 first run content: {nul_run[:40]!r}; an untouched session's runs equal before and after: {same}")
finally:
with eng.begin() as c:
c.execute(text(f"DROP SCHEMA IF EXISTS {S} CASCADE"))
print(f"schema {S} dropped")
main()Agent Configuration (if applicable)
n/a
Expected Behavior
One rewrite of the table, and the step goes through an escaped NUL the way agno's writes do since 2.3.22.
Actual Behavior
3,000 sessions, runs column 25.6 MB as text, 7 json columns
ALTER TABLE statements: 7, table rewrites: 7, 1.73 s in ALTERs, json columns left: 0 of 7
3,000 sessions, runs column 25.6 MB as text, 7 json columns, one run holding an escaped NUL
v2.3.0 failed: unsupported Unicode escape sequence
ALTER TABLE statements: 5, table rewrites: 5, 1.14 s in ALTERs, json columns left: 7 of 7On a larger table (48.6 MB runs column) the seven ALTERs took 10.7 s against 1.1 s for one ALTER with the same seven clauses.
Screenshots or Logs (if applicable)
n/a
Environment
- OS: macOS
- Agno Version: 3.0.11 (`db/migrations/` unchanged on main)
- External Dependency Versions: SQLAlchemy 2.0.52, psycopg 3.3.5, PostgreSQL 15.18
- Additional Environment Details: Python 3.12Possible Solutions (optional)
Collect the table's json columns first and send one statement, ALTER TABLE t ALTER COLUMN a TYPE JSONB USING a::jsonb, ALTER COLUMN b TYPE JSONB USING b::jsonb, ...; PostgreSQL then does one pass (ALTER TABLE notes). Before it, find the rows whose text holds that escape (a strpos on c::text) and rewrite them with sanitize_postgres_strings, the sanitizer agno applies on write since 2.3.22. PR coming.
Source: agno-agi/agno