Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## 2024-07-18 - Prevent O(N) memory loading for sequence calculation
**Learning:** Found an anti-pattern where calculating the next sequence number for a job event loaded up to 1000 events into memory via `list_for_job(...)[-1]` just to inspect the final sequence number, causing unnecessary memory consumption and query overhead.
**Action:** Replaced array indexing on list results with direct O(1) SQL aggregation (`func.max(sequence_no)`) via a new `get_max_sequence_no` repository method. Always use database aggregation instead of loading entities into application memory just to compute aggregates.
4 changes: 2 additions & 2 deletions apps/api/src/cortex_api/services/jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,8 @@ async def cancel_job(uow: CortexUnitOfWork, job_id: str) -> JobStatusDetail:
if updated is None: # pragma: no cover - defensive
raise NotFoundError(f"Job `{job_id}` was not found.")

existing_events = await uow.job_events.list_for_job(job_id, limit=1000)
next_sequence = existing_events[-1].sequence_no + 1 if existing_events else 1
max_seq = await uow.job_events.get_max_sequence_no(job_id)
next_sequence = max_seq + 1
await uow.job_events.add(
JobEventRecord(
job_id=job_id,
Expand Down
11 changes: 10 additions & 1 deletion packages/db/src/cortex_db/repositories.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
SynthesisType,
TenantRecord,
)
from sqlalchemy import desc, or_, select, update
from sqlalchemy import desc, func, or_, select, update
from sqlalchemy.ext.asyncio import AsyncSession

from .models import (
Expand Down Expand Up @@ -1637,6 +1637,15 @@ async def add(self, record: JobEventRecord) -> JobEventRecord:
await self._session.refresh(model)
return _job_event_from_model(model)

async def get_max_sequence_no(self, job_id: str) -> int:
"""Efficiently gets the maximum sequence number for a job's events."""
result = await self._session.execute(
select(func.coalesce(func.max(JobEventModel.sequence_no), 0)).where(
JobEventModel.job_id == job_id
)
)
return result.scalar_one()

async def list_for_job(
self,
job_id: str,
Expand Down
4 changes: 2 additions & 2 deletions packages/evaluation/src/cortex_evaluation/jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -561,8 +561,8 @@ async def _append_event(
message: str,
details: dict[str, Any] | None = None,
) -> None:
existing_events = await uow.job_events.list_for_job(job.job_id, limit=1000)
next_sequence = existing_events[-1].sequence_no + 1 if existing_events else 1
max_seq = await uow.job_events.get_max_sequence_no(job.job_id)
next_sequence = max_seq + 1
await uow.job_events.add(
JobEventRecord(
job_id=job.job_id,
Expand Down
4 changes: 2 additions & 2 deletions packages/knowledge/src/cortex_knowledge/jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -480,8 +480,8 @@ async def _append_event(
message: str,
details: dict[str, Any] | None = None,
) -> None:
existing_events = await uow.job_events.list_for_job(job.job_id, limit=1000)
next_sequence = existing_events[-1].sequence_no + 1 if existing_events else 1
max_seq = await uow.job_events.get_max_sequence_no(job.job_id)
next_sequence = max_seq + 1
await uow.job_events.add(
JobEventRecord(
job_id=job.job_id,
Expand Down
4 changes: 2 additions & 2 deletions packages/parse/src/cortex_parse/jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -412,8 +412,8 @@ async def _append_event(
message: str,
details: dict[str, Any] | None = None,
) -> None:
existing_events = await uow.job_events.list_for_job(job.job_id, limit=1000)
next_sequence = existing_events[-1].sequence_no + 1 if existing_events else 1
max_seq = await uow.job_events.get_max_sequence_no(job.job_id)
next_sequence = max_seq + 1
await uow.job_events.add(
JobEventRecord(
job_id=job.job_id,
Expand Down
4 changes: 2 additions & 2 deletions packages/synthesis/src/cortex_synthesis/jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,8 +401,8 @@ async def _append_event(
message: str,
details: dict[str, Any] | None = None,
) -> None:
existing_events = await uow.job_events.list_for_job(job.job_id, limit=1000)
next_sequence = existing_events[-1].sequence_no + 1 if existing_events else 1
max_seq = await uow.job_events.get_max_sequence_no(job.job_id)
next_sequence = max_seq + 1
await uow.job_events.add(
JobEventRecord(
job_id=job.job_id,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

from cortex_evaluation import (
EvaluationStorageCaller as WorkerStorageCaller,
)
from cortex_evaluation import (
persist_evaluation_report,
)

Expand Down
Loading