AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(backend): unbrick dev deploy — drop no-op cutover backfill, batch startup tenancy backfill (#13512)
Nicholas Tindle0a9f185a6fee
diff --git a/.github/workflows/platform-autogpt-deploy-dev.yaml b/.github/workflows/platform-autogpt-deploy-dev.yamlindex b415fb1b7b..7657d862ad 100644--- a/.github/workflows/platform-autogpt-deploy-dev.yaml+++ b/.github/workflows/platform-autogpt-deploy-dev.yaml@@ -12,6 +12,13 @@ on:required: truedefault: 'master'type: string+ resolve_rolled_back:+ description: >-+ Migration name to mark rolled-back before deploying (recovers a+ failed _prisma_migrations row, e.g. 20260415000000_org_tenancy_cutover)+ required: false+ default: ''+ type: stringpermissions:contents: 'read'@@ -39,6 +46,16 @@ jobs:python -m pip install --upgrade pippip install prisma+ - name: Resolve failed migration (manual dispatch only)+ if: ${{ github.event.inputs.resolve_rolled_back != '' }}+ working-directory: ./autogpt_platform/backend+ run: |+ python -m prisma migrate resolve --rolled-back "$MIGRATION_NAME"+ env:+ MIGRATION_NAME: ${{ github.event.inputs.resolve_rolled_back }}+ DATABASE_URL: ${{ secrets.BACKEND_DATABASE_URL }}+ DIRECT_URL: ${{ secrets.BACKEND_DATABASE_URL }}+- name: Run Backend Migrationsworking-directory: ./autogpt_platform/backendrun: |diff --git a/autogpt_platform/backend/backend/data/org_migration.py b/autogpt_platform/backend/backend/data/org_migration.pyindex b3d0e19d7b..5d17aa3f6b 100644--- a/autogpt_platform/backend/backend/data/org_migration.py+++ b/autogpt_platform/backend/backend/data/org_migration.py@@ -16,7 +16,9 @@ same moment the User row is created — not only when the backfill runs.import loggingimport reimport time-from typing import LiteralString+from collections.abc import Awaitable, Callable+from typing import TYPE_CHECKING, LiteralString+from uuid import uuid4from prisma.errors import UniqueViolationErrorfrom prisma.models import Organization@@ -24,8 +26,27 @@ from prisma.models import Organizationfrom backend.data.db import prisma, transactionfrom backend.util.json import SafeJson+if TYPE_CHECKING:+ from backend.data.redis_client import AsyncRedisClient+logger = logging.getLogger(__name__)+_MIGRATION_LOCK_RENEW_SCRIPT: LiteralString = """+if redis.call("GET", KEYS[1]) == ARGV[1] then+ return redis.call("EXPIRE", KEYS[1], tonumber(ARGV[2]))+end+return 0+"""++_MIGRATION_LOCK_RELEASE_SCRIPT: LiteralString = """+if redis.call("GET", KEYS[1]) == ARGV[1] then+ return redis.call("DEL", KEYS[1])+end+return 0+"""++_RenewLock = Callable[[], Awaitable[None]]+def _sanitize_slug(raw: str) -> str:"""Convert a string to a URL-safe slug: lowercase, alphanumeric + hyphens."""@@ -431,12 +452,59 @@ async def migrate_credit_transactions() -> int:return result-async def _assign_team_tenancy(table_sql: "LiteralString") -> int:+async def _assign_team_tenancy(+ table_sql: "LiteralString", renew_lock: _RenewLock | None = None+) -> int:"""Assign organizationId + teamId on a single table's unassigned rows."""- return await prisma.execute_raw(table_sql)+ updated = await prisma.execute_raw(table_sql)+ if renew_lock is not None:+ await renew_lock()+ return updated+++async def _assign_org_tenancy(+ table_sql: "LiteralString", renew_lock: _RenewLock | None = None+) -> int:+ """Assign organizationId on a single table's unassigned rows."""+ updated = await prisma.execute_raw(table_sql)+ if renew_lock is not None:+ await renew_lock()+ return updated+++async def _assign_team_tenancy_batched(+ table_name: str,+ batch_sql: "LiteralString",+ renew_lock: _RenewLock | None = None,+) -> int:+ """Run a LIMIT-batched tenancy UPDATE until no assignable rows remain.++ Large tables (executions, chat sessions) cannot be updated in one+ statement: a full-table UPDATE exceeds the platform's statement timeout+ (Supabase kills it at 2 minutes — this is what failed the dev deploy).+ ``batch_sql`` must limit itself via a subquery that only selects rows+ its own JOIN will match, so every selected row updates and the loop is+ guaranteed to terminate — rows whose user has no personal org are never+ selected and can't spin it. Each pass is idempotent+ (``organizationId IS NULL`` filter), so an interrupted run resumes+ cleanly on the next startup.+ """+ total = 0+ while True:+ updated = await prisma.execute_raw(batch_sql)+ if renew_lock is not None:+ await renew_lock()+ if updated == 0:+ return total+ total += updated+ logger.info(+ f"Org migration: assigned {total} {table_name} rows so far (batched)"+ )-async def assign_resources_to_teams() -> dict[str, int]:+async def assign_resources_to_teams(+ renew_lock: _RenewLock | None = None,+) -> dict[str, int]:"""Set organizationId and teamId on all tenant-bound rows that lack them.Uses the user's personal org and its default workspace.@@ -455,29 +523,58 @@ async def assign_resources_to_teams() -> dict[str, int]:JOIN "Organization" o ON o."id" = om."orgId" AND o."isPersonal" = trueJOIN "Team" w ON w."orgId" = o."id" AND w."isDefault" = trueWHERE t."userId" = om."userId" AND om."isOwner" = true AND t."organizationId" IS NULL- """+ """,+ renew_lock=renew_lock,)- results["AgentGraphExecution"] = await _assign_team_tenancy(+ results["AgentGraphExecution"] = await _assign_team_tenancy_batched(+ "AgentGraphExecution","""UPDATE "AgentGraphExecution" tSET "organizationId" = o."id", "teamId" = w."id"FROM "OrgMember" omJOIN "Organization" o ON o."id" = om."orgId" AND o."isPersonal" = trueJOIN "Team" w ON w."orgId" = o."id" AND w."isDefault" = true- WHERE t."userId" = om."userId" AND om."isOwner" = true AND t."organizationId" IS NULL- """+ WHERE t."userId" = om."userId" AND om."isOwner" = true+ AND t."id" IN (+ SELECT t2."id"+ FROM "AgentGraphExecution" t2+ JOIN "OrgMember" om2+ ON om2."userId" = t2."userId" AND om2."isOwner" = true+ JOIN "Organization" o2+ ON o2."id" = om2."orgId" AND o2."isPersonal" = true+ JOIN "Team" w2+ ON w2."orgId" = o2."id" AND w2."isDefault" = true+ WHERE t2."organizationId" IS NULL+ LIMIT 10000+ )+ """,+ renew_lock=renew_lock,)- results["ChatSession"] = await _assign_team_tenancy(+ results["ChatSession"] = await _assign_team_tenancy_batched(+ "ChatSession","""UPDATE "ChatSession" tSET "organizationId" = o."id", "teamId" = w."id"FROM "OrgMember" omJOIN "Organization" o ON o."id" = om."orgId" AND o."isPersonal" = trueJOIN "Team" w ON w."orgId" = o."id" AND w."isDefault" = true- WHERE t."userId" = om."userId" AND om."isOwner" = true AND t."organizationId" IS NULL- """+ WHERE t."userId" = om."userId" AND om."isOwner" = true+ AND t."id" IN (+ SELECT t2."id"+ FROM "ChatSession" t2+ JOIN "OrgMember" om2+ ON om2."userId" = t2."userId" AND om2."isOwner" = true+ JOIN "Organization" o2+ ON o2."id" = om2."orgId" AND o2."isPersonal" = true+ JOIN "Team" w2+ ON w2."orgId" = o2."id" AND w2."isDefault" = true+ WHERE t2."organizationId" IS NULL+ LIMIT 10000+ )+ """,+ renew_lock=renew_lock,)results["AgentPreset"] = await _assign_team_tenancy(@@ -488,7 +585,8 @@ async def assign_resources_to_teams() -> dict[str, int]:JOIN "Organization" o ON o."id" = om."orgId" AND o."isPersonal" = trueJOIN "Team" w ON w."orgId" = o."id" AND w."isDefault" = trueWHERE t."userId" = om."userId" AND om."isOwner" = true AND t."organizationId" IS NULL- """+ """,+ renew_lock=renew_lock,)results["LibraryAgent"] = await _assign_team_tenancy(@@ -499,7 +597,8 @@ async def assign_resources_to_teams() -> dict[str, int]:JOIN "Organization" o ON o."id" = om."orgId" AND o."isPersonal" = trueJOIN "Team" w ON w."orgId" = o."id" AND w."isDefault" = trueWHERE t."userId" = om."userId" AND om."isOwner" = true AND t."organizationId" IS NULL- """+ """,+ renew_lock=renew_lock,)results["LibraryFolder"] = await _assign_team_tenancy(@@ -510,7 +609,8 @@ async def assign_resources_to_teams() -> dict[str, int]:JOIN "Organization" o ON o."id" = om."orgId" AND o."isPersonal" = trueJOIN "Team" w ON w."orgId" = o."id" AND w."isDefault" = trueWHERE t."userId" = om."userId" AND om."isOwner" = true AND t."organizationId" IS NULL- """+ """,+ renew_lock=renew_lock,)results["IntegrationWebhook"] = await _assign_team_tenancy(@@ -521,7 +621,8 @@ async def assign_resources_to_teams() -> dict[str, int]:JOIN "Organization" o ON o."id" = om."orgId" AND o."isPersonal" = trueJOIN "Team" w ON w."orgId" = o."id" AND w."isDefault" = trueWHERE t."userId" = om."userId" AND om."isOwner" = true AND t."organizationId" IS NULL- """+ """,+ renew_lock=renew_lock,)results["APIKey"] = await _assign_team_tenancy(@@ -532,7 +633,8 @@ async def assign_resources_to_teams() -> dict[str, int]:JOIN "Organization" o ON o."id" = om."orgId" AND o."isPersonal" = trueJOIN "Team" w ON w."orgId" = o."id" AND w."isDefault" = trueWHERE t."userId" = om."userId" AND om."isOwner" = true AND t."organizationId" IS NULL- """+ """,+ renew_lock=renew_lock,)results["UserNotificationBatch"] = await _assign_team_tenancy(@@ -543,32 +645,35 @@ async def assign_resources_to_teams() -> dict[str, int]:JOIN "Organization" o ON o."id" = om."orgId" AND o."isPersonal" = trueJOIN "Team" w ON w."orgId" = o."id" AND w."isDefault" = trueWHERE t."userId" = om."userId" AND om."isOwner" = true AND t."organizationId" IS NULL- """+ """,+ renew_lock=renew_lock,)# --- Tables needing only organizationId ---- results["BuilderSearchHistory"] = await prisma.execute_raw(+ results["BuilderSearchHistory"] = await _assign_org_tenancy("""UPDATE "BuilderSearchHistory" tSET "organizationId" = o."id"FROM "OrgMember" omJOIN "Organization" o ON o."id" = om."orgId" AND o."isPersonal" = trueWHERE t."userId" = om."userId" AND om."isOwner" = true AND t."organizationId" IS NULL- """+ """,+ renew_lock=renew_lock,)- results["PendingHumanReview"] = await prisma.execute_raw(+ results["PendingHumanReview"] = await _assign_org_tenancy("""UPDATE "PendingHumanReview" tSET "organizationId" = o."id"FROM "OrgMember" omJOIN "Organization" o ON o."id" = om."orgId" AND o."isPersonal" = trueWHERE t."userId" = om."userId" AND om."isOwner" = true AND t."organizationId" IS NULL- """+ """,+ renew_lock=renew_lock,)- results["StoreListingVersion"] = await prisma.execute_raw(+ results["StoreListingVersion"] = await _assign_org_tenancy("""UPDATE "StoreListingVersion" slvSET "organizationId" = o."id"@@ -577,7 +682,8 @@ async def assign_resources_to_teams() -> dict[str, int]:JOIN "OrgMember" om ON om."userId" = sl."owningUserId" AND om."isOwner" = trueJOIN "Organization" o ON o."id" = om."orgId" AND o."isPersonal" = trueWHERE slv."id" = v."id" AND slv."organizationId" IS NULL- """+ """,+ renew_lock=renew_lock,)for table_name, count in results.items():@@ -736,6 +842,39 @@ async def migrate_credentials_to_table() -> int:return created+async def _renew_migration_lock(+ redis: "AsyncRedisClient",+ lock_key: str,+ lock_token: str,+ lock_timeout: int,+) -> None:+ renewed = await redis.execute_command(+ "EVAL",+ _MIGRATION_LOCK_RENEW_SCRIPT,+ 1,+ lock_key,+ lock_token,+ str(lock_timeout),+ )+ if renewed != 1:+ raise RuntimeError("Org migration lost the distributed bootstrap lock")+++async def _release_migration_lock(+ redis: "AsyncRedisClient",+ lock_key: str,+ lock_token: str,+) -> bool:+ released = await redis.execute_command(+ "EVAL",+ _MIGRATION_LOCK_RELEASE_SCRIPT,+ 1,+ lock_key,+ lock_token,+ )+ return released == 1++async def run_migration() -> None:"""Orchestrate the full org bootstrap migration. Idempotent.@@ -746,25 +885,36 @@ async def run_migration() -> None:redis = await get_redis_async()lock_key = "org-migration-bootstrap-lock"+ lock_token = str(uuid4())lock_timeout = 300 # 5 min max# SET NX EX — acquire only if no other pod holds it- acquired = await redis.set(lock_key, "1", nx=True, ex=lock_timeout)+ acquired = await redis.set(lock_key, lock_token, nx=True, ex=lock_timeout)if not acquired:logger.info("Org migration: another pod holds the lock, skipping")return+ async def renew_lock() -> None:+ await _renew_migration_lock(redis, lock_key, lock_token, lock_timeout)+try:start = time.monotonic()logger.info("Org migration: starting personal org bootstrap")orgs_created = await create_orgs_for_existing_users()+ await renew_lock()await migrate_org_balances()+ await renew_lock()await migrate_credit_transactions()- resource_counts = await assign_resources_to_teams()+ await renew_lock()+ resource_counts = await assign_resources_to_teams(renew_lock=renew_lock)+ await renew_lock()await migrate_store_listings()+ await renew_lock()await create_store_listing_aliases()+ await renew_lock()await migrate_credentials_to_table()+ await renew_lock()total_resources = sum(resource_counts.values())elapsed = time.monotonic() - start@@ -775,6 +925,6 @@ async def run_migration() -> None:)finally:try:- await redis.delete(lock_key)+ await _release_migration_lock(redis, lock_key, lock_token)except Exception:passdiff --git a/autogpt_platform/backend/backend/data/org_migration_test.py b/autogpt_platform/backend/backend/data/org_migration_test.pyindex b7a2d821c8..c2eb6db543 100644--- a/autogpt_platform/backend/backend/data/org_migration_test.py+++ b/autogpt_platform/backend/backend/data/org_migration_test.py@@ -10,6 +10,8 @@ from unittest.mock import AsyncMock, MagicMockimport pytestfrom backend.data.org_migration import (+ _release_migration_lock,+ _renew_migration_lock,_resolve_unique_slug,_sanitize_slug,assign_resources_to_teams,@@ -709,6 +711,11 @@ class TestAssignResources:new_callable=AsyncMock,return_value=10,)+ mocker.patch(+ "backend.data.org_migration._assign_team_tenancy_batched",+ new_callable=AsyncMock,+ return_value=10,+ )mock_prisma.execute_raw = AsyncMock(return_value=10)result = await assign_resources_to_teams()@@ -729,10 +736,122 @@ class TestAssignResources:new_callable=AsyncMock,return_value=0,)+ mocker.patch(+ "backend.data.org_migration._assign_team_tenancy_batched",+ new_callable=AsyncMock,+ return_value=0,+ )mock_prisma.execute_raw = AsyncMock(return_value=0)result = await assign_resources_to_teams()assert all(v == 0 for v in result.values())+ @pytest.mark.asyncio+ async def test_big_tables_use_batched_updates(self, mock_prisma, mocker):+ """AgentGraphExecution and ChatSession must go through the batched+ path — a single full-table UPDATE exceeds the platform statement+ timeout on production-sized data (this took down the dev deploy)."""+ single = mocker.patch(+ "backend.data.org_migration._assign_team_tenancy",+ new_callable=AsyncMock,+ return_value=0,+ )+ batched = mocker.patch(+ "backend.data.org_migration._assign_team_tenancy_batched",+ new_callable=AsyncMock,+ return_value=0,+ )+ mock_prisma.execute_raw = AsyncMock(return_value=0)++ await assign_resources_to_teams()++ batched_tables = {call.args[0] for call in batched.await_args_list}+ assert batched_tables == {"AgentGraphExecution", "ChatSession"}+ single_sql = " ".join(call.args[0] for call in single.await_args_list)+ assert '"AgentGraphExecution"' not in single_sql+ assert 'UPDATE "ChatSession"' not in single_sql++ @pytest.mark.asyncio+ async def test_renews_after_each_assignment_statement(self, mock_prisma):+ mock_prisma.execute_raw = AsyncMock(return_value=0)+ renew_lock = AsyncMock()++ result = await assign_resources_to_teams(renew_lock=renew_lock)++ assert len(result) == 12+ assert mock_prisma.execute_raw.await_count == 12+ assert renew_lock.await_count == 12+++class TestBatchedTenancy:+ @pytest.mark.asyncio+ async def test_loops_until_no_rows_remain(self, mock_prisma):+ from backend.data.org_migration import _assign_team_tenancy_batched++ mock_prisma.execute_raw = AsyncMock(side_effect=[3, 2, 0])++ total = await _assign_team_tenancy_batched(+ "SomeTable", 'UPDATE "SomeTable" SET x = 1'+ )++ assert total == 5+ assert mock_prisma.execute_raw.await_count == 3++ @pytest.mark.asyncio+ async def test_renews_lock_after_each_batch_statement(self, mock_prisma):+ from backend.data.org_migration import _assign_team_tenancy_batched++ mock_prisma.execute_raw = AsyncMock(side_effect=[3, 2, 0])+ renew_lock = AsyncMock()++ total = await _assign_team_tenancy_batched(+ "SomeTable", 'UPDATE "SomeTable" SET x = 1', renew_lock=renew_lock+ )++ assert total == 5+ assert renew_lock.await_count == 3++ @pytest.mark.asyncio+ async def test_empty_table_returns_zero_after_one_probe(self, mock_prisma):+ from backend.data.org_migration import _assign_team_tenancy_batched++ mock_prisma.execute_raw = AsyncMock(return_value=0)++ total = await _assign_team_tenancy_batched(+ "SomeTable", 'UPDATE "SomeTable" SET x = 1'+ )++ assert total == 0+ assert mock_prisma.execute_raw.await_count == 1+++class TestMigrationLock:+ @pytest.mark.asyncio+ async def test_renew_extends_owned_lock(self):+ redis = AsyncMock()+ redis.execute_command = AsyncMock(return_value=1)++ await _renew_migration_lock(redis, "lock-key", "token", 300)++ redis.execute_command.assert_awaited_once()++ @pytest.mark.asyncio+ async def test_renew_fails_loud_when_lock_is_lost(self):+ redis = AsyncMock()+ redis.execute_command = AsyncMock(return_value=0)++ with pytest.raises(RuntimeError, match="lost the distributed bootstrap lock"):+ await _renew_migration_lock(redis, "lock-key", "token", 300)++ @pytest.mark.asyncio+ async def test_release_uses_token_safe_script(self):+ redis = AsyncMock()+ redis.execute_command = AsyncMock(return_value=0)++ released = await _release_migration_lock(redis, "lock-key", "token")++ assert released is False+ redis.delete.assert_not_called()+# ---------------------------------------------------------------------------# migrate_store_listings@@ -756,6 +875,16 @@ class TestRunMigration:@pytest.mark.asyncioasync def test_calls_all_steps_in_order(self, mocker):calls: list[str] = []+ redis = AsyncMock()+ redis.set = AsyncMock(return_value=True)+ redis.execute_command = AsyncMock(return_value=1)++ mocker.patch(+ "backend.data.redis_client.get_redis_async",+ new_callable=AsyncMock,+ return_value=redis,+ )+ mocker.patch("backend.data.org_migration.uuid4", return_value="lock-token")mocker.patch("backend.data.org_migration.create_orgs_for_existing_users",@@ -769,11 +898,15 @@ class TestRunMigration:"backend.data.org_migration.migrate_credit_transactions",new_callable=lambda: lambda: _track(calls, "credits", 0),)++ async def assign_resources(renew_lock=None):+ if renew_lock is not None:+ await renew_lock()+ return await _track(calls, "assign_resources", {"AgentGraph": 5})+mocker.patch("backend.data.org_migration.assign_resources_to_teams",- new_callable=lambda: lambda: _track(- calls, "assign_resources", {"AgentGraph": 5}- ),+ new=assign_resources,)mocker.patch("backend.data.org_migration.migrate_store_listings",@@ -790,6 +923,10 @@ class TestRunMigration:await run_migration()+ redis.set.assert_awaited_once_with(+ "org-migration-bootstrap-lock", "lock-token", nx=True, ex=300+ )+ assert redis.execute_command.await_count == 9assert calls == ["create_orgs","balances",diff --git a/autogpt_platform/backend/migrations/20260415000000_org_tenancy_cutover/migration.sql b/autogpt_platform/backend/migrations/20260415000000_org_tenancy_cutover/migration.sqlindex d4bc78b220..021ae3553f 100644--- a/autogpt_platform/backend/migrations/20260415000000_org_tenancy_cutover/migration.sql+++ b/autogpt_platform/backend/migrations/20260415000000_org_tenancy_cutover/migration.sql@@ -1,66 +1,25 @@-- Org tenancy cutover migration--- 1. Backfill NULL organizationId on AgentGraph, AgentGraphExecution, StoreListing--- 2. Make organizationId NOT NULL on those tables--- 3. Update unique constraint on StoreListing from (owningUserId, slug) to (owningOrgId, slug)+-- 1. (REMOVED) Backfill of NULL organizationId — owned by the app-startup+-- backfill (backend/data/org_migration.py), NOT this migration+-- 2. Make organizationId NOT NULL on those tables (deferred)+-- 3. Update unique constraint on StoreListing from (owningUserId, slug) to (owningOrgId, slug) (deferred)-- 4. Update views: StoreAgent (add owning_org_id), StoreSubmission (add organization_id),-- Creator → StoreCreator (add org_name)-- Prisma wraps each migration file in its own transaction.-- ==========================================================================--- Step 1: Backfill NULL organizationId values+-- Step 1: (REMOVED) Backfill NULL organizationId values-- ==========================================================================---- AgentGraph: set organizationId from the user's personal org-UPDATE "AgentGraph" ag-SET "organizationId" = (- SELECT o.id- FROM "Organization" o- JOIN "OrgMember" om ON om."orgId" = o.id- WHERE om."userId" = ag."userId"- AND o."isPersonal" = true- LIMIT 1-)-WHERE ag."organizationId" IS NULL;---- AgentGraphExecution: same strategy-UPDATE "AgentGraphExecution" ex-SET "organizationId" = (- SELECT o.id- FROM "Organization" o- JOIN "OrgMember" om ON om."orgId" = o.id- WHERE om."userId" = ex."userId"- AND o."isPersonal" = true- LIMIT 1-)-WHERE ex."organizationId" IS NULL;---- StoreListing: backfill owningOrgId from user's personal org-UPDATE "StoreListing" sl-SET "owningOrgId" = (- SELECT o.id- FROM "Organization" o- JOIN "OrgMember" om ON om."orgId" = o.id- WHERE om."userId" = sl."owningUserId"- AND o."isPersonal" = true- LIMIT 1-)-WHERE sl."owningOrgId" IS NULL;---- Safety: warn if any rows still have NULL (backfill missed them).--- Uses WARNING instead of EXCEPTION so fresh CI databases (no data to backfill) don't abort.-DO $$-BEGIN- IF EXISTS (SELECT 1 FROM "AgentGraph" WHERE "organizationId" IS NULL) THEN- RAISE WARNING 'AgentGraph has rows with NULL organizationId after backfill';- END IF;- IF EXISTS (SELECT 1 FROM "AgentGraphExecution" WHERE "organizationId" IS NULL) THEN- RAISE WARNING 'AgentGraphExecution has rows with NULL organizationId after backfill';- END IF;- IF EXISTS (SELECT 1 FROM "StoreListing" WHERE "owningOrgId" IS NULL) THEN- RAISE WARNING 'StoreListing has rows with NULL owningOrgId after backfill';- END IF;-END $$;+-- The backfill CANNOT do useful work at migration time: personal orgs are+-- created by the app-startup backfill (org_migration.py), which runs AFTER+-- migrations — so Organization/OrgMember are always empty here and the+-- per-row subquery resolved to NULL for every row. On the dev database that+-- meant a full-table rewrite of AgentGraphExecution setting NULL back to+-- NULL, which blew the platform's 2-minute statement timeout and failed the+-- whole deploy (SQLSTATE 57014). The startup backfill performs the real+-- assignment in bounded batches once orgs exist; reads stay null-tolerant+-- until then.-- ==========================================================================-- Step 2: (DEFERRED) Make organizationId NOT NULL