Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat(4.3): a cold lake query reports a cost estimate and a progress state

Beenu Arora4bfece451f64
diff --git a/services/api/app/api/v1/endpoints/lake.py b/services/api/app/api/v1/endpoints/lake.py
index d7e25855d..885a83f78 100644
--- a/services/api/app/api/v1/endpoints/lake.py
+++ b/services/api/app/api/v1/endpoints/lake.py
@@ -36,8 +36,9 @@ import uuid
from datetime import datetime
from typing import Annotated, Any
-from fastapi import APIRouter, Depends, HTTPException, Request, Response, status
+from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Request, Response, status
from pydantic import BaseModel, Field
+from sqlalchemy import select
from app.api.v1.deps import AuthUser, DBSession, require_permission
from app.core.logging import safe_log_value
@@ -48,7 +49,10 @@ from app.db.clickhouse import (
execute_lake_query,
fetch_lake_schema,
)
+from app.models.lake_query_job import LakeQueryJob
from app.services.audit import emit_audit
+from app.services.lake_cold_query import ColdEstimateUnavailable, ScanEstimate, estimate_scan
+from app.services.lake_query_runner import cancel_job, claim_job, new_query_id, read_progress, run_job
from app.services.lake_rate_limit import get_lake_rate_limiter
from app.services.lake_sql import (
ALLOWED_TABLES,
@@ -121,6 +125,16 @@ class LakeQueryRequest(BaseModel):
le=60.0,
description=("Optional wall-clock cap. Defaults to the server cap (30s). Useful for agent loops that need to fail fast."),
)
+ force_sync: bool = Field(
+ default=False,
+ description=(
+ "Run synchronously even when the estimate says the query must read the cold "
+ "volume. Off by default: the synchronous path is bounded by the 30-second default "
+ "and 60-second maximum above, and a cold read that does not fit inside them used "
+ "to come back as a bare timeout with no indication of how much data was involved. "
+ "Set this only when you already know the scan is small."
+ ),
+ )
class LakeQueryResponse(BaseModel):
@@ -305,6 +319,44 @@ async def execute_lake_sql(
detail=f"lake SQL invalid: {exc}",
) from exc
+ # ---- Step 1b: is this a cold scan? ----------------------------------
+ #
+ # Depth 4.3. Before this, a query over the cold volume either returned
+ # inside the published 30-second default or raised a bare timeout,
+ # which tells an analyst nothing about whether a longer deadline would
+ # have helped or how much data was involved.
+ #
+ # The routing rule deliberately does not predict a duration. Doing so
+ # would need a bytes-per-second figure, and the only honest source for
+ # one is a measurement on the deployment's own hardware. A query is
+ # routed to a job when ClickHouse's own estimate says it must read the
+ # cold volume, which is the case the plan names.
+ estimate: ScanEstimate | None = None
+ if not body.force_sync:
+ try:
+ estimate = await estimate_scan(rewrite.sql)
+ except ColdEstimateUnavailable as exc:
+ # Not fatal. An un-estimable query runs the way it always did,
+ # because refusing it would make the lake unusable on a
+ # deployment whose system tables this role cannot read. Logged
+ # so a permanently unreadable estimator is visible rather than
+ # silently turning the feature off.
+ logger.info("lake.sql.estimate_unavailable tenant_id=%s reason=%s", current_user.tenant_id, exc)
+ if estimate is not None and estimate.touches_cold:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail={
+ "error": "cold_scan",
+ "message": (
+ "this query reads the cold tier, which does not reliably finish inside the "
+ f"{_DEFAULT_API_TIMEOUT_SECONDS:.0f}s synchronous bound. Submit it to "
+ "POST /api/v1/lake/query-jobs, which reports progress, or set force_sync "
+ "if you already know the scan is small."
+ ),
+ "estimate": estimate.as_dict(),
+ },
+ )
+
# ---- Step 2: execute ------------------------------------------------
try:
result = await execute_lake_query(
@@ -401,6 +453,284 @@ async def execute_lake_sql(
)
+# ----------------------------------------------- cold-tier query jobs
+#
+# Depth plan 4.3, third bullet. A cold-tier scan outlives its request, so
+# it becomes a row rather than a coroutine: the API runs more than one
+# replica, and an in-process registry would lose every job on a restart
+# and 404 half of them on the other replica.
+
+
+class LakeEstimateRequest(BaseModel):
+ """Ask what a query would read, without running it."""
+
+ sql: str = Field(..., min_length=1, max_length=200_000)
+ row_cap: int | None = Field(default=None, ge=1, le=MAX_ROW_CAP)
+
+
+class LakeEstimateResponse(BaseModel):
+ estimated_rows: int
+ estimated_parts: int
+ estimated_bytes: int
+ cold_bytes: int
+ warm_bytes: int
+ touches_cold: bool
+ tables: list[str]
+ #: ``None`` when no retrieval price is configured. Never 0.0, which
+ #: would read as "free".
+ estimated_usd: float | None
+ cost_basis: str
+
+
+class LakeQueryJobRequest(BaseModel):
+ sql: str = Field(..., min_length=1, max_length=200_000)
+ row_cap: int | None = Field(default=None, ge=1, le=MAX_ROW_CAP)
+
+
+class LakeQueryJobResponse(BaseModel):
+ """A job's state. The fields a console needs to show progress honestly."""
+
+ id: uuid.UUID
+ status: str
+ referenced_tables: list[str]
+ row_cap: int
+ estimate: dict[str, Any]
+ rows_read: int
+ bytes_read: int
+ total_rows_approx: int
+ #: Nullable. ClickHouse publishes ``total_rows_approx`` best-effort,
+ #: so a running query can have a numerator and no denominator — and a
+ #: bar that invents 100% because the denominator was zero is worse
+ #: than one that says it does not know.
+ progress_ratio: float | None
+ columns: list[str] | None
+ rows: list[list[Any]] | None
+ row_count: int | None
+ error: str | None
+ created_at: datetime
+ started_at: datetime | None
+ finished_at: datetime | None
+
+
+def _job_response(job: LakeQueryJob) -> LakeQueryJobResponse:
+ return LakeQueryJobResponse(
+ id=job.id,
+ status=job.status,
+ referenced_tables=list(job.referenced_tables or []),
+ row_cap=job.row_cap,
+ estimate=job.estimate or {},
+ rows_read=job.rows_read,
+ bytes_read=job.bytes_read,
+ total_rows_approx=job.total_rows_approx,
+ progress_ratio=job.progress_ratio,
+ columns=list(job.result_columns) if job.result_columns else None,
+ rows=job.result_rows,
+ row_count=job.row_count,
+ error=job.error,
+ created_at=job.created_at,
+ started_at=job.started_at,
+ finished_at=job.finished_at,
+ )
+
+
+def _rewrite_or_raise(sql: str, tenant_id: uuid.UUID, row_cap: int | None):
+ try:
+ return rewrite_for_tenant(sql, tenant_id, row_cap=row_cap)
+ except LakeSqlForbiddenError as exc:
+ raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=f"lake SQL forbidden: {exc}") from exc
+ except LakeSqlSyntaxError as exc:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"lake SQL invalid: {exc}") from exc
+
+
[email protected]("/estimate", response_model=LakeEstimateResponse)
+async def estimate_lake_sql(
+ body: LakeEstimateRequest,
+ response: Response,
+ current_user: Annotated[AuthUser, Depends(require_permission("lake:query"))],
+) -> LakeEstimateResponse:
+ """What would this query read, and where does that data live?
+
+ Charged at the schema rate rather than the query rate: an estimate
+ runs ``EXPLAIN ESTIMATE`` and two system-table reads, none of which
+ touch tenant data. Pricing it like a scan would train analysts to
+ skip the estimate, which is the opposite of the point.
+ """
+ await _acquire_or_429(response=response, tenant_id=current_user.tenant_id, cost=_SCHEMA_COST)
+ rewrite = _rewrite_or_raise(body.sql, current_user.tenant_id, body.row_cap)
+ try:
+ estimate = await estimate_scan(rewrite.sql)
+ except ColdEstimateUnavailable as exc:
+ # 503, not an empty estimate. "We could not estimate" and "this
+ # reads nothing" are opposite answers and must not share a
+ # response shape.
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail=f"the scan could not be estimated: {exc}",
+ ) from exc
+ return LakeEstimateResponse(**estimate.as_dict())
+
+
[email protected]("/query-jobs", response_model=LakeQueryJobResponse, status_code=status.HTTP_202_ACCEPTED)
+async def submit_lake_query_job(
+ body: LakeQueryJobRequest,
+ background: BackgroundTasks,
+ response: Response,
+ request: Request,
+ current_user: Annotated[AuthUser, Depends(require_permission("lake:query"))],
+ db: DBSession,
+) -> LakeQueryJobResponse:
+ """Submit a query that is allowed to take longer than the synchronous bound.
+
+ The estimate is taken once, here, and stored on the job. It is never
+ recomputed: it is the number the analyst agreed to before the scan
+ started, and moving it afterwards would make the record of what they
+ were told untrue.
+ """
+ await _acquire_or_429(response=response, tenant_id=current_user.tenant_id, cost=_QUERY_COST)
+ rewrite = _rewrite_or_raise(body.sql, current_user.tenant_id, body.row_cap)
+
+ try:
+ estimate = (await estimate_scan(rewrite.sql)).as_dict()
+ except ColdEstimateUnavailable as exc:
+ # The job still runs. An un-estimable query is exactly the one an
+ # analyst most wants the progress state for, and refusing it here
+ # would leave them with only the synchronous path that times out.
+ logger.info("lake.job.estimate_unavailable tenant_id=%s reason=%s", current_user.tenant_id, exc)
+ estimate = {"unavailable": str(exc)}
+
+ job = LakeQueryJob(
+ tenant_id=current_user.tenant_id,
+ submitted_by=current_user.user_id,
+ submitted_email=current_user.email,
+ rewritten_sql=rewrite.sql,
+ row_cap=rewrite.row_cap,
+ referenced_tables=sorted(rewrite.referenced_tables),
+ query_id="pending",
+ estimate=estimate,
+ )
+ db.add(job)
+ await db.flush()
+ job.query_id = new_query_id(job.id)
+ await db.commit()
+ await db.refresh(job)
+
+ await _audit_query_attempt(
+ db=db,
+ tenant_id=current_user.tenant_id,
+ user_id=current_user.user_id,
+ user_email=current_user.email,
+ request=request,
+ outcome="job_submitted",
+ referenced_tables=sorted(rewrite.referenced_tables),
+ row_cap=rewrite.row_cap,
+ )
+
+ background.add_task(_start_job, job.id)
+ logger.info(
+ "lake.job.submitted job_id=%s tenant_id=%s tables=%s cold_bytes=%s",
+ job.id,
+ current_user.tenant_id,
+ sorted(rewrite.referenced_tables),
+ estimate.get("cold_bytes"),
+ )
+ return _job_response(job)
+
+
+async def _start_job(job_id: uuid.UUID) -> None:
+ """Claim and run one job.
+
+ Separated from the endpoint so the claim is the same conditional
+ UPDATE whether the job is started by the submitting replica or picked
+ up later: two replicas must not both start one scan.
+ """
+ from app.db.database import AsyncSessionLocal # noqa: PLC0415 — avoids an import cycle at module load
+
+ async with AsyncSessionLocal() as session:
+ if not await claim_job(session, job_id):
+ logger.info("lake.job.already_claimed job_id=%s", job_id)
+ return
+ await run_job(AsyncSessionLocal, job_id)
+
+
[email protected]("/query-jobs", response_model=list[LakeQueryJobResponse])
+async def list_lake_query_jobs(
+ current_user: Annotated[AuthUser, Depends(require_permission("lake:query"))],
+ db: DBSession,
+ limit: int = 50,
+) -> list[LakeQueryJobResponse]:
+ result = await db.execute(
+ select(LakeQueryJob)
+ .where(LakeQueryJob.tenant_id == current_user.tenant_id)
+ .order_by(LakeQueryJob.created_at.desc())
+ .limit(max(1, min(limit, 200)))
+ )
+ return [_job_response(job) for job in result.scalars().all()]
+
+
+async def _load_job(db: Any, tenant_id: uuid.UUID, job_id: uuid.UUID) -> LakeQueryJob:
+ """Fetch one job, scoped to the caller's tenant.
+
+ The predicate is in the query rather than left to row-level security
+ alone: a job id is a handle a console holds, and RLS here is defence
+ in depth rather than the only control.
+ """
+ result = await db.execute(
+ select(LakeQueryJob).where(
+ LakeQueryJob.id == job_id,
+ LakeQueryJob.tenant_id == tenant_id,
+ )
+ )
+ job = result.scalar_one_or_none()
+ if job is None:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="lake query job not found")
+ return job
+
+
[email protected]("/query-jobs/{job_id}", response_model=LakeQueryJobResponse)
+async def get_lake_query_job(
+ job_id: uuid.UUID,
+ current_user: Annotated[AuthUser, Depends(require_permission("lake:query"))],
+ db: DBSession,
+) -> LakeQueryJobResponse:
+ """One job's state, with a live progress read while it is running.
+
+ The live read is folded into the response but is **not** written back
+ over a terminal state: a late progress row must not make a finished
+ job look like it started again.
+ """
+ job = await _load_job(db, current_user.tenant_id, job_id)
+ if job.status == "running":
+ progress = await read_progress(job.query_id)
+ if progress is not None:
+ job.rows_read = progress.rows_read
+ job.bytes_read = progress.bytes_read
+ job.total_rows_approx = progress.total_rows_approx
+ job.progress_ratio = progress.ratio
+ await db.commit()
+ return _job_response(job)
+
+
[email protected]("/query-jobs/{job_id}/cancel", response_model=LakeQueryJobResponse)
+async def cancel_lake_query_job(
+ job_id: uuid.UUID,
+ current_user: Annotated[AuthUser, Depends(require_permission("lake:query"))],
+ db: DBSession,
+) -> LakeQueryJobResponse:
+ """Stop a running scan.
+
+ A job that has already ended answers 409 rather than being quietly
+ re-marked: cancelling a finished job would rewrite the record of what
+ happened.
+ """
+ job = await _load_job(db, current_user.tenant_id, job_id)
+ if not await cancel_job(db, job):
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail=f"this job already ended as {job.status!r}",
+ )
+ return _job_response(job)
+
+
@router.get(
"/schema",
response_model=LakeSchemaResponse,
diff --git a/services/api/app/db/clickhouse.py b/services/api/app/db/clickhouse.py
index 326d620aa..2400b316a 100644
--- a/services/api/app/db/clickhouse.py
+++ b/services/api/app/db/clickhouse.py
@@ -228,6 +228,7 @@ async def execute_lake_query(
timeout_seconds: float | None = None,
extra_settings: dict[str, Any] | None = None,
params: dict[str, Any] | None = None,
+ query_id: str | None = None,
) -> LakeQueryResult:
"""Run a rewritten lake SQL statement and return columns + rows.
@@ -307,12 +308,19 @@ async def execute_lake_query(
def _run() -> tuple[list[list[Any]], list[tuple[str, str]]]:
# ``with_column_types=True`` returns ``(rows, [(name, type), ...])``
# which we need so the API can echo a stable column ordering.
- return client.execute(
- sql,
- params or {},
- with_column_types=True,
- settings=merged_settings,
- )
+ #
+ # ``query_id`` is passed only when the caller set one. It is part
+ # of the protocol's query envelope rather than a server setting,
+ # which is why it is an argument here and not merged into
+ # ``settings`` — and it is what makes a long scan's progress
+ # readable from ``system.processes``.
+ kwargs: dict[str, Any] = {
+ "with_column_types": True,
+ "settings": merged_settings,
+ }
+ if query_id is not None:
+ kwargs["query_id"] = query_id
+ return client.execute(sql, params or {}, **kwargs)
try:
rows, column_meta = await asyncio.wait_for(asyncio.to_thread(_run), timeout=asyncio_cap)
@@ -349,6 +357,42 @@ async def execute_lake_query(
)
+async def execute_lake_query_with_id(
+ sql: str,
+ *,
+ query_id: str,
+ timeout_seconds: float,
+ params: dict[str, Any] | None = None,
+ extra_settings: dict[str, Any] | None = None,
+) -> LakeQueryResult:
+ """Run a query under a caller-chosen ClickHouse query id.
+
+ The id is what makes progress readable: ``system.processes`` is keyed
+ on it, so a poller can ask the server how far a running scan has got
+ rather than guessing from elapsed time. Without it a long cold-tier
+ query is a black box that either returns or times out, which is the
+ behaviour depth item 4.3 exists to replace.
+
+ Thin on purpose — it is :func:`execute_lake_query` with the id
+ threaded through, so the two cannot drift in how they clamp the
+ timeout or normalise driver exceptions.
+
+ The id goes to the driver's own ``query_id`` argument rather than
+ into ``settings``: ``query_id`` is part of the protocol's query
+ envelope and is not a server setting, so putting it in the settings
+ map would either be rejected as unknown or silently ignored,
+ depending on the driver version — and a progress poller keyed on an
+ id the server never saw returns "not running" for a query that is.
+ """
+ return await execute_lake_query(
+ sql,
+ timeout_seconds=timeout_seconds,
+ extra_settings=extra_settings,
+ params=params,
+ query_id=query_id,
+ )
+
+
async def fetch_lake_schema(
*,
tables: Iterable[str] | None = None,
diff --git a/services/api/app/models/lake_query_job.py b/services/api/app/models/lake_query_job.py
new file mode 100644
index 000000000..c6783ed4c
--- /dev/null
+++ b/services/api/app/models/lake_query_job.py
@@ -0,0 +1,66 @@
+"""Cold-tier lake query jobs (depth plan 4.3).
+
+A job is a lake query that outlives the request that started it, because
+reading the cold volume is not a thing that reliably finishes inside the
+published 30-second synchronous bound.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime
+from typing import Any
+
+from sqlalchemy import BigInteger, DateTime, Float, ForeignKey, Integer, Text
+from sqlalchemy.dialects.postgresql import ARRAY, JSONB, UUID
+from sqlalchemy.orm import Mapped, mapped_column
+
+from app.db.database import Base
+
+#: The lifecycle. `queued` is the only state a runner may claim, and a
+#: terminal state is never left.
+JOB_STATUSES = ("queued", "running", "succeeded", "failed", "cancelled")
+TERMINAL_STATUSES = frozenset({"succeeded", "failed", "cancelled"})
+
+
+class LakeQueryJob(Base):
+ __tablename__ = "lake_query_jobs"
+
+ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)
+ submitted_by: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True)
+ submitted_email: Mapped[str | None] = mapped_column(Text, nullable=True)
+
+ #: The rewritten, tenant-scoped SQL — never the caller's original,
+ #: which carries no tenant predicate.
+ rewritten_sql: Mapped[str] = mapped_column(Text, nullable=False)
+ row_cap: Mapped[int] = mapped_column(Integer, nullable=False)
+ referenced_tables: Mapped[list[str]] = mapped_column(ARRAY(Text), nullable=False, default=list)
+
+ query_id: Mapped[str] = mapped_column(Text, nullable=False, unique=True)
+ status: Mapped[str] = mapped_column(Text, nullable=False, default="queued")
+
+ #: As written at submit time and never recomputed: it is the number
+ #: the analyst agreed to before the scan started.
+ estimate: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False, default=dict)
+
+ rows_read: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
+ bytes_read: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
+ total_rows_approx: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
+ #: Nullable on purpose. NULL means unknown, never zero.
+ progress_ratio: Mapped[float | None] = mapped_column(Float, nullable=True)
+
+ result_columns: Mapped[list[str] | None] = mapped_column(ARRAY(Text), nullable=True)
+ result_rows: Mapped[Any | None] = mapped_column(JSONB, nullable=True)
+ row_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
+
+ error: Mapped[str | None] = mapped_column(Text, nullable=True)
+
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
+ started_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
+ finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
+ updated_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True),
+ default=lambda: datetime.now(UTC),
+ onupdate=lambda: datetime.now(UTC),
+ )
diff --git a/services/api/app/services/lake_cold_query.py b/services/api/app/services/lake_cold_query.py
new file mode 100644
index 000000000..b3c165b54
--- /dev/null
+++ b/services/api/app/services/lake_cold_query.py
@@ -0,0 +1,373 @@
+"""Estimating and pacing a query that has to read the cold tier.
+
+Depth plan 4.3, third bullet: *a query over cold data through ``/lake/sql``
+or a hunt reports an estimated cost and a progress state instead of timing
+out silently.*
+
+What was wrong
+--------------
+``/lake/sql`` already reported a ``cost``, but it was the rate limiter's
+token price — a number about how often you may ask, not about how much the
+asking will read. And there was no progress state at all: a query over the
+cold volume either came back inside the published 30-second default or
+raised ``LakeQueryTimeoutError``, which tells an analyst nothing about
+whether a longer timeout would have helped, how much data was involved, or
+what it would have cost to find out.
+
+Where the numbers come from
+---------------------------
+Every figure here is ClickHouse's, not ours.
+
+* Rows and parts come from ``EXPLAIN ESTIMATE``, which is the planner's
+ own answer after partition pruning.
+* The warm/cold split comes from ``system.parts`` joined to
+ ``system.disks``, matched against the volume names the tiering storage
+ policy declares. A part is cold because ClickHouse says it is on the
+ cold volume, not because of its age — the two disagree whenever a move
+ is in flight or the TTL has been changed, and the disk is the one that
+ decides what the read costs.
+* Progress comes from ``system.processes`` keyed on the query id we set,
+ so ``rows_read`` and ``total_rows_approx`` are the server's counters.
+
+There is deliberately **no invented throughput constant**. A predicted
+"this will take N seconds" would need a bytes-per-second figure, and the
+only honest source for one is a measurement on the deployment's own
+hardware, which this code has not got. The routing rule therefore does not
+predict a duration: a query is routed to a job when the estimate says it
+must read the **cold volume**, which is the case the plan names, and the
+synchronous bound stays the published 30-second default and 60-second
+maximum that ``/lake/sql`` already documents.
+
+Money
+-----
+``estimated_usd`` is ``None`` unless an operator has configured a
+retrieval price. ``docs/decisions/storage-cost-model.json`` is a *storage*
+rate card — dollars per GB-month resident — and using it to price a read
+would be quoting the wrong number confidently. A deployment that knows its
+provider's retrieval price sets ``AISOC_LAKE_COLD_RETRIEVAL_USD_PER_GB``
+and gets a figure derived from it; one that does not gets ``None`` and the
+reason, which is more useful than a plausible invention.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import re
+from dataclasses import asdict, dataclass, field
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+#: Volume names the tiering storage policy declares
+#: (``services/api/clickhouse/tiering/storage-policy.xml``). A part on one
+#: of these is a part whose read leaves local disk.
+COLD_VOLUME_NAMES = frozenset({"cold"})
+
+#: The table the lake stores events in. Estimating is scoped to the
+#: allowlisted tables the rewriter already permits; this is the only one
+#: that is tiered today, and a table absent from the parts query
+#: contributes zero cold bytes rather than being guessed at.
+LAKE_DATABASE = "aisoc"
+
+#: Environment variable carrying the deployment's own retrieval price. No
+#: default: see the module docstring.
+RETRIEVAL_PRICE_ENV = "AISOC_LAKE_COLD_RETRIEVAL_USD_PER_GB"
+
+_BYTES_PER_GB = 1024**3
+
+
+class ColdEstimateUnavailable(RuntimeError):
+ """The estimate could not be produced.
+
+ Raised rather than returning a zero. A scan estimate of zero and "we
+ could not estimate" are opposite answers, and returning the first for
+ the second is how a query over 400 days of cold data gets waved
+ through as free.
+ """
+
+
+@dataclass(frozen=True)
+class ScanEstimate:
+ """What a query is expected to read, split by where the data lives."""
+
+ estimated_rows: int
+ estimated_parts: int
+ estimated_bytes: int
+ cold_bytes: int
+ warm_bytes: int
+ tables: list[str] = field(default_factory=list)
+ #: ``None`` when no retrieval price is configured, with ``cost_basis``
+ #: saying so. Never 0.0, which would read as "free".
+ estimated_usd: float | None = None
+ cost_basis: str = ""
+
+ @property
+ def touches_cold(self) -> bool:
+ return self.cold_bytes > 0
+
+ def as_dict(self) -> dict[str, Any]:
+ payload = asdict(self)
+ payload["touches_cold"] = self.touches_cold
+ return payload
+
+
+def _retrieval_price() -> float | None:
+ raw = os.environ.get(RETRIEVAL_PRICE_ENV, "").strip()
+ if not raw:
+ return None
+ try:
+ price = float(raw)
+ except ValueError:
+ # Loud: an operator who set a price and got no figure would
+ # reasonably conclude the feature does not work.
+ logger.error(
+ "%s is set to %r, which is not a number; no cost figure will be reported",
+ RETRIEVAL_PRICE_ENV,
+ raw,
+ )
+ return None
+ if price < 0:
+ logger.error("%s is negative (%s); ignoring it", RETRIEVAL_PRICE_ENV, price)
+ return None
+ return price
+
+
+def price_cold_bytes(cold_bytes: int) -> tuple[float | None, str]:
+ """Turn cold bytes into a money figure, or say why there is none."""
+ price = _retrieval_price()
+ if price is None:
+ return None, (
+ "no retrieval price is configured, so no money figure is reported. "
+ f"docs/decisions/storage-cost-model.json is a storage rate card (dollars per GB-month "
+ f"resident) and pricing a read from it would be quoting the wrong number. Set "
+ f"{RETRIEVAL_PRICE_ENV} to your provider's retrieval price to get one."
+ )
+ gb = cold_bytes / _BYTES_PER_GB
+ return round(gb * price, 4), (f"{gb:.3f} GB from the cold volume at the configured {RETRIEVAL_PRICE_ENV}={price} USD/GB")
+
+
+# ``EXPLAIN ESTIMATE`` returns one row per table with the columns
+# (database, table, parts, rows, marks). Column order is stable across the
+# versions this project supports, but the rows are read by name where the
+# driver gives names and by position only as a fallback — a silent column
+# reorder would otherwise swap parts and rows, and both are plausible
+# integers.
+_ESTIMATE_COLUMNS = ("database", "table", "parts", "rows", "marks")
+
+
+def parse_explain_estimate(columns: list[str], rows: list[list[Any]]) -> tuple[int, int, list[str]]:
+ """Fold ``EXPLAIN ESTIMATE`` output into (rows, parts, tables)."""
+ if not rows:
+ return 0, 0, []
+ index = {name: i for i, name in enumerate(columns)}
+ if not {"rows", "parts"} <= set(index):
+ if len(columns) != len(_ESTIMATE_COLUMNS):
+ raise ColdEstimateUnavailable(f"EXPLAIN ESTIMATE returned columns {columns!r}, which this build cannot read")
+ index = {name: i for i, name in enumerate(_ESTIMATE_COLUMNS)}
+
+ total_rows = 0
+ total_parts = 0
+ tables: list[str] = []
+ for row in rows:
+ total_rows += int(row[index["rows"]] or 0)
+ total_parts += int(row[index["parts"]] or 0)
+ if "table" in index:
+ name = str(row[index["table"]] or "")
+ if name and name not in tables:
+ tables.append(name)
+ return total_rows, total_parts, tables
+
+
+# The parts query. Scoped to the lake database and to the tables the
+# estimate named, so a tenant's estimate does not read the whole cluster's
+# part list. ``active`` matters: inactive parts are merge leftovers that
+# no query reads, and counting them would inflate every estimate.
+PARTS_SQL = (
+ "SELECT disks.name AS disk, "
+ "sum(parts.bytes_on_disk) AS bytes_on_disk "
+ "FROM system.parts AS parts "
+ "LEFT JOIN system.disks AS disks ON disks.name = parts.disk_name "
+ "WHERE parts.active AND parts.database = %(database)s AND parts.table IN %(tables)s "
+ "GROUP BY disks.name"
+)
+
+
+def split_bytes_by_volume(
+ rows: list[list[Any]],
+ *,
+ cold_disk_names: frozenset[str],
+) -> tuple[int, int]:
+ """Split ``(disk, bytes)`` pairs into (cold, warm).
+
+ A disk name this deployment does not recognise as cold counts as warm.
+ That direction is deliberate: over-reporting cold bytes would route
+ ordinary queries into the job path and make the feature feel broken,
+ while under-reporting routes a genuinely cold query to the
+ synchronous path where it fails the way it always did — no worse than
+ before, and visible.
+ """
+ cold = 0
+ warm = 0
+ for row in rows:
+ disk = str(row[0] or "")
+ size = int(row[1] or 0)
+ if disk in cold_disk_names:
+ cold += size
+ else:
+ warm += size
+ return cold, warm
+
+
+def cold_disk_names_from_policy(policy_rows: list[list[Any]]) -> frozenset[str]:
+ """Which disks belong to a cold volume, per ``system.storage_policies``.
+
+ Read from the server rather than hardcoded, because the volume is
+ named in a mounted XML file an operator owns. The constant above is
+ the fallback for a deployment that has not applied the tiering
+ migration, where there is no cold volume and the answer is empty
+ anyway.
+ """
+ names: set[str] = set()
+ for row in policy_rows:
+ volume = str(row[0] or "")
+ if volume not in COLD_VOLUME_NAMES:
+ continue
+ disks = row[1]
+ if isinstance(disks, (list, tuple)):
+ names.update(str(d) for d in disks)
+ elif disks:
+ names.add(str(disks))
+ return frozenset(names)
+
+
+#: A query id is echoed into logs and into ``system.processes``; keeping it
+#: to a known-safe alphabet means it can never carry anything that would
+#: need escaping wherever it is rendered.
+_QUERY_ID_SAFE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
+
+
+def validate_query_id(query_id: str) -> str:
+ if not _QUERY_ID_SAFE.match(query_id):
+ raise ValueError(f"query id {query_id!r} is not of the expected shape")
+ return query_id
+
+
+@dataclass(frozen=True)
+class QueryProgress:
+ """A running query's own counters, from ``system.processes``.
+
+ ``total_rows_approx`` is ClickHouse's estimate and can move while the
+ query runs, so ``ratio`` is clamped and is explicitly ``None`` when
+ the server has not published a total — a progress bar that invents
+ 100% because the denominator was zero is worse than one that says it
+ does not know.
+ """
+
+ rows_read: int
+ bytes_read: int
+ total_rows_approx: int
+ elapsed_seconds: float
+
+ @property
+ def ratio(self) -> float | None:
+ if self.total_rows_approx <= 0:
+ return None
+ return min(1.0, self.rows_read / self.total_rows_approx)
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "rows_read": self.rows_read,
+ "bytes_read": self.bytes_read,
+ "total_rows_approx": self.total_rows_approx,
+ "elapsed_seconds": round(self.elapsed_seconds, 3),
+ "ratio": self.ratio,
+ }
+
+
+PROGRESS_SQL = "SELECT read_rows, read_bytes, total_rows_approx, elapsed FROM system.processes WHERE query_id = %(query_id)s"
+
+#: Which disks each storage volume holds, per the server.
+POLICY_SQL = "SELECT arrayJoin(volume_name) AS volume, disks FROM system.storage_policies"
+
+
+async def estimate_scan(rewritten_sql: str) -> ScanEstimate:
+ """Ask ClickHouse what a query will read, and where it lives.
+
+ Every number here is the server's. This function does no arithmetic
+ beyond summing what it is told and converting bytes to a price when
+ one is configured.
+
+ Raises :class:`ColdEstimateUnavailable` when the server cannot be
+ asked, rather than returning zeros — a scan estimate of zero and "we
+ could not estimate" are opposite answers, and returning the first for
+ the second waves a 400-day cold scan through as free.
+ """
+ # Imported here rather than at module scope: app.db.clickhouse imports
+ # the driver lazily and importing it at module load would pull the
+ # soft dependency into every process that imports this module, which
+ # includes the pure-function tests.
+ from app.db.clickhouse import ( # noqa: PLC0415
+ LakeQueryError,
+ LakeQueryNotConfiguredError,
+ execute_lake_query,
+ )
+
+ try:
+ explained = await execute_lake_query(f"EXPLAIN ESTIMATE {rewritten_sql}", timeout_seconds=10.0)
+ except LakeQueryNotConfiguredError as exc:
+ raise ColdEstimateUnavailable("the lake backend is not configured") from exc
+ except LakeQueryError as exc:
+ raise ColdEstimateUnavailable(f"EXPLAIN ESTIMATE failed: {exc}") from exc
+
+ rows, parts, tables = parse_explain_estimate(explained.columns, explained.rows)
+ if not tables:
+ # A query the planner attributes to no table reads nothing from
+ # the lake — a constant select, say. Zero is the right answer
+ # here and is distinguishable from the failure above, which
+ # raises.
+ return ScanEstimate(
+ estimated_rows=rows,
+ estimated_parts=parts,
+ estimated_bytes=0,
+ cold_bytes=0,
+ warm_bytes=0,
+ tables=[],
+ estimated_usd=None,
+ cost_basis="this query reads no lake table",
+ )
+
+ try:
+ policies = await execute_lake_query(POLICY_SQL, timeout_seconds=10.0)
+ cold_disks = cold_disk_names_from_policy(policies.rows)
+ except (LakeQueryError, LakeQueryNotConfiguredError) as exc:
+ # A deployment that has not applied the tiering migration has no
+ # cold volume and no storage_policies row for one. Treated as
+ # "nothing is cold" rather than as a failure, because that is the
+ # truth on an untiered deployment and refusing to estimate would
+ # make this feature unusable there.
+ logger.info("lake.estimate.no_storage_policy reason=%s", exc)
+ cold_disks = frozenset()
+
+ try:
+ parts_result = await execute_lake_query(
+ PARTS_SQL,
+ timeout_seconds=10.0,
+ params={"database": LAKE_DATABASE, "tables": tuple(tables)},
+ )
+ except (LakeQueryError, LakeQueryNotConfiguredError) as exc:
+ raise ColdEstimateUnavailable(f"could not read system.parts: {exc}") from exc
+
+ cold_bytes, warm_bytes = split_bytes_by_volume(parts_result.rows, cold_disk_names=cold_disks)
+ estimated_usd, basis = price_cold_bytes(cold_bytes)
+
+ return ScanEstimate(
+ estimated_rows=rows,
+ estimated_parts=parts,
+ estimated_bytes=cold_bytes + warm_bytes,
+ cold_bytes=cold_bytes,
+ warm_bytes=warm_bytes,
+ tables=tables,
+ estimated_usd=estimated_usd,
+ cost_basis=basis,
+ )
diff --git a/services/api/app/services/lake_query_runner.py b/services/api/app/services/lake_query_runner.py
new file mode 100644
index 000000000..f917686e8
--- /dev/null
+++ b/services/api/app/services/lake_query_runner.py
@@ -0,0 +1,310 @@
+"""Running a cold-tier lake query as a job, and reporting its progress.
+
+Depth plan 4.3. The synchronous path at ``POST /lake/sql`` is bounded by
+the published 30-second default and 60-second maximum. A scan that has to
+read the cold volume is routed here instead, where it reports what it is
+doing rather than disappearing until it either returns or raises a
+timeout.
+
+Three things this module is careful about, each because the opposite has
+shipped in this repository before.
+
+**A claim is atomic.** The runner claims a job with a conditional UPDATE
+rather than a SELECT followed by an UPDATE, so two API replicas cannot
+both start the same scan. Two concurrent reads of the cold volume for one
+analyst's question is the cost of getting that wrong.
+
+**Progress is the server's.** ``rows_read`` and ``total_rows_approx``
+come from ``system.processes``. Nothing here derives a percentage from
+elapsed time, because elapsed time over a cold read is not proportional
+to anything.
+
+**A terminal state is never left.** A job that failed stays failed. The
+alternative — a poller that resets a finished job because a stale
+progress read came back — is how a completed query appears to start
+again.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import logging
+import uuid
+from datetime import UTC, datetime
+from typing import Any
+
+from sqlalchemy import select, update
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from app.db.clickhouse import (
+ LakeQueryError,
+ LakeQueryNotConfiguredError,
+ LakeQueryTimeoutError,
+ execute_lake_query,
+ execute_lake_query_with_id,
+)
+from app.models.lake_query_job import TERMINAL_STATUSES, LakeQueryJob
+from app.services.lake_cold_query import PROGRESS_SQL, QueryProgress, validate_query_id
+
+logger = logging.getLogger(__name__)
+
+#: How long a job may run before the runner gives up on it. Far above the
+#: synchronous bound — the whole point is that this path is allowed to
+#: take longer — and still bounded, because an unbounded query holds a
+#: ClickHouse thread and a cold-volume read budget indefinitely.
+#:
+#: Fifteen minutes is a policy choice, not a measurement, and is stated as
+#: one: nothing here claims a cold scan takes fifteen minutes. It is the
+#: ceiling past which a human should be asked whether they still want the
+#: answer.
+JOB_TIMEOUT_SECONDS = 15 * 60.0
+
+#: How often the poller asks ClickHouse where the query has got to. Two
+#: seconds is frequent enough for a console progress bar and rare enough
+#: that the poll is not itself a load.
+PROGRESS_POLL_SECONDS = 2.0
+
+
+def new_query_id(job_id: uuid.UUID) -> str:
+ """A ClickHouse query id derived from the job id.
+
+ Derived rather than random so the two can always be matched up in a
+ ClickHouse query log by someone who only has one of them.
+ """
+ return validate_query_id(f"aisoc-lake-{job_id}")
+
+
+async def read_progress(query_id: str) -> QueryProgress | None:
+ """Ask ClickHouse how far a running query has got.
+
+ ``None`` means the server does not know about this query id, which is
+ true both before it starts and after it finishes. The caller
+ distinguishes those by the job's own status rather than by this
+ answer, because "not running" is not "not started".
+ """
+ try:
+ result = await execute_lake_query(
+ PROGRESS_SQL,
+ timeout_seconds=5.0,
+ params={"query_id": query_id},
+ )
+ except (LakeQueryError, LakeQueryNotConfiguredError) as exc:
+ # Not fatal to the job: the scan is still running whether or not
+ # the progress read succeeded. Logged rather than swallowed, so a
+ # permanently unreadable system.processes is visible instead of
+ # looking like a query that never progresses.
+ logger.warning("lake.job.progress_unreadable query_id=%s error=%s", query_id, exc)
+ return None
+ if not result.rows:
+ return None
+ row = result.rows[0]
+ return QueryProgress(
+ rows_read=int(row[0] or 0),
+ bytes_read=int(row[1] or 0),
+ total_rows_approx=int(row[2] or 0),
+ elapsed_seconds=float(row[3] or 0.0),
+ )
+
+
+async def claim_job(session: AsyncSession, job_id: uuid.UUID) -> bool:
+ """Move one job from ``queued`` to ``running``, atomically.
+
+ The ``status == 'queued'`` predicate is the whole mechanism: a second
+ replica running the same statement updates zero rows and learns that
+ it lost. A SELECT-then-UPDATE would have both replicas read `queued`
+ and both start the scan.
+ """
+ result = await session.execute(
+ update(LakeQueryJob)
+ .where(LakeQueryJob.id == job_id, LakeQueryJob.status == "queued")
+ .values(status="running", started_at=datetime.now(UTC), updated_at=datetime.now(UTC))
+ .returning(LakeQueryJob.id)
+ )
+ claimed = result.scalar_one_or_none() is not None
+ await session.commit()
+ return claimed
+
+
+async def _record_progress(
+ session_factory: async_sessionmaker[AsyncSession],
+ job_id: uuid.UUID,
+ progress: QueryProgress,
+) -> None:
+ async with session_factory() as session:
+ await session.execute(
+ update(LakeQueryJob)
+ .where(LakeQueryJob.id == job_id, LakeQueryJob.status == "running")
+ .values(
+ rows_read=progress.rows_read,
+ bytes_read=progress.bytes_read,
+ total_rows_approx=progress.total_rows_approx,
+ progress_ratio=progress.ratio,
+ updated_at=datetime.now(UTC),
+ )
+ )
+ await session.commit()
+
+
+async def _finish(
+ session_factory: async_sessionmaker[AsyncSession],
+ job_id: uuid.UUID,
+ **values: Any,
+) -> None:
+ """Write a terminal state, and only onto a job that is still running.
+
+ The ``status == 'running'`` predicate stops a late finish from
+ overwriting a cancellation an operator has already made.
+ """
+ async with session_factory() as session:
+ await session.execute(
+ update(LakeQueryJob)
+ .where(LakeQueryJob.id == job_id, LakeQueryJob.status == "running")
+ .values(finished_at=datetime.now(UTC), updated_at=datetime.now(UTC), **values)
+ )
+ await session.commit()
+
+
+async def run_job(
+ session_factory: async_sessionmaker[AsyncSession],
+ job_id: uuid.UUID,
+ *,
+ timeout_seconds: float = JOB_TIMEOUT_SECONDS,
+ poll_seconds: float = PROGRESS_POLL_SECONDS,
+) -> None:
+ """Execute one claimed job, recording progress until it ends.
+
+ Exceptions are turned into a ``failed`` status rather than being
+ allowed to escape: this runs as a background task, and an exception
+ escaping a background task leaves a job stuck at ``running`` forever
+ with nothing in any log explaining why.
+ """
+ async with session_factory() as session:
+ job = await session.get(LakeQueryJob, job_id)
+ if job is None:
+ logger.warning("lake.job.vanished job_id=%s", job_id)
+ return
+ if job.status != "running":
+ logger.info("lake.job.not_running job_id=%s status=%s", job_id, job.status)
+ return
+ sql = job.rewritten_sql
+ query_id = job.query_id
+
+ poller = asyncio.create_task(_poll(session_factory, job_id, query_id, poll_seconds))
+ try:
+ result = await execute_lake_query_with_id(
+ sql,
+ query_id=query_id,
+ timeout_seconds=timeout_seconds,
+ )
+ except LakeQueryTimeoutError as exc:
+ await _finish(
+ session_factory,
+ job_id,
+ status="failed",
+ error=(
+ f"the scan exceeded the job ceiling of {timeout_seconds:.0f}s: {exc}. "
+ "Narrow the time range or the columns selected, or raise the ceiling for this deployment."
+ ),
+ )
+ return
+ except (LakeQueryError, LakeQueryNotConfiguredError) as exc:
+ await _finish(session_factory, job_id, status="failed", error=str(exc))
+ return
+ except Exception as exc: # noqa: BLE001 — see the docstring
+ logger.exception("lake.job.unexpected job_id=%s", job_id)
+ await _finish(session_factory, job_id, status="failed", error=f"unexpected error: {exc}")
+ return
+ finally:
+ poller.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await poller
+
+ await _finish(
+ session_factory,
+ job_id,
+ status="succeeded",
+ result_columns=result.columns,
+ result_rows=_jsonable(result.rows),
+ row_count=result.row_count,
+ rows_read=result.row_count,
+ progress_ratio=1.0,
+ )
+ logger.info("lake.job.succeeded job_id=%s rows=%d elapsed_ms=%d", job_id, result.row_count, result.elapsed_ms)
+
+
+async def _poll(
+ session_factory: async_sessionmaker[AsyncSession],
+ job_id: uuid.UUID,
+ query_id: str,
+ poll_seconds: float,
+) -> None:
+ while True:
+ await asyncio.sleep(poll_seconds)
+ progress = await read_progress(query_id)
+ if progress is None:
+ continue
+ await _record_progress(session_factory, job_id, progress)
+
+
+def _jsonable(rows: list[list[Any]]) -> list[list[Any]]:
+ """Make driver values storable in JSONB.
+
+ ClickHouse returns datetimes, UUIDs and Decimals as Python objects,
+ and ``json.dumps`` refuses all three. Stringifying them here keeps
+ the failure out of the commit, where it would mark a succeeded scan
+ as failed after it had already paid for the read.
+ """
+ out: list[list[Any]] = []
+ for row in rows:
+ converted: list[Any] = []
+ for value in row:
+ if isinstance(value, (str, int, float, bool)) or value is None:
+ converted.append(value)
+ elif isinstance(value, (list, tuple)):
+ converted.append([str(v) for v in value])
+ else:
+ converted.append(str(value))
+ out.append(converted)
+ return out
+
+
+async def cancel_job(session: AsyncSession, job: LakeQueryJob) -> bool:
+ """Mark a job cancelled and ask ClickHouse to stop the query.
+
+ Returns False for a job that has already ended. Cancelling a finished
+ job would rewrite the record of what happened.
+ """
+ if job.status in TERMINAL_STATUSES:
+ return False
+ job.status = "cancelled"
+ job.finished_at = datetime.now(UTC)
+ job.error = "cancelled by an operator"
+ await session.commit()
+
+ # Best effort, and after the status is durable: if the KILL fails the
+ # job is still correctly recorded as cancelled, and the query will
+ # end at the job ceiling anyway. The id is validated at construction,
+ # so it cannot carry anything that needs escaping here.
+ try:
+ await execute_lake_query(
+ "KILL QUERY WHERE query_id = %(query_id)s ASYNC",
+ timeout_seconds=5.0,
+ params={"query_id": job.query_id},
+ )
+ except (LakeQueryError, LakeQueryNotConfiguredError) as exc:
+ logger.warning("lake.job.kill_failed job_id=%s error=%s", job.id, exc)
+ return True
+
+
+async def list_stuck_jobs(session: AsyncSession, older_than_seconds: float) -> list[LakeQueryJob]:
+ """Jobs still `running` long past the ceiling.
+
+ A job whose runner died mid-scan — an API replica restarted, say —
+ stays `running` forever with no task behind it, which reads to an
+ analyst as a query that is still working. Surfacing them is what lets
+ readiness and the console say otherwise.
+ """
+ cutoff = datetime.now(UTC).timestamp() - older_than_seconds
+ result = await session.execute(select(LakeQueryJob).where(LakeQueryJob.status == "running"))
+ return [job for job in result.scalars().all() if job.started_at is not None and job.started_at.timestamp() < cutoff]
diff --git a/services/api/migrations/111_lake_query_jobs.sql b/services/api/migrations/111_lake_query_jobs.sql
new file mode 100644
index 000000000..8c00b3f92
--- /dev/null
+++ b/services/api/migrations/111_lake_query_jobs.sql
@@ -0,0 +1,107 @@
+-- Depth plan 4.3, third bullet — a query over cold data reports an
+-- estimated cost and a progress state instead of timing out silently.
+--
+-- Why a table rather than an in-process dictionary
+-- ------------------------------------------------
+-- A cold-tier scan outlives the request that started it, and the API runs
+-- more than one replica. An in-process job registry would lose every job
+-- on a restart and answer 404 for half of them on a second replica, which
+-- is the shape this repository has already shipped three times (API keys,
+-- marketplace installs, the action-approval store).
+--
+-- `progress_ratio` is deliberately nullable. ClickHouse publishes
+-- `total_rows_approx` on a best-effort basis, so a running query can have
+-- a row count and no denominator. A progress bar that invents 100%
+-- because the denominator was zero is worse than one that says it does
+-- not know.
+--
+-- `estimate` is stored as written at submit time and never recomputed.
+-- It is the number the analyst agreed to before the scan started; moving
+-- it afterwards would make the record of what they were told untrue.
+
+CREATE TABLE IF NOT EXISTS lake_query_jobs (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
+ -- The authenticated principal that submitted it. Nullable only
+ -- because a service principal has no user row; a job with neither is
+ -- refused at the API.
+ submitted_by UUID,
+ submitted_email TEXT,
+
+ -- The rewritten, tenant-scoped SQL. Stored rather than the caller's
+ -- original: the original has no tenant predicate, and a re-run from
+ -- this row must not be able to resolve to a different tenant than the
+ -- submission did.
+ rewritten_sql TEXT NOT NULL,
+ row_cap INTEGER NOT NULL,
+ referenced_tables TEXT[] NOT NULL DEFAULT '{}',
+
+ -- The ClickHouse query id, so progress can be read from
+ -- system.processes and the query can be killed.
+ query_id TEXT NOT NULL UNIQUE,
+
+ status TEXT NOT NULL DEFAULT 'queued'
+ CHECK (status IN ('queued','running','succeeded','failed','cancelled')),
+
+ estimate JSONB NOT NULL DEFAULT '{}',
+
+ rows_read BIGINT NOT NULL DEFAULT 0,
+ bytes_read BIGINT NOT NULL DEFAULT 0,
+ total_rows_approx BIGINT NOT NULL DEFAULT 0,
+ progress_ratio DOUBLE PRECISION,
+
+ -- The result, bounded by row_cap at submit time. Held here rather
+ -- than streamed because the caller is polling: there is nothing to
+ -- stream to.
+ result_columns TEXT[],
+ result_rows JSONB,
+ row_count INTEGER,
+
+ -- Why it ended, when it ended badly. A failed job with no reason is
+ -- indistinguishable from one nobody looked at.
+ error TEXT,
+
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ started_at TIMESTAMPTZ,
+ finished_at TIMESTAMPTZ,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+-- The poll path: one tenant's jobs, newest first.
+CREATE INDEX IF NOT EXISTS lake_query_jobs_tenant_idx
+ ON lake_query_jobs (tenant_id, created_at DESC);
+
+-- The runner's claim path. Partial, because a finished job is never
+-- claimed again and indexing the history would grow without bound.
+CREATE INDEX IF NOT EXISTS lake_query_jobs_queued_idx
+ ON lake_query_jobs (created_at)
+ WHERE status = 'queued';
+
+COMMENT ON TABLE lake_query_jobs IS
+ 'Cold-tier lake queries that outlive their request. A job carries the estimate the analyst '
+ 'agreed to before the scan started, and the server''s own progress counters while it runs.';
+
+COMMENT ON COLUMN lake_query_jobs.progress_ratio IS
+ 'Nullable on purpose: ClickHouse publishes total_rows_approx best-effort, so a running query '
+ 'can have a numerator and no denominator. NULL means unknown, never zero.';
+
+COMMENT ON COLUMN lake_query_jobs.estimate IS
+ 'As written at submit time and never recomputed. It is the number the analyst agreed to.';
+
+-- Written out rather than looped with format(), so the policy stays
+-- visible to grep and to scripts/check_tenant_query_predicates.py.
+DO $$
+BEGIN
+ EXECUTE 'ALTER TABLE lake_query_jobs ENABLE ROW LEVEL SECURITY';
+ EXECUTE 'ALTER TABLE lake_query_jobs FORCE ROW LEVEL SECURITY';
+ EXECUTE 'DROP POLICY IF EXISTS tenant_isolation ON lake_query_jobs';
+ EXECUTE
+ 'CREATE POLICY tenant_isolation ON lake_query_jobs '
+ 'USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL) '
+ 'WITH CHECK (tenant_id = current_tenant_id())';
+
+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THEN
+ EXECUTE 'GRANT SELECT, INSERT, UPDATE, DELETE ON lake_query_jobs TO aisoc_app';
+ END IF;
+END
+$$;