fix(module-builder): fix pool exhaustion deadlock and allow therapeutic modules

This commit is contained in:
Urvish Prajapati 2026-11-23 13:18:02 +05:30
parent 4c52d6278f
commit a195d4b39c
3 changed files with 70 additions and 64 deletions

View File

@ -10,13 +10,15 @@ from collections.abc import AsyncIterator
from app.core.config import settings from app.core.config import settings
engine = create_async_engine(settings.database_url, pool_pre_ping=True, future=True) engine = create_async_engine(
# AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession) settings.database_url,
pool_size=settings.database_pool_size,
# async def get_db_session() -> AsyncGenerator[AsyncSession, None]: max_overflow=settings.database_max_overflow,
# async with AsyncSessionLocal() as session: pool_timeout=settings.database_pool_timeout_seconds,
# yield session pool_pre_ping=True,
pool_recycle=1800,
future=True,
)
SessionFactory = async_sessionmaker( SessionFactory = async_sessionmaker(
bind=engine, bind=engine,
@ -27,4 +29,10 @@ SessionFactory = async_sessionmaker(
async def get_db_session() -> AsyncIterator[AsyncSession]: async def get_db_session() -> AsyncIterator[AsyncSession]:
async with SessionFactory() as session: async with SessionFactory() as session:
yield session try:
yield session
except Exception:
await session.rollback()
raise
finally:
await session.close()

View File

@ -50,8 +50,7 @@ class ModuleBuilderService:
if legacy_mod: if legacy_mod:
legacy_meta = legacy_mod.metadata_json or {} legacy_meta = legacy_mod.metadata_json or {}
legacy_kind = legacy_meta.get("kind") or "legacy" legacy_kind = legacy_meta.get("kind") or "legacy"
legacy_managed = legacy_meta.get("managed_by") if legacy_kind != "therapeutic":
if legacy_kind != "therapeutic" or legacy_managed != "module_builder":
raise HTTPException( raise HTTPException(
status_code=403, status_code=403,
detail=( detail=(
@ -345,8 +344,7 @@ class ModuleBuilderService:
if legacy_mod: if legacy_mod:
legacy_meta = legacy_mod.metadata_json or {} legacy_meta = legacy_mod.metadata_json or {}
legacy_kind = legacy_meta.get("kind") or "legacy" legacy_kind = legacy_meta.get("kind") or "legacy"
legacy_managed = legacy_meta.get("managed_by") if legacy_kind != "therapeutic":
if legacy_kind != "therapeutic" or legacy_managed != "module_builder":
raise HTTPException( raise HTTPException(
status_code=403, status_code=403,
detail=( detail=(
@ -469,7 +467,6 @@ class ModuleBuilderService:
) )
res = await self.session.execute(stmt) res = await self.session.execute(stmt)
cat = res.scalar_one() cat = res.scalar_one()
await self.session.commit()
# Count diseases # Count diseases
count_stmt = select(func.count(BuilderDisease.id)).where( count_stmt = select(func.count(BuilderDisease.id)).where(
@ -478,6 +475,7 @@ class ModuleBuilderService:
) )
count_res = await self.session.execute(count_stmt) count_res = await self.session.execute(count_stmt)
count = count_res.scalar_one() or 0 count = count_res.scalar_one() or 0
await self.session.commit()
return BuilderCategorySummary( return BuilderCategorySummary(
id=cat.id, id=cat.id,
@ -491,28 +489,7 @@ class ModuleBuilderService:
async def delete_category(self, module_code: str, category_code: str) -> bool: async def delete_category(self, module_code: str, category_code: str) -> bool:
clean_code = module_code.strip().lower() clean_code = module_code.strip().lower()
await self._verify_module_editable(clean_code)
# 1. Block if legacy module
legacy_stmt = select(Module).where(Module.code == clean_code)
legacy_res = await self.session.execute(legacy_stmt)
legacy_mod = legacy_res.scalar_one_or_none()
if legacy_mod:
legacy_meta = legacy_mod.metadata_json or {}
legacy_kind = legacy_meta.get("kind") or "legacy"
legacy_managed = legacy_meta.get("managed_by")
if legacy_kind != "therapeutic" or legacy_managed != "module_builder":
raise HTTPException(
status_code=403,
detail=(
f"Module '{clean_code}' is a legacy '{legacy_kind}' module "
"and cannot be modified via Module Builder."
),
)
stmt = select(BuilderModule).where(BuilderModule.code == clean_code)
mod = (await self.session.execute(stmt)).scalar_one_or_none()
if not mod:
return False
del_stmt = delete(BuilderCategory).where( del_stmt = delete(BuilderCategory).where(
BuilderCategory.module_code == clean_code, BuilderCategory.module_code == clean_code,
@ -671,7 +648,6 @@ class ModuleBuilderService:
) )
res = await self.session.execute(stmt) res = await self.session.execute(stmt)
dis = res.scalar_one() dis = res.scalar_one()
await self.session.commit()
count_stmt = select(func.count(BuilderPattern.id)).where( count_stmt = select(func.count(BuilderPattern.id)).where(
BuilderPattern.module_code == module_code, BuilderPattern.module_code == module_code,
@ -701,9 +677,10 @@ class ModuleBuilderService:
updated_at=now, updated_at=now,
) )
await self.session.execute(init_pat) await self.session.execute(init_pat)
await self.session.commit()
count = 1 count = 1
await self.session.commit()
return BuilderDiseaseSummary( return BuilderDiseaseSummary(
id=dis.id, id=dis.id,
module_code=dis.module_code, module_code=dis.module_code,
@ -719,28 +696,7 @@ class ModuleBuilderService:
self, module_code: str, category_code: str, disease_code: str self, module_code: str, category_code: str, disease_code: str
) -> bool: ) -> bool:
clean_code = module_code.strip().lower() clean_code = module_code.strip().lower()
await self._verify_module_editable(clean_code)
# 1. Block if legacy module
legacy_stmt = select(Module).where(Module.code == clean_code)
legacy_res = await self.session.execute(legacy_stmt)
legacy_mod = legacy_res.scalar_one_or_none()
if legacy_mod:
legacy_meta = legacy_mod.metadata_json or {}
legacy_kind = legacy_meta.get("kind") or "legacy"
legacy_managed = legacy_meta.get("managed_by")
if legacy_kind != "therapeutic" or legacy_managed != "module_builder":
raise HTTPException(
status_code=403,
detail=(
f"Module '{clean_code}' is a legacy '{legacy_kind}' module "
"and cannot be modified via Module Builder."
),
)
stmt = select(BuilderModule).where(BuilderModule.code == clean_code)
mod = (await self.session.execute(stmt)).scalar_one_or_none()
if not mod:
return False
stmt = delete(BuilderDisease).where( stmt = delete(BuilderDisease).where(
BuilderDisease.module_code == clean_code, BuilderDisease.module_code == clean_code,

View File

@ -39,11 +39,18 @@ With the clean Acupedia naming conventions:
- **Database**: `acupedia_db` - **Database**: `acupedia_db`
- **User**: `db_admin` / Password: `C1234spl` - **User**: `db_admin` / Password: `C1234spl`
- **Volumes**: `acupedia-postgres-data`, `acupedia-minio-data` - **Volumes**: `acupedia-postgres-data`, `acupedia-minio-data`
- **MinIO Bucket**: `accupedia-media` - **MinIO Bucket**: `acupedia-media`
### Step 2.1: Generate Container Git Info Metadata (Recommended)
Before building, run the script to capture the branch and commit of `api`, `store`, and `admin`:
### Start the containers:
```bash ```bash
cd ~/acupedia/acupedia_ops cd ~/acupedia/acupedia_ops
./scripts/generate-git-info.sh
```
### Step 2.2: Start the Containers
```bash
docker compose -f docker-compose.dev.yml up -d --build docker compose -f docker-compose.dev.yml up -d --build
``` ```
@ -63,7 +70,20 @@ docker compose -f docker-compose.dev.yml exec backend \
--- ---
### Step 3.2: Seed Authentication & Super Admin User ### Step 3.2: Run Alembic Migrations (Module Builder & Dynamic Content)
Stamps the baseline DDL (schema v5 includes migrations up to `0003`) and applies new migrations (such as Module Builder tables `content.builder_modules`, `content.builder_categories`, etc.):
```bash
docker compose -f docker-compose.dev.yml exec backend \
alembic stamp 0003_monthly_invoice_seq
docker compose -f docker-compose.dev.yml exec backend \
alembic upgrade head
```
---
### Step 3.3: Seed Authentication & Super Admin User
Seeds default roles (`super_admin`, `admin`, `finance_admin`, `practitioner`), permissions, and creates the super admin account: Seeds default roles (`super_admin`, `admin`, `finance_admin`, `practitioner`), permissions, and creates the super admin account:
```bash ```bash
@ -75,7 +95,7 @@ docker compose -f docker-compose.dev.yml exec -e ACCUPEDIA_BOOTSTRAP_ADMIN_PASSW
--- ---
### Step 3.3: Seed Content & Modules ### Step 3.4: Seed Content & Modules
Reads the mounted `/app/content` folder, parses templates, and seeds and publishes all 16 clinical modules (`m0001` through `m0042`): Reads the mounted `/app/content` folder, parses templates, and seeds and publishes all 16 clinical modules (`m0001` through `m0042`):
```bash ```bash
@ -89,7 +109,7 @@ docker compose -f docker-compose.dev.yml exec backend \
--- ---
### Step 3.4: Seed Clinical Media Assets (Images to MinIO) ### Step 3.4: Seed Clinical Media Assets (Images to MinIO)
Seeds all 787 anatomical images, channel pathways, and charts across the 4 visual modules into MinIO object storage (`accupedia-media` bucket) and links them to their respective content items in PostgreSQL: Seeds all 787 anatomical images, channel pathways, and charts across the 4 visual modules into MinIO object storage (`acupedia-media` bucket) and links them to their respective content items in PostgreSQL:
**Option A (Recommended — Automated 1-line loop for all 4 modules):** **Option A (Recommended — Automated 1-line loop for all 4 modules):**
```bash ```bash
@ -186,3 +206,25 @@ After running the manual steps above, test your endpoints:
| **Admin Portal** | `3001` | `http://<IP_OR_DOMAIN>:3001/admin/` | | **Admin Portal** | `3001` | `http://<IP_OR_DOMAIN>:3001/admin/` |
| **MinIO Console** | `9001` | `http://<IP_OR_DOMAIN>:9001` (`minioadmin` / `minioadmin`) | | **MinIO Console** | `9001` | `http://<IP_OR_DOMAIN>:9001` (`minioadmin` / `minioadmin`) |
| **MailHog UI** | `8025` | `http://<IP_OR_DOMAIN>:8025` | | **MailHog UI** | `8025` | `http://<IP_OR_DOMAIN>:8025` |
### Git Identity Verification (Inspect Container Branch & Commit)
To verify which branch and commit are running inside each container:
```bash
# 1. API Backend
docker compose -f docker-compose.dev.yml exec backend cat /app/.git_api_info
# 2. Storefront
docker compose -f docker-compose.dev.yml exec store cat /app/.git_store_info
# 3. Admin Portal
docker compose -f docker-compose.dev.yml exec admin cat /app/.git_admin_info
```
Example output:
```text
Branch: main
Commit: 29279bfd72a6fa296d1aa05a825bd88ca1f36c91
```