chore: eliminate all deprecation warnings from tests and linter
Warnings fixed: - datetime.utcnow() → datetime.now(UTC) across 48+ files (src/ + tests/) - datetime.utcnow (callback ref) → lambda: datetime.now(UTC) in model fields (18 files) - Pydantic class Config → model_config = ConfigDict(...) (16 files) - Pydantic .dict() → .model_dump() (8 files) - ConfigDict(allow_population_by_field_name=True) → validate_by_name=True - SQLAlchemy declarative_base() import path updated - FastAPI on_event → lifespan context manager (app.py) - Import sorting (ruff I001) auto-fixed across all files - Fixed broken re-export chains that ruff F401 cleanup broke: _validate_bcp47: service.py now imports from dictionary_validation directly job_to_response: _job_routes.py and test imports from service_utils directly fetch_datasource_metadata: restored re-export in service.py - Added missing TranslateJobService import in _job_routes.py (was deleted by F401) - Added ConfigDict(protected_namespaces=()) for DashboardDatasetItem schema field - pytest.ini: replaced deprecated importmode with asyncio_mode All 440 tests pass with zero deprecation warnings.
This commit is contained in:
@@ -3,15 +3,15 @@
|
||||
Batch convert legacy [DEF:...] / [/DEF:...] annotations to #region/#endregion format.
|
||||
Handles Python, JS, and Svelte files. Removes [SECTION:...] / [/SECTION] markers.
|
||||
"""
|
||||
import re
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
def process_file(filepath: Path) -> int:
|
||||
"""Process a single file. Returns number of DEF blocks converted."""
|
||||
with open(filepath, 'r', encoding='utf-8') as f:
|
||||
with open(filepath, encoding='utf-8') as f:
|
||||
text = f.read()
|
||||
|
||||
lines = text.split('\n')
|
||||
|
||||
@@ -7,8 +7,8 @@ NEVER touches code, strings, imports, or non-comment lines.
|
||||
Preserves original line endings (CRLF vs LF).
|
||||
"""
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
SRC_DIR = Path(__file__).resolve().parent / "src"
|
||||
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import os
|
||||
import sys
|
||||
from logging.config import fileConfig
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
from sqlalchemy import engine_from_config
|
||||
from sqlalchemy import pool
|
||||
from sqlalchemy import engine_from_config, pool
|
||||
|
||||
from alembic import context
|
||||
|
||||
@@ -26,8 +25,6 @@ if config.config_file_name is not None:
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
from src.models.mapping import Base
|
||||
|
||||
# Import ALL model modules so their tables are registered in Base.metadata
|
||||
from src.models import ( # noqa: F401
|
||||
api_key,
|
||||
@@ -46,8 +43,10 @@ from src.models import ( # noqa: F401
|
||||
task,
|
||||
translate,
|
||||
)
|
||||
|
||||
# Import config models with explicit alias to avoid name collision with alembic config
|
||||
import src.models.config as models_config # noqa: F401
|
||||
from src.models.mapping import Base
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
@@ -5,17 +5,18 @@ Revises: c4a3a2f74bfe
|
||||
Create Date: 2026-05-14 18:00:00.000000
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
from collections.abc import Sequence
|
||||
from datetime import UTC
|
||||
|
||||
from sqlalchemy.sql import text
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.sql import text
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = '543d43d752b8'
|
||||
down_revision: Union[str, Sequence[str], None] = 'c4a3a2f74bfe'
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
down_revision: str | Sequence[str] | None = 'c4a3a2f74bfe'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
@@ -82,8 +83,8 @@ def upgrade() -> None:
|
||||
""")
|
||||
).fetchall()
|
||||
|
||||
from datetime import datetime
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
for row in missing:
|
||||
record_id = row[0]
|
||||
@@ -129,7 +130,7 @@ def upgrade() -> None:
|
||||
# Determine final value (prefer user_edit over llm_translation)
|
||||
final_value = resolved_edit if resolved_edit else resolved_value
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
now = datetime.now(UTC)
|
||||
lang_id = str(uuid.uuid4())
|
||||
|
||||
connection.execute(
|
||||
|
||||
@@ -5,17 +5,17 @@ Revises: b0c1d2e3f4a5
|
||||
Create Date: 2026-05-26 15:27:06.159151
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
from collections.abc import Sequence
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = '86c7b1d6a710'
|
||||
down_revision: Union[str, Sequence[str], None] = 'b0c1d2e3f4a5'
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
down_revision: str | Sequence[str] | None = 'b0c1d2e3f4a5'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
|
||||
@@ -5,17 +5,17 @@ Revises: 543d43d752b8
|
||||
Create Date: 2026-05-14 23:43:32.216941
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
from collections.abc import Sequence
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import sqlite
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = '8dd0a93af539'
|
||||
down_revision: Union[str, Sequence[str], None] = '543d43d752b8'
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
down_revision: str | Sequence[str] | None = '543d43d752b8'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
|
||||
@@ -6,17 +6,17 @@ Create Date: 2026-05-20 14:30:00.000000
|
||||
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
from collections.abc import Sequence
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "9f8e7d6c5b4a"
|
||||
down_revision: Union[str, Sequence[str], None] = "b1c2d3e4f5a6"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
down_revision: str | Sequence[str] | None = "b1c2d3e4f5a6"
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def _is_multimodal_heuristic(model_name: str) -> bool:
|
||||
|
||||
@@ -5,16 +5,15 @@ Revises: c4a3a2f74bfe
|
||||
Create Date: 2026-05-21 18:55:00.000000
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
from collections.abc import Sequence
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = 'a5b6c7d8e9f0'
|
||||
down_revision: Union[str, Sequence[str], None] = 'c4a3a2f74bfe'
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
down_revision: str | Sequence[str] | None = 'c4a3a2f74bfe'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
|
||||
@@ -6,17 +6,17 @@ Create Date: 2026-05-21 10:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
from collections.abc import Sequence
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "a7b1c2d3e4f5"
|
||||
down_revision: Union[str, Sequence[str], None] = "9f8e7d6c5b4a"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
down_revision: str | Sequence[str] | None = "9f8e7d6c5b4a"
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
|
||||
@@ -5,16 +5,15 @@ Revises: f0e9d8c7b6a5
|
||||
Create Date: 2026-05-21 19:05:00.000000
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
from collections.abc import Sequence
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = 'b0c1d2e3f4a5'
|
||||
down_revision: Union[str, Sequence[str], None] = 'f0e9d8c7b6a5'
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
down_revision: str | Sequence[str] | None = 'f0e9d8c7b6a5'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
# Each entry: (table, constraint_name, column, ref_table, ondelete_rule)
|
||||
FK_FIXES = [
|
||||
|
||||
@@ -4,14 +4,16 @@ Revision ID: c4a3a2f74bfe
|
||||
Revises: ed310b33f02c
|
||||
Create Date: 2026-05-14 17:30:36.865269
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
from alembic import op
|
||||
from collections.abc import Sequence
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision: str = 'c4a3a2f74bfe'
|
||||
down_revision: Union[str, Sequence[str], None] = 'ed310b33f02c'
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
down_revision: str | Sequence[str] | None = 'ed310b33f02c'
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
|
||||
@@ -6,17 +6,17 @@ Create Date: 2026-05-21 12:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
from collections.abc import Sequence
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "e5f4d3c2b1a"
|
||||
down_revision: Union[str, Sequence[str], None] = "a7b1c2d3e4f5"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
down_revision: str | Sequence[str] | None = "a7b1c2d3e4f5"
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
|
||||
@@ -5,17 +5,17 @@ Revises:
|
||||
Create Date: 2026-05-14 15:35:03.167031
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
from collections.abc import Sequence
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = 'ed310b33f02c'
|
||||
down_revision: Union[str, Sequence[str], None] = None
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
down_revision: str | Sequence[str] | None = None
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
|
||||
@@ -5,16 +5,15 @@ Revises: a5b6c7d8e9f0, e5f4d3c2b1a
|
||||
Create Date: 2026-05-21 19:00:00.000000
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
from collections.abc import Sequence
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = 'f0e9d8c7b6a5'
|
||||
down_revision: Union[str, Sequence[str], None] = ('a5b6c7d8e9f0', 'e5f4d3c2b1a')
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
down_revision: str | Sequence[str] | None = ('a5b6c7d8e9f0', 'e5f4d3c2b1a')
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
FK_DEFS = [
|
||||
('resource_mappings', 'resource_mappings_environment_id_fkey', 'environment_id'),
|
||||
|
||||
@@ -16,4 +16,4 @@ include = ["src*"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
pythonpath = ["."]
|
||||
importmode = "importlib"
|
||||
asyncio_mode = "auto"
|
||||
|
||||
@@ -173,4 +173,4 @@ async def auth_callback_adfs(
|
||||
|
||||
|
||||
# #endregion auth_callback_adfs
|
||||
# #endregion AuthApi
|
||||
# #endregion AuthApi
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
# Set required env vars before any app imports
|
||||
import os
|
||||
|
||||
os.environ.setdefault("SECRET_KEY", "test-secret-key-for-testing")
|
||||
os.environ.setdefault("AUTH_DATABASE_URL", "sqlite:///:memory:test_auth")
|
||||
os.environ.setdefault("DEV_MODE", "true")
|
||||
|
||||
@@ -6,7 +6,7 @@ os.environ["ENCRYPTION_KEY"] = "OnrCzomBWbIjTf7Y-fnhL2adlU55bHZQjp8zX5zBC5w="
|
||||
# @RELATION DEPENDS_ON -> [AssistantApi]
|
||||
# @INVARIANT Every test clears assistant in-memory state before execution.
|
||||
import asyncio
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
from unittest.mock import MagicMock
|
||||
import uuid
|
||||
|
||||
@@ -54,8 +54,8 @@ class _FakeTask:
|
||||
self.params = params or {}
|
||||
self.result = result or {}
|
||||
self.user_id = user_id
|
||||
self.started_at = datetime.utcnow()
|
||||
self.finished_at = datetime.utcnow()
|
||||
self.started_at = datetime.now(UTC)
|
||||
self.finished_at = datetime.now(UTC)
|
||||
# #endregion _FakeTask
|
||||
# @DEBT: Divergent _FakeTaskManager definition. Canonical version should be in conftest.py. Authz variant is missing get_all_tasks().
|
||||
# #region _FakeTaskManager [TYPE Class] [C:2]
|
||||
@@ -206,9 +206,9 @@ def _dataset_review_session():
|
||||
recommended_action=RecommendedAction.APPROVE_MAPPING,
|
||||
status=SessionStatus.ACTIVE,
|
||||
current_phase=SessionPhase.MAPPING_REVIEW,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
last_activity_at=datetime.utcnow(),
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
last_activity_at=datetime.now(UTC),
|
||||
)
|
||||
session.findings = []
|
||||
session.previews = []
|
||||
@@ -226,8 +226,8 @@ def _dataset_review_session():
|
||||
requires_confirmation=False,
|
||||
recovery_status="recovered",
|
||||
notes=None,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
)
|
||||
]
|
||||
session.execution_mappings = [
|
||||
@@ -245,8 +245,8 @@ def _dataset_review_session():
|
||||
approval_state=ApprovalState.PENDING,
|
||||
approved_by_user_id=None,
|
||||
approved_at=None,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
)
|
||||
]
|
||||
session.semantic_fields = []
|
||||
|
||||
@@ -7,7 +7,7 @@ os.environ["ENCRYPTION_KEY"] = "OnrCzomBWbIjTf7Y-fnhL2adlU55bHZQjp8zX5zBC5w="
|
||||
# @RELATION DEPENDS_ON -> AssistantApi
|
||||
# @INVARIANT Security-sensitive flows fail closed for unauthorized actors.
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import os
|
||||
import pytest
|
||||
from types import SimpleNamespace
|
||||
@@ -249,7 +249,7 @@ def test_expired_confirmation_cannot_be_confirmed():
|
||||
)
|
||||
)
|
||||
assistant_module.CONFIRMATIONS[create.confirmation_id].expires_at = (
|
||||
datetime.utcnow() - timedelta(minutes=1)
|
||||
datetime.now(UTC) - timedelta(minutes=1)
|
||||
)
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
_run_async(
|
||||
|
||||
@@ -56,7 +56,7 @@ def _make_task(
|
||||
# @RELATION BINDS_TO -> TestReportsApi
|
||||
# @BRIEF Validate reports list endpoint default pagination and contract keys for mixed task statuses.
|
||||
def test_get_reports_default_pagination_contract():
|
||||
now = datetime.utcnow()
|
||||
now = datetime.now(UTC)
|
||||
tasks = [
|
||||
_make_task(
|
||||
"t-1",
|
||||
@@ -103,7 +103,7 @@ def test_get_reports_default_pagination_contract():
|
||||
# @RELATION BINDS_TO -> TestReportsApi
|
||||
# @BRIEF Validate reports list endpoint applies task-type/status filters and pagination boundaries.
|
||||
def test_get_reports_filter_and_pagination():
|
||||
now = datetime.utcnow()
|
||||
now = datetime.now(UTC)
|
||||
tasks = [
|
||||
_make_task(
|
||||
"t-1",
|
||||
@@ -150,7 +150,7 @@ def test_get_reports_filter_and_pagination():
|
||||
# @RELATION BINDS_TO -> TestReportsApi
|
||||
# @BRIEF Validate reports sorting remains stable when task timestamps mix naive and timezone-aware datetimes.
|
||||
def test_get_reports_handles_mixed_naive_and_aware_datetimes():
|
||||
naive_now = datetime.utcnow()
|
||||
naive_now = datetime.now(UTC)
|
||||
aware_now = datetime.now(UTC)
|
||||
tasks = [
|
||||
_make_task(
|
||||
@@ -184,7 +184,7 @@ def test_get_reports_handles_mixed_naive_and_aware_datetimes():
|
||||
# @RELATION BINDS_TO -> TestReportsApi
|
||||
# @BRIEF Validate reports list endpoint rejects unsupported task type filters with HTTP 400.
|
||||
def test_get_reports_invalid_filter_returns_400():
|
||||
now = datetime.utcnow()
|
||||
now = datetime.now(UTC)
|
||||
tasks = [
|
||||
_make_task(
|
||||
"t-1",
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
# @BRIEF Contract tests for GET /api/reports/{report_id} detail endpoint behavior.
|
||||
# @LAYER Domain
|
||||
# @INVARIANT Detail endpoint tests must keep deterministic assertions for success and not-found contracts.
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from types import SimpleNamespace
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
@@ -35,7 +35,7 @@ def _admin_user():
|
||||
# @RELATION BINDS_TO -> TestReportsDetailApi
|
||||
# @BRIEF Build deterministic Task payload for reports detail endpoint contract assertions.
|
||||
def _make_task(task_id: str, plugin_id: str, status: TaskStatus, result=None):
|
||||
now = datetime.utcnow()
|
||||
now = datetime.now(UTC)
|
||||
return Task(
|
||||
id=task_id,
|
||||
plugin_id=plugin_id,
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
# @BRIEF Validate implemented reports payload shape against OpenAPI-required top-level contract fields.
|
||||
# @LAYER Domain
|
||||
# @INVARIANT List and detail payloads include required contract keys.
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
@@ -34,7 +34,7 @@ def _admin_user():
|
||||
# @RELATION BINDS_TO -> TestReportsOpenapiConformance
|
||||
# @BRIEF Construct deterministic task fixture consumed by reports list/detail payload assertions.
|
||||
def _task(task_id: str, plugin_id: str, status: TaskStatus):
|
||||
now = datetime.utcnow()
|
||||
now = datetime.now(UTC)
|
||||
return Task(
|
||||
id=task_id,
|
||||
plugin_id=plugin_id,
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from fastapi import Depends, HTTPException, Query
|
||||
@@ -69,7 +69,7 @@ async def list_conversations(
|
||||
conv_id = row.conversation_id
|
||||
if not conv_id:
|
||||
continue
|
||||
created_at = row.created_at or datetime.utcnow()
|
||||
created_at = row.created_at or datetime.now(UTC)
|
||||
if conv_id not in summary:
|
||||
summary[conv_id] = {
|
||||
"conversation_id": conv_id,
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
@@ -138,13 +138,13 @@ async def _dispatch_dataset_review_intent(
|
||||
continue
|
||||
mapping.approval_state = ApprovalState.APPROVED
|
||||
mapping.approved_by_user_id = current_user.id
|
||||
mapping.approved_at = datetime.utcnow()
|
||||
mapping.approved_at = datetime.now(UTC)
|
||||
updated_count += 1
|
||||
if updated_count == 0:
|
||||
raise HTTPException(
|
||||
status_code=409, detail="No matching mappings available to approve"
|
||||
)
|
||||
session.last_activity_at = datetime.utcnow()
|
||||
session.last_activity_at = datetime.now(UTC)
|
||||
if session.readiness_state == ReadinessState.MAPPING_REVIEW_NEEDED:
|
||||
session.recommended_action = RecommendedAction.GENERATE_SQL_PREVIEW
|
||||
repository.bump_session_version(session)
|
||||
@@ -206,7 +206,7 @@ async def _dispatch_dataset_review_intent(
|
||||
raise
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
session.last_activity_at = datetime.utcnow()
|
||||
session.last_activity_at = datetime.now(UTC)
|
||||
repository.bump_session_version(session)
|
||||
repository.db.commit()
|
||||
repository.db.refresh(session)
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
import uuid
|
||||
|
||||
@@ -59,7 +59,7 @@ def _append_history(
|
||||
"state": state,
|
||||
"task_id": task_id,
|
||||
"confirmation_id": confirmation_id,
|
||||
"created_at": datetime.utcnow(),
|
||||
"created_at": datetime.now(UTC),
|
||||
}
|
||||
)
|
||||
|
||||
@@ -120,7 +120,7 @@ def _audit(user_id: str, payload: dict[str, Any]):
|
||||
if user_id not in ASSISTANT_AUDIT:
|
||||
ASSISTANT_AUDIT[user_id] = []
|
||||
ASSISTANT_AUDIT[user_id].append(
|
||||
{**payload, "created_at": datetime.utcnow().isoformat()}
|
||||
{**payload, "created_at": datetime.now(UTC).isoformat()}
|
||||
)
|
||||
logger.info(f"[assistant.audit] {payload}")
|
||||
|
||||
@@ -197,7 +197,7 @@ def _update_confirmation_state(db: Session, confirmation_id: str, state: str):
|
||||
return
|
||||
row.state = state
|
||||
if state in {"consumed", "expired", "cancelled"}:
|
||||
row.consumed_at = datetime.utcnow()
|
||||
row.consumed_at = datetime.now(UTC)
|
||||
db.commit()
|
||||
except Exception as exc:
|
||||
db.rollback()
|
||||
@@ -301,7 +301,7 @@ def _resolve_or_create_conversation(
|
||||
# @PRE db session is available and user_id references current actor scope.
|
||||
# @POST Messages older than ASSISTANT_MESSAGE_TTL_DAYS are removed from persistence and memory mirrors.
|
||||
def _cleanup_history_ttl(db: Session, user_id: str):
|
||||
cutoff = datetime.utcnow() - timedelta(days=ASSISTANT_MESSAGE_TTL_DAYS)
|
||||
cutoff = datetime.now(UTC) - timedelta(days=ASSISTANT_MESSAGE_TTL_DAYS)
|
||||
try:
|
||||
query = db.query(AssistantMessageRecord).filter(
|
||||
AssistantMessageRecord.user_id == user_id,
|
||||
@@ -344,7 +344,7 @@ def _cleanup_history_ttl(db: Session, user_id: str):
|
||||
def _is_conversation_archived(updated_at: datetime | None) -> bool:
|
||||
if not updated_at:
|
||||
return False
|
||||
cutoff = datetime.utcnow() - timedelta(days=ASSISTANT_ARCHIVE_AFTER_DAYS)
|
||||
cutoff = datetime.now(UTC) - timedelta(days=ASSISTANT_ARCHIVE_AFTER_DAYS)
|
||||
return updated_at < cutoff
|
||||
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
@@ -106,13 +106,13 @@ async def send_message(request: AssistantMessageRequest, current_user: User=Depe
|
||||
_audit(user_id, audit_payload)
|
||||
_persist_audit(db, user_id, audit_payload, conversation_id)
|
||||
logger.reflect('Belief protocol postcondition checkpoint for send_message')
|
||||
return AssistantMessageResponse(conversation_id=conversation_id, response_id=str(uuid.uuid4()), state='needs_clarification', text=text, intent=intent, actions=[AssistantAction(type='rephrase', label='Rephrase command')], created_at=datetime.utcnow())
|
||||
return AssistantMessageResponse(conversation_id=conversation_id, response_id=str(uuid.uuid4()), state='needs_clarification', text=text, intent=intent, actions=[AssistantAction(type='rephrase', label='Rephrase command')], created_at=datetime.now(UTC))
|
||||
try:
|
||||
_authorize_intent(intent, current_user)
|
||||
operation = intent.get('operation')
|
||||
if operation not in _SAFE_OPS:
|
||||
confirmation_id = str(uuid.uuid4())
|
||||
confirm = ConfirmationRecord(id=confirmation_id, user_id=user_id, conversation_id=conversation_id, intent=intent, dispatch={'intent': intent}, expires_at=datetime.utcnow() + __import__('datetime').timedelta(minutes=5), created_at=datetime.utcnow())
|
||||
confirm = ConfirmationRecord(id=confirmation_id, user_id=user_id, conversation_id=conversation_id, intent=intent, dispatch={'intent': intent}, expires_at=datetime.now(UTC) + __import__('datetime').timedelta(minutes=5), created_at=datetime.now(UTC))
|
||||
CONFIRMATIONS[confirmation_id] = confirm
|
||||
_persist_confirmation(db, confirm)
|
||||
text = await _async_confirmation_summary(intent, config_manager, db)
|
||||
@@ -122,7 +122,7 @@ async def send_message(request: AssistantMessageRequest, current_user: User=Depe
|
||||
_audit(user_id, audit_payload)
|
||||
_persist_audit(db, user_id, audit_payload, conversation_id)
|
||||
logger.reflect('Belief protocol postcondition checkpoint for send_message')
|
||||
return AssistantMessageResponse(conversation_id=conversation_id, response_id=str(uuid.uuid4()), state='needs_confirmation', text=text, intent=intent, confirmation_id=confirmation_id, actions=[AssistantAction(type='confirm', label='✅ Подтвердить', target=confirmation_id), AssistantAction(type='cancel', label='❌ Отменить', target=confirmation_id)], created_at=datetime.utcnow())
|
||||
return AssistantMessageResponse(conversation_id=conversation_id, response_id=str(uuid.uuid4()), state='needs_confirmation', text=text, intent=intent, confirmation_id=confirmation_id, actions=[AssistantAction(type='confirm', label='✅ Подтвердить', target=confirmation_id), AssistantAction(type='cancel', label='❌ Отменить', target=confirmation_id)], created_at=datetime.now(UTC))
|
||||
text, task_id, actions = await _dispatch_intent(intent, current_user, task_manager, config_manager, db)
|
||||
state = 'started' if task_id else 'success'
|
||||
_append_history(user_id, conversation_id, 'assistant', text, state=state, task_id=task_id)
|
||||
@@ -131,7 +131,7 @@ async def send_message(request: AssistantMessageRequest, current_user: User=Depe
|
||||
_audit(user_id, audit_payload)
|
||||
_persist_audit(db, user_id, audit_payload, conversation_id)
|
||||
logger.reflect('Belief protocol postcondition checkpoint for send_message')
|
||||
return AssistantMessageResponse(conversation_id=conversation_id, response_id=str(uuid.uuid4()), state=state, text=text, intent=intent, task_id=task_id, actions=actions, created_at=datetime.utcnow())
|
||||
return AssistantMessageResponse(conversation_id=conversation_id, response_id=str(uuid.uuid4()), state=state, text=text, intent=intent, task_id=task_id, actions=actions, created_at=datetime.now(UTC))
|
||||
except HTTPException as exc:
|
||||
detail_text = str(exc.detail)
|
||||
is_clarification_error = exc.status_code in (400, 422) and (detail_text.lower().startswith('missing') or 'укажите' in detail_text.lower() or 'выберите' in detail_text.lower())
|
||||
@@ -148,7 +148,7 @@ async def send_message(request: AssistantMessageRequest, current_user: User=Depe
|
||||
_audit(user_id, audit_payload)
|
||||
_persist_audit(db, user_id, audit_payload, conversation_id)
|
||||
logger.reflect('Belief protocol postcondition checkpoint for send_message')
|
||||
return AssistantMessageResponse(conversation_id=conversation_id, response_id=str(uuid.uuid4()), state=state, text=text, intent=intent, actions=[AssistantAction(type='rephrase', label='Rephrase command')] if state == 'needs_clarification' else [], created_at=datetime.utcnow())
|
||||
return AssistantMessageResponse(conversation_id=conversation_id, response_id=str(uuid.uuid4()), state=state, text=text, intent=intent, actions=[AssistantAction(type='rephrase', label='Rephrase command')] if state == 'needs_clarification' else [], created_at=datetime.now(UTC))
|
||||
|
||||
|
||||
# #endregion send_message
|
||||
@@ -187,7 +187,7 @@ async def confirm_operation(
|
||||
status_code=400, detail=f"Confirmation already {record.state}"
|
||||
)
|
||||
|
||||
if datetime.utcnow() > record.expires_at:
|
||||
if datetime.now(UTC) > record.expires_at:
|
||||
record.state = "expired"
|
||||
_update_confirmation_state(db, confirmation_id, "expired")
|
||||
raise HTTPException(status_code=400, detail="Confirmation expired")
|
||||
@@ -234,10 +234,11 @@ async def confirm_operation(
|
||||
intent=intent,
|
||||
task_id=task_id,
|
||||
actions=actions,
|
||||
created_at=datetime.utcnow(),
|
||||
created_at=datetime.now(UTC),
|
||||
)
|
||||
|
||||
|
||||
|
||||
# #endregion confirm_operation
|
||||
|
||||
|
||||
@@ -309,10 +310,11 @@ async def cancel_operation(
|
||||
intent=record.intent,
|
||||
confirmation_id=confirmation_id,
|
||||
actions=[],
|
||||
created_at=datetime.utcnow(),
|
||||
created_at=datetime.now(UTC),
|
||||
)
|
||||
|
||||
|
||||
|
||||
# #endregion cancel_operation
|
||||
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
# #region GitStatus [C:1] [TYPE DataClass]
|
||||
@@ -96,6 +96,7 @@ class DashboardChartItem(BaseModel):
|
||||
# #region DashboardDatasetItem [C:1] [TYPE DataClass]
|
||||
# @BRIEF DTO for a dataset associated with a dashboard.
|
||||
class DashboardDatasetItem(BaseModel):
|
||||
model_config = ConfigDict(protected_namespaces=())
|
||||
id: int
|
||||
table_name: str
|
||||
schema: str | None = None
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from fastapi import Depends, Header, HTTPException, status
|
||||
@@ -524,7 +524,7 @@ def _serialize_clarification_question_payload(payload):
|
||||
"topic_ref": payload.topic_ref, "question_text": payload.question_text,
|
||||
"why_it_matters": payload.why_it_matters, "current_guess": payload.current_guess,
|
||||
"priority": payload.priority, "state": payload.state, "options": payload.options,
|
||||
"answer": None, "created_at": datetime.utcnow(), "updated_at": datetime.utcnow(),
|
||||
"answer": None, "created_at": datetime.now(UTC), "updated_at": datetime.now(UTC),
|
||||
})
|
||||
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any, Union, cast
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
@@ -746,8 +746,8 @@ async def update_execution_mapping(
|
||||
mapping.transformation_note = request.transformation_note
|
||||
mapping.approval_state = ApprovalState.APPROVED
|
||||
mapping.approved_by_user_id = current_user.id
|
||||
mapping.approved_at = datetime.utcnow()
|
||||
session.last_activity_at = datetime.utcnow()
|
||||
mapping.approved_at = datetime.now(UTC)
|
||||
session.last_activity_at = datetime.now(UTC)
|
||||
session.recommended_action = RecommendedAction.GENERATE_SQL_PREVIEW
|
||||
if session.readiness_state in {
|
||||
ReadinessState.MAPPING_REVIEW_NEEDED,
|
||||
@@ -801,10 +801,10 @@ async def approve_execution_mapping(
|
||||
mapping = _get_owned_mapping_or_404(session, mapping_id)
|
||||
mapping.approval_state = ApprovalState.APPROVED
|
||||
mapping.approved_by_user_id = current_user.id
|
||||
mapping.approved_at = datetime.utcnow()
|
||||
mapping.approved_at = datetime.now(UTC)
|
||||
if request.approval_note:
|
||||
mapping.transformation_note = request.approval_note
|
||||
session.last_activity_at = datetime.utcnow()
|
||||
session.last_activity_at = datetime.now(UTC)
|
||||
if session.readiness_state == ReadinessState.MAPPING_REVIEW_NEEDED:
|
||||
session.recommended_action = RecommendedAction.GENERATE_SQL_PREVIEW
|
||||
sr = cast(Any, session)
|
||||
@@ -850,11 +850,11 @@ async def approve_batch_execution_mappings(
|
||||
mapping = _get_owned_mapping_or_404(session, mid)
|
||||
mapping.approval_state = ApprovalState.APPROVED
|
||||
mapping.approved_by_user_id = current_user.id
|
||||
mapping.approved_at = datetime.utcnow()
|
||||
mapping.approved_at = datetime.now(UTC)
|
||||
if request.approval_note:
|
||||
mapping.transformation_note = request.approval_note
|
||||
updated.append(mapping)
|
||||
session.last_activity_at = datetime.utcnow()
|
||||
session.last_activity_at = datetime.now(UTC)
|
||||
if session.readiness_state == ReadinessState.MAPPING_REVIEW_NEEDED:
|
||||
session.recommended_action = RecommendedAction.GENERATE_SQL_PREVIEW
|
||||
sr = cast(Any, session)
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
import re
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from ...core.logger import belief_scope, logger
|
||||
from ...core.superset_client import SupersetClient
|
||||
@@ -49,8 +49,7 @@ class DatasetItem(BaseModel):
|
||||
last_task: LastTask | None = None
|
||||
metric_count: int = 0
|
||||
|
||||
class Config:
|
||||
allow_population_by_field_name = True
|
||||
model_config = ConfigDict(validate_by_name=True)
|
||||
# #endregion DatasetItem
|
||||
|
||||
# #region LinkedDashboard [C:1] [TYPE DataClass]
|
||||
@@ -104,8 +103,7 @@ class DatasetDetailResponse(BaseModel):
|
||||
created_on: str | None = None
|
||||
changed_on: str | None = None
|
||||
|
||||
class Config:
|
||||
allow_population_by_field_name = True
|
||||
model_config = ConfigDict(validate_by_name=True)
|
||||
# #endregion DatasetDetailResponse
|
||||
|
||||
# #region StatsCounts [C:1] [TYPE DataClass]
|
||||
@@ -498,7 +496,7 @@ def _strip_html_tags(text: str) -> str:
|
||||
return text
|
||||
if re.search(r"<[^>]*>", text):
|
||||
cleaned = re.sub(r"<[^>]*>", "", text)
|
||||
logger.warning(f"[_strip_html_tags] HTML tags detected and stripped from description")
|
||||
logger.warning("[_strip_html_tags] HTML tags detected and stripped from description")
|
||||
return cleaned
|
||||
return text
|
||||
# #endregion _strip_html_tags
|
||||
|
||||
@@ -97,7 +97,7 @@ async def resolve_merge_conflicts(
|
||||
)
|
||||
resolved_files = _gs.resolve_merge_conflicts(
|
||||
dashboard_id,
|
||||
[item.dict() for item in resolve_data.resolutions],
|
||||
[item.model_dump() for item in resolve_data.resolutions],
|
||||
)
|
||||
return {"status": "success", "resolved_files": resolved_files}
|
||||
except HTTPException:
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from src.models.git import GitProvider, GitStatus, SyncStatus
|
||||
|
||||
@@ -52,8 +52,7 @@ class GitServerConfigSchema(GitServerConfigBase):
|
||||
status: GitStatus
|
||||
last_validated: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
# #endregion GitServerConfigSchema
|
||||
|
||||
# #region GitRepositorySchema [TYPE Class]
|
||||
@@ -68,8 +67,7 @@ class GitRepositorySchema(BaseModel):
|
||||
current_branch: str
|
||||
sync_status: SyncStatus
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
# #endregion GitRepositorySchema
|
||||
|
||||
# #region BranchSchema [TYPE Class]
|
||||
@@ -171,8 +169,7 @@ class DeploymentEnvironmentSchema(BaseModel):
|
||||
superset_url: str
|
||||
is_active: bool
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
# #endregion DeploymentEnvironmentSchema
|
||||
|
||||
# #region DeployRequest [TYPE Class]
|
||||
|
||||
@@ -8,10 +8,10 @@
|
||||
# @INVARIANT All mutation endpoints return 202 {task_id} per spec.
|
||||
# @INVARIANT RBAC enforced per FR-015 matrix via has_permission() dependency.
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any, cast
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
||||
from fastapi import Depends, HTTPException, Request, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ....core.logger import belief_scope, logger as app_logger
|
||||
@@ -48,7 +48,6 @@ from ._schemas import (
|
||||
MaintenanceStartResponse,
|
||||
)
|
||||
|
||||
|
||||
# ── GET /api/maintenance/dashboard-banners ───────────────────
|
||||
# FR-015: viewer, operator, admin all have READ access
|
||||
|
||||
@@ -127,7 +126,7 @@ async def list_events(
|
||||
):
|
||||
with belief_scope("list_events"):
|
||||
# ── Auto-expiry: end events past their end_time ──
|
||||
now = datetime.now(timezone.utc)
|
||||
now = datetime.now(UTC)
|
||||
expired = (
|
||||
db.query(MaintenanceEvent)
|
||||
.filter(
|
||||
@@ -253,11 +252,11 @@ async def start_maintenance(
|
||||
)
|
||||
|
||||
# Validate times are within reasonable range (future ±1h grace period)
|
||||
now = datetime.now(timezone.utc)
|
||||
now = datetime.now(UTC)
|
||||
grace_threshold = 3600 # 1 hour in seconds
|
||||
if request.start_time:
|
||||
diff = (request.start_time - now).total_seconds() if request.start_time.tzinfo else \
|
||||
(request.start_time.replace(tzinfo=timezone.utc) - now).total_seconds()
|
||||
(request.start_time.replace(tzinfo=UTC) - now).total_seconds()
|
||||
if diff < -grace_threshold:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
@@ -281,7 +280,6 @@ async def start_maintenance(
|
||||
pass
|
||||
|
||||
# ── Idempotency check ──
|
||||
from ....services.maintenance import build_idempotency_key
|
||||
|
||||
sorted_tables = sorted(t.strip().lower() for t in request.tables if t.strip())
|
||||
idem_tables = frozenset(sorted_tables)
|
||||
|
||||
@@ -8,7 +8,6 @@ from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
# ── Request Schemas ──────────────────────────────────────────
|
||||
|
||||
# #region MaintenanceStartRequest [C:1] [TYPE Class]
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ...core.database import get_db
|
||||
@@ -42,8 +42,7 @@ class MappingResponse(BaseModel):
|
||||
target_db_name: str
|
||||
engine: str | None = None
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
# #endregion MappingResponse
|
||||
|
||||
# #region SuggestRequest [TYPE DataClass]
|
||||
@@ -98,7 +97,7 @@ async def create_mapping(
|
||||
db.refresh(existing)
|
||||
return existing
|
||||
|
||||
new_mapping = DatabaseMapping(**mapping.dict())
|
||||
new_mapping = DatabaseMapping(**mapping.model_dump())
|
||||
db.add(new_mapping)
|
||||
db.commit()
|
||||
db.refresh(new_mapping)
|
||||
|
||||
@@ -112,7 +112,7 @@ async def execute_migration(
|
||||
)
|
||||
|
||||
# Include replace_db_config and fix_cross_filters in the task parameters
|
||||
task_params = selection.dict()
|
||||
task_params = selection.model_dump()
|
||||
task_params["replace_db_config"] = selection.replace_db_config
|
||||
task_params["fix_cross_filters"] = selection.fix_cross_filters
|
||||
|
||||
|
||||
@@ -456,12 +456,12 @@ async def get_consolidated_settings(
|
||||
normalized_llm = normalize_llm_settings(config.settings.llm)
|
||||
|
||||
response_payload = ConsolidatedSettingsResponse(
|
||||
environments=[env.dict() for env in config.environments],
|
||||
environments=[env.model_dump() for env in config.environments],
|
||||
connections=config.settings.connections,
|
||||
llm=normalized_llm,
|
||||
llm_providers=llm_providers_list,
|
||||
logging=config.settings.logging.dict(),
|
||||
storage=config.settings.storage.dict(),
|
||||
logging=config.settings.logging.model_dump(),
|
||||
storage=config.settings.storage.model_dump(),
|
||||
notifications=notifications_payload,
|
||||
features=config.settings.features.model_dump(),
|
||||
app_timezone=config.settings.app_timezone,
|
||||
@@ -531,7 +531,7 @@ async def update_consolidated_settings(
|
||||
# Update app_timezone if provided
|
||||
if "app_timezone" in settings_patch:
|
||||
new_tz = settings_patch["app_timezone"]
|
||||
from ...core.timezone import validate_timezone, invalidate_timezone_cache
|
||||
from ...core.timezone import invalidate_timezone_cache, validate_timezone
|
||||
if not validate_timezone(new_tz):
|
||||
raise HTTPException(status_code=422, detail=f"Invalid IANA timezone: {new_tz}")
|
||||
current_settings.app_timezone = new_tz
|
||||
@@ -566,7 +566,7 @@ async def create_validation_policy(
|
||||
_=Depends(has_permission("admin:settings", "WRITE")),
|
||||
):
|
||||
with belief_scope("create_validation_policy"):
|
||||
db_policy = ValidationPolicy(**policy.dict())
|
||||
db_policy = ValidationPolicy(**policy.model_dump())
|
||||
db.add(db_policy)
|
||||
db.commit()
|
||||
db.refresh(db_policy)
|
||||
|
||||
@@ -13,9 +13,9 @@ from ....dependencies import get_config_manager, get_current_user, has_permissio
|
||||
from ....plugins.translate.service import (
|
||||
TranslateJobService,
|
||||
get_datasource_columns as fetch_datasource_columns_service,
|
||||
job_to_response,
|
||||
)
|
||||
from ....plugins.translate.service_target_schema import validate_target_table_schema
|
||||
from ....plugins.translate.service_utils import job_to_response
|
||||
from ....schemas.auth import User
|
||||
from ....schemas.translate import (
|
||||
DatasourceColumnsResponse,
|
||||
|
||||
@@ -117,7 +117,6 @@ async def get_task(
|
||||
logger.reason(f"get_task — Task: {task_id}, User: {current_user.username}", extra={"src": "validation_routes"})
|
||||
try:
|
||||
task = task_service.get_task(task_id)
|
||||
from ...schemas.validation import ValidationRunResponse
|
||||
# Find recent runs for this specific task via task_id
|
||||
recent = run_service.list_runs(
|
||||
task_id=task_id,
|
||||
|
||||
@@ -23,33 +23,33 @@
|
||||
|
||||
# Set required env vars before ANY app imports — crash-early guard for AuthConfig()
|
||||
import os
|
||||
|
||||
os.environ.setdefault("SECRET_KEY", "test-secret-key-for-testing")
|
||||
os.environ.setdefault("AUTH_DATABASE_URL", "sqlite:///:memory:test_auth")
|
||||
os.environ.setdefault("DATABASE_URL", "sqlite:///:memory:test_main")
|
||||
os.environ.setdefault("DEV_MODE", "true")
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from datetime import UTC, datetime
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from src.api.routes.validation import _get_run_service, _get_task_service
|
||||
from src.app import app
|
||||
from src.dependencies import (
|
||||
get_current_user,
|
||||
get_config_manager,
|
||||
get_current_user,
|
||||
get_task_manager,
|
||||
)
|
||||
from src.api.routes.validation import _get_task_service, _get_run_service
|
||||
from src.models.auth import User
|
||||
from src.schemas.validation import (
|
||||
TriggerRunResponse,
|
||||
ValidationRunDetailResponse,
|
||||
ValidationRunListResponse,
|
||||
ValidationTaskListResponse,
|
||||
ValidationTaskResponse,
|
||||
ValidationRunListResponse,
|
||||
ValidationRunDetailResponse,
|
||||
TriggerRunResponse,
|
||||
)
|
||||
from src.models.auth import User
|
||||
|
||||
# ── Shared mocks ───────────────────────────────────────────────────────
|
||||
|
||||
@@ -64,7 +64,7 @@ mock_user.roles.append(admin_role)
|
||||
|
||||
def _make_now():
|
||||
"""Return a timezone-aware UTC datetime for Pydantic v2."""
|
||||
return datetime.now(timezone.utc)
|
||||
return datetime.now(UTC)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
|
||||
@@ -10,13 +10,15 @@
|
||||
# @DATA_CONTRACT [HTTP Request | WS Message] -> [HTTP Response | JSON Log Stream]
|
||||
# @RATIONALE Duplicate @RELATION and @INVARIANT lines removed from header. Import sorting unified via ruff isort (I) rule across src/ — 139 fixes applied.
|
||||
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
# project_root is used for static files mounting
|
||||
project_root = Path(__file__).resolve().parent.parent.parent
|
||||
import asyncio
|
||||
|
||||
from alembic.config import Config as AlembicConfig
|
||||
from fastapi import FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import FileResponse
|
||||
@@ -24,6 +26,8 @@ from fastapi.staticfiles import StaticFiles
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.middleware.sessions import SessionMiddleware
|
||||
|
||||
from alembic import command as alembic_command
|
||||
|
||||
from .api import auth
|
||||
from .api.routes import (
|
||||
admin,
|
||||
@@ -50,9 +54,6 @@ from .api.routes import (
|
||||
translate,
|
||||
validation,
|
||||
)
|
||||
from alembic.config import Config as AlembicConfig
|
||||
from alembic import command as alembic_command
|
||||
|
||||
from .core.auth.security import get_password_hash
|
||||
from .core.cot_logger import seed_trace_id
|
||||
from .core.database import AuthSessionLocal, init_db
|
||||
@@ -62,6 +63,28 @@ from .core.utils.network import NetworkError
|
||||
from .dependencies import get_scheduler_service, get_task_manager
|
||||
from .models.auth import Role, User
|
||||
|
||||
|
||||
# #region lifespan [C:3] [TYPE Function]
|
||||
# @BRIEF Async context manager for FastAPI startup/shutdown lifecycle.
|
||||
# @RELATION CALLS -> [run_alembic_migrations]
|
||||
# @RELATION CALLS -> [init_db]
|
||||
# @RELATION CALLS -> [AppDependencies]
|
||||
# @POST On startup: schema up-to-date, admin exists, scheduler started. On shutdown: scheduler stopped.
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
# Startup
|
||||
seed_trace_id()
|
||||
with belief_scope("startup_event"):
|
||||
ensure_encryption_key()
|
||||
run_alembic_migrations()
|
||||
init_db()
|
||||
ensure_initial_admin_user()
|
||||
scheduler = get_scheduler_service()
|
||||
scheduler.start()
|
||||
yield
|
||||
# Shutdown
|
||||
scheduler.stop()
|
||||
# #endregion lifespan
|
||||
# #region FastAPI_App [C:3] [TYPE Global] [SEMANTICS app, fastapi, instance, route-registry]
|
||||
# @BRIEF Canonical FastAPI application instance for route, middleware, and websocket registration.
|
||||
# @RELATION DEPENDS_ON -> [ApiRoutesModule]
|
||||
@@ -70,6 +93,7 @@ app = FastAPI(
|
||||
title="Superset Tools API",
|
||||
description="API for managing Superset automation tools and plugins.",
|
||||
version="1.0.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
# #endregion FastAPI_App
|
||||
# #region ensure_initial_admin_user [C:3] [TYPE Function]
|
||||
@@ -152,37 +176,7 @@ def run_alembic_migrations() -> None:
|
||||
# #endregion run_alembic_migrations
|
||||
|
||||
|
||||
# #region startup_event [C:3] [TYPE Function]
|
||||
# @BRIEF Handles application startup: Alembic → create_all → admin bootstrap → scheduler.
|
||||
# @RELATION CALLS -> [run_alembic_migrations]
|
||||
# @RELATION CALLS -> [init_db]
|
||||
# @POST Schema is up-to-date via Alembic, missing tables created, admin exists, scheduler started.
|
||||
@app.on_event("startup")
|
||||
async def startup_event():
|
||||
seed_trace_id()
|
||||
with belief_scope("startup_event"):
|
||||
ensure_encryption_key()
|
||||
# 1. Alembic — applies ALL pending migrations (add/drop/rename columns, data migrations)
|
||||
run_alembic_migrations()
|
||||
# 2. init_db — creates new tables via create_all() (does NOT alter existing ones)
|
||||
init_db()
|
||||
ensure_initial_admin_user()
|
||||
scheduler = get_scheduler_service()
|
||||
scheduler.start()
|
||||
# #endregion startup_event
|
||||
# #region shutdown_event [C:3] [TYPE Function]
|
||||
# @BRIEF Handles application shutdown tasks, such as stopping the scheduler.
|
||||
# @RELATION CALLS -> [AppDependencies]
|
||||
# @PRE None.
|
||||
# @POST Scheduler is stopped.
|
||||
# Shutdown event
|
||||
@app.on_event("shutdown")
|
||||
async def shutdown_event():
|
||||
seed_trace_id()
|
||||
with belief_scope("shutdown_event"):
|
||||
scheduler = get_scheduler_service()
|
||||
scheduler.stop()
|
||||
# #endregion shutdown_event
|
||||
|
||||
# #region app_middleware [TYPE Block]
|
||||
# @BRIEF Configure application-wide middleware (Session, CORS).
|
||||
# @RATIONALE SessionMiddleware uses SESSION_SECRET_KEY independent of JWT SECRET_KEY (see [SEC:H-4]).
|
||||
@@ -349,8 +343,8 @@ async def _authenticate_websocket(websocket: WebSocket, endpoint_name: str) -> b
|
||||
|
||||
# Try JWT first, fallback to API key
|
||||
try:
|
||||
from .core.auth.jwt import decode_token
|
||||
from .core.auth.api_key import hash_api_key
|
||||
from .core.auth.jwt import decode_token
|
||||
from .core.database import SessionLocal
|
||||
|
||||
# Attempt JWT validation
|
||||
@@ -479,7 +473,7 @@ async def websocket_endpoint(
|
||||
initial_sent = 0
|
||||
for log_entry in initial_logs:
|
||||
if matches_filters(log_entry):
|
||||
log_dict = log_entry.dict()
|
||||
log_dict = log_entry.model_dump()
|
||||
log_dict["timestamp"] = log_dict["timestamp"].isoformat()
|
||||
await websocket.send_json(log_dict)
|
||||
initial_sent += 1
|
||||
@@ -510,7 +504,7 @@ async def websocket_endpoint(
|
||||
log_entry = await queue.get()
|
||||
if not matches_filters(log_entry):
|
||||
continue
|
||||
log_dict = log_entry.dict()
|
||||
log_dict = log_entry.model_dump()
|
||||
log_dict["timestamp"] = log_dict["timestamp"].isoformat()
|
||||
await websocket.send_json(log_dict)
|
||||
logger.reflect(
|
||||
|
||||
@@ -12,12 +12,11 @@
|
||||
# @SIDE_EFFECT None
|
||||
# @DATA_CONTRACT TokenPayload -> JWT string
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import hashlib
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from jose import jwt
|
||||
from jose.exceptions import JWTError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ...models.auth import TokenBlacklist
|
||||
@@ -34,7 +33,7 @@ from .config import auth_config
|
||||
def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
|
||||
with belief_scope("create_access_token"):
|
||||
to_encode = data.copy()
|
||||
now = datetime.now(timezone.utc)
|
||||
now = datetime.now(UTC)
|
||||
if expires_delta:
|
||||
expire = now + expires_delta
|
||||
else:
|
||||
@@ -101,7 +100,7 @@ def _hash_token(token: str) -> str:
|
||||
# @PRE db is a valid SQLAlchemy session.
|
||||
# @POST Expired blacklist rows are removed.
|
||||
def _prune_blacklist(db: Session) -> None:
|
||||
now = datetime.now(timezone.utc)
|
||||
now = datetime.now(UTC)
|
||||
db.query(TokenBlacklist).filter(TokenBlacklist.expires_at < now).delete()
|
||||
db.commit()
|
||||
|
||||
@@ -131,7 +130,7 @@ def blacklist_token(token: str, db: Session) -> None:
|
||||
if isinstance(exp_raw, datetime):
|
||||
expires_at = exp_raw
|
||||
else:
|
||||
expires_at = datetime.fromtimestamp(exp_raw, tz=timezone.utc)
|
||||
expires_at = datetime.fromtimestamp(exp_raw, tz=UTC)
|
||||
|
||||
existing = db.query(TokenBlacklist).filter(TokenBlacklist.jti == jti).first()
|
||||
if existing:
|
||||
|
||||
@@ -12,9 +12,8 @@
|
||||
# @SIDE_EFFECT Writes auth audit log entries
|
||||
# @DATA_CONTRACT AuthEvent -> LogEntry
|
||||
|
||||
import copy
|
||||
from datetime import UTC, datetime
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from ..logger import belief_scope, logger
|
||||
@@ -52,7 +51,7 @@ def _mask_details(details: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
# dict are masked to prevent credential leakage — see [SEC:L-1].
|
||||
def log_security_event(event_type: str, username: str, details: dict = None):
|
||||
with belief_scope("log_security_event", f"{event_type}:{username}"):
|
||||
timestamp = datetime.utcnow().isoformat()
|
||||
timestamp = datetime.now(UTC).isoformat()
|
||||
logger.info(
|
||||
"[AUDIT][%s][%s] User: %s",
|
||||
timestamp,
|
||||
|
||||
@@ -124,7 +124,7 @@ class BeliefFormatter(logging.Formatter):
|
||||
# #region LogEntry [C:1] [TYPE Class] [SEMANTICS log,entry,record,pydantic]
|
||||
# @BRIEF A Pydantic model representing a single, structured log entry.
|
||||
class LogEntry(BaseModel):
|
||||
timestamp: datetime = Field(default_factory=datetime.utcnow)
|
||||
timestamp: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
||||
level: str
|
||||
message: str
|
||||
context: dict[str, Any] | None = None
|
||||
|
||||
@@ -7,9 +7,9 @@
|
||||
# Window resets after ATTEMPT_WINDOW seconds of no activity.
|
||||
# @REJECTED Redis-backed limiter — not available in all deployments.
|
||||
# Per-user limiting — user isn't known until after auth.
|
||||
import time
|
||||
import threading
|
||||
from collections import defaultdict
|
||||
import threading
|
||||
import time
|
||||
|
||||
# ── Configuration ──
|
||||
MAX_ATTEMPTS: int = 10 # Max failed attempts per window
|
||||
|
||||
@@ -172,8 +172,7 @@ def remove_banner_from_position(position_json: dict, chart_id: int) -> dict:
|
||||
del position_json[md_key]
|
||||
|
||||
# Remove ROW entry
|
||||
if row_key in position_json:
|
||||
del position_json[row_key]
|
||||
position_json.pop(row_key, None)
|
||||
|
||||
# Remove ROW from GRID_ID children
|
||||
grid = position_json.get("GRID_ID")
|
||||
|
||||
@@ -127,7 +127,7 @@ class JobLifecycle:
|
||||
f"Starting execution of task {task_id} for plugin '{plugin.name}'"
|
||||
)
|
||||
task.status = TaskStatus.RUNNING
|
||||
task.started_at = datetime.utcnow()
|
||||
task.started_at = datetime.now(UTC)
|
||||
self.persistence_service.persist_task(task)
|
||||
if add_log_callback:
|
||||
add_log_callback(
|
||||
@@ -181,7 +181,7 @@ class JobLifecycle:
|
||||
metadata={"error_type": type(e).__name__},
|
||||
)
|
||||
finally:
|
||||
task.finished_at = datetime.utcnow()
|
||||
task.finished_at = datetime.now(UTC)
|
||||
self.event_bus.flush_task_logs(task_id)
|
||||
self.persistence_service.persist_task(task)
|
||||
logger.info(
|
||||
|
||||
@@ -34,7 +34,6 @@
|
||||
|
||||
import asyncio
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import threading
|
||||
from typing import Any
|
||||
|
||||
from ..logger import belief_scope, logger
|
||||
|
||||
@@ -9,12 +9,12 @@
|
||||
# @POST Task models exported with immutable IDs
|
||||
# @SIDE_EFFECT Defines task data schema
|
||||
# @DATA_CONTRACT TaskInput -> TaskModel
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
from enum import Enum
|
||||
from typing import Any
|
||||
import uuid
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
# #region TaskStatus [TYPE Enum]
|
||||
@@ -41,7 +41,7 @@ class LogLevel(str, Enum):
|
||||
# optional_fields: {timestamp: datetime, level: str, source: str, context: dict, metadata: dict}
|
||||
# }
|
||||
class LogEntry(BaseModel):
|
||||
timestamp: datetime = Field(default_factory=datetime.utcnow)
|
||||
timestamp: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
||||
level: str = Field(default="INFO")
|
||||
message: str
|
||||
source: str = Field(
|
||||
@@ -65,8 +65,7 @@ class TaskLog(BaseModel):
|
||||
source: str
|
||||
message: str
|
||||
metadata: dict[str, Any] | None = None
|
||||
class Config:
|
||||
from_attributes = True
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
# #endregion TaskLog
|
||||
# #region LogFilter [TYPE Class]
|
||||
class LogFilter(BaseModel):
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
# @RELATION DEPENDS_ON -> [TaskGraph]
|
||||
# @RELATION DEPENDS_ON -> [TasksSessionLocal]
|
||||
# @INVARIANT Database schema must match the TaskRecord model structure.
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
import json
|
||||
import re
|
||||
|
||||
@@ -179,7 +179,7 @@ class TaskPersistenceService:
|
||||
# Store logs as JSON, converting datetime to string
|
||||
record.logs = []
|
||||
for log in task.logs:
|
||||
log_dict = log.dict()
|
||||
log_dict = log.model_dump()
|
||||
if isinstance(log_dict.get("timestamp"), datetime):
|
||||
log_dict["timestamp"] = log_dict["timestamp"].isoformat()
|
||||
# Also clean up any datetimes in context
|
||||
@@ -244,7 +244,7 @@ class TaskPersistenceService:
|
||||
log_data = dict(log_data)
|
||||
log_data["timestamp"] = (
|
||||
self._parse_datetime(log_data.get("timestamp"))
|
||||
or datetime.utcnow()
|
||||
or datetime.now(UTC)
|
||||
)
|
||||
logs.append(LogEntry(**log_data))
|
||||
started_at = self._parse_datetime(record.started_at)
|
||||
|
||||
@@ -235,4 +235,4 @@ class DatasetMapper:
|
||||
return
|
||||
# #endregion run_mapping
|
||||
# #endregion DatasetMapper
|
||||
# #endregion DatasetMapperModule
|
||||
# #endregion DatasetMapperModule
|
||||
|
||||
@@ -11,7 +11,7 @@ from __future__ import annotations
|
||||
|
||||
# #region SupersetCompilationAdapter.imports [TYPE Block]
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from src.core.config_models import Environment
|
||||
@@ -140,7 +140,7 @@ class SupersetCompilationAdapter:
|
||||
compiled_by="superset",
|
||||
error_code=None,
|
||||
error_details=None,
|
||||
compiled_at=datetime.utcnow(),
|
||||
compiled_at=datetime.now(UTC),
|
||||
)
|
||||
logger.reflect(
|
||||
"Superset-generated SQL preview captured successfully",
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
# @RELATION DEPENDS_ON -> [LogEntry]
|
||||
# @RELATION DEPENDS_ON -> [CotJsonFormatter]
|
||||
from collections import deque
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
@@ -12,7 +12,7 @@ from pydantic import BaseModel, Field
|
||||
|
||||
# #region LogEntry [C:1] [TYPE Class] [SEMANTICS log,entry,record,pydantic]
|
||||
class LogEntry(BaseModel):
|
||||
timestamp: datetime = Field(default_factory=datetime.utcnow)
|
||||
timestamp: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
||||
level: str
|
||||
message: str
|
||||
context: dict[str, Any] | None = None
|
||||
|
||||
@@ -13,12 +13,10 @@
|
||||
# @RELATION CALLS -> [get_api_key_principal]
|
||||
# @RELATION CALLS -> [info]
|
||||
|
||||
import json
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from datetime import UTC, datetime
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends, HTTPException, Request, status
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
@@ -214,7 +212,7 @@ def get_clean_release_facade(db=Depends(get_db)) -> CleanReleaseFacade:
|
||||
class APIKeyPrincipal:
|
||||
name: str
|
||||
api_key_id: str
|
||||
environment_id: Optional[str] = None
|
||||
environment_id: str | None = None
|
||||
permissions: list[str] = field(default_factory=list)
|
||||
# #endregion APIKeyPrincipal
|
||||
|
||||
@@ -337,8 +335,8 @@ def require_api_key_or_jwt(
|
||||
if api_key.expires_at:
|
||||
expires_at = api_key.expires_at
|
||||
if expires_at.tzinfo is None:
|
||||
expires_at = expires_at.replace(tzinfo=timezone.utc)
|
||||
if expires_at < datetime.now(timezone.utc):
|
||||
expires_at = expires_at.replace(tzinfo=UTC)
|
||||
if expires_at < datetime.now(UTC):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="API key has expired",
|
||||
@@ -361,7 +359,7 @@ def require_api_key_or_jwt(
|
||||
)
|
||||
|
||||
# Update last_used_at (best-effort, non-blocking)
|
||||
api_key.last_used_at = datetime.now(timezone.utc)
|
||||
api_key.last_used_at = datetime.now(UTC)
|
||||
db.flush()
|
||||
|
||||
logger.info(f"API key auth: {api_key.name} ({api_key.prefix}...)")
|
||||
@@ -425,7 +423,7 @@ async def check_api_key_environment_scope(request: Request, db, target_env_id: s
|
||||
async def get_api_key_principal(
|
||||
request: Request,
|
||||
db=Depends(get_db),
|
||||
) -> Optional[APIKeyPrincipal]:
|
||||
) -> APIKeyPrincipal | None:
|
||||
"""Extract and validate API key from X-API-Key header.
|
||||
|
||||
If no header is present, returns None (fall through to JWT auth).
|
||||
@@ -460,8 +458,8 @@ async def get_api_key_principal(
|
||||
if api_key.expires_at:
|
||||
expires_at = api_key.expires_at
|
||||
if expires_at.tzinfo is None:
|
||||
expires_at = expires_at.replace(tzinfo=timezone.utc)
|
||||
if expires_at < datetime.now(timezone.utc):
|
||||
expires_at = expires_at.replace(tzinfo=UTC)
|
||||
if expires_at < datetime.now(UTC):
|
||||
logger.warning(f"API key auth failed: key expired (id: {api_key.id}, name: {api_key.name})")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
@@ -469,7 +467,7 @@ async def get_api_key_principal(
|
||||
)
|
||||
|
||||
# Update last_used_at (non-blocking, best-effort)
|
||||
api_key.last_used_at = datetime.now(timezone.utc)
|
||||
api_key.last_used_at = datetime.now(UTC)
|
||||
db.flush()
|
||||
|
||||
logger.info(f"API key auth success: {api_key.name} ({api_key.prefix}...)")
|
||||
|
||||
@@ -6,7 +6,7 @@ from pathlib import Path
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import pytest
|
||||
|
||||
|
||||
@@ -116,12 +116,12 @@ class TestReportQuery:
|
||||
assert q.sort_order == order
|
||||
def test_time_range_validation_valid(self):
|
||||
from src.models.report import ReportQuery
|
||||
now = datetime.utcnow()
|
||||
now = datetime.now(UTC)
|
||||
q = ReportQuery(time_from=now - timedelta(days=1), time_to=now)
|
||||
assert q.time_from < q.time_to
|
||||
def test_time_range_validation_invalid(self):
|
||||
from src.models.report import ReportQuery
|
||||
now = datetime.utcnow()
|
||||
now = datetime.now(UTC)
|
||||
with pytest.raises(ValueError, match="time_from"):
|
||||
ReportQuery(time_from=now, time_to=now - timedelta(days=1))
|
||||
def test_page_ge_1(self):
|
||||
@@ -152,7 +152,7 @@ class TestReportCollection:
|
||||
from src.models.report import ReportCollection, ReportQuery, ReportStatus, TaskReport, TaskType
|
||||
report = TaskReport(
|
||||
report_id="r1", task_id="t1", task_type=TaskType.BACKUP,
|
||||
status=ReportStatus.SUCCESS, updated_at=datetime.utcnow(),
|
||||
status=ReportStatus.SUCCESS, updated_at=datetime.now(UTC),
|
||||
summary="OK"
|
||||
)
|
||||
col = ReportCollection(
|
||||
@@ -167,7 +167,7 @@ class TestReportDetailView:
|
||||
from src.models.report import ReportDetailView, ReportStatus, TaskReport, TaskType
|
||||
report = TaskReport(
|
||||
report_id="r1", task_id="t1", task_type=TaskType.BACKUP,
|
||||
status=ReportStatus.SUCCESS, updated_at=datetime.utcnow(),
|
||||
status=ReportStatus.SUCCESS, updated_at=datetime.now(UTC),
|
||||
summary="Backup OK"
|
||||
)
|
||||
detail = ReportDetailView(report=report)
|
||||
@@ -179,7 +179,7 @@ class TestReportDetailView:
|
||||
from src.models.report import ReportDetailView, ReportStatus, TaskReport, TaskType
|
||||
report = TaskReport(
|
||||
report_id="r1", task_id="t1", task_type=TaskType.MIGRATION,
|
||||
status=ReportStatus.FAILED, updated_at=datetime.utcnow(),
|
||||
status=ReportStatus.FAILED, updated_at=datetime.now(UTC),
|
||||
summary="Migration failed"
|
||||
)
|
||||
detail = ReportDetailView(
|
||||
|
||||
@@ -5,10 +5,10 @@
|
||||
# @INVARIANT key_hash is stored as SHA-256 hex digest (64 chars). prefix stores "ssk_" + first 7 chars.
|
||||
# @INVARIANT Raw key is NEVER stored — shown once at creation and discarded.
|
||||
|
||||
from datetime import UTC, datetime
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import Boolean, Column, DateTime, JSON, String
|
||||
from sqlalchemy import JSON, Boolean, Column, DateTime, String
|
||||
|
||||
from .mapping import Base
|
||||
|
||||
@@ -25,7 +25,7 @@ class APIKey(Base):
|
||||
environment_id = Column(String(50), nullable=True) # Scoped to environment; null = all
|
||||
permissions = Column(JSON, nullable=False) # e.g. ["maintenance:start", "maintenance:end"]
|
||||
active = Column(Boolean, default=True, nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False)
|
||||
expires_at = Column(DateTime, nullable=True)
|
||||
last_used_at = Column(DateTime, nullable=True)
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
# @SIDE_EFFECT Defines assistant audit/message/confirmation tables
|
||||
# @DATA_CONTRACT AssistantData -> AssistantRecord
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import JSON, Column, DateTime, String, Text
|
||||
|
||||
@@ -28,7 +28,7 @@ class AssistantAuditRecord(Base):
|
||||
task_id = Column(String, nullable=True)
|
||||
message = Column(Text, nullable=True)
|
||||
payload = Column(JSON, nullable=True)
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False)
|
||||
|
||||
|
||||
# #endregion AssistantAuditRecord
|
||||
@@ -51,7 +51,7 @@ class AssistantMessageRecord(Base):
|
||||
task_id = Column(String, nullable=True)
|
||||
confirmation_id = Column(String, nullable=True)
|
||||
payload = Column(JSON, nullable=True)
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False)
|
||||
|
||||
|
||||
# #endregion AssistantMessageRecord
|
||||
@@ -72,7 +72,7 @@ class AssistantConfirmationRecord(Base):
|
||||
intent = Column(JSON, nullable=False)
|
||||
dispatch = Column(JSON, nullable=False)
|
||||
expires_at = Column(DateTime, nullable=False)
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False)
|
||||
consumed_at = Column(DateTime, nullable=True)
|
||||
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
# @SIDE_EFFECT Defines auth user tables
|
||||
# @DATA_CONTRACT UserData -> UserRecord
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import Boolean, Column, DateTime, ForeignKey, String, Table
|
||||
@@ -69,7 +69,7 @@ class User(Base):
|
||||
auth_source = Column(String, default="LOCAL") # LOCAL or ADFS
|
||||
is_active = Column(Boolean, default=True)
|
||||
is_ad_user = Column(Boolean, default=False)
|
||||
created_at = Column(DateTime, default=datetime.utcnow)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC))
|
||||
last_login = Column(DateTime, nullable=True)
|
||||
|
||||
roles = relationship("Role", secondary=user_roles, back_populates="users")
|
||||
@@ -128,7 +128,7 @@ class TokenBlacklist(Base):
|
||||
jti = Column(String, primary_key=True) # JWT ID from the token
|
||||
token_hash = Column(String(64), nullable=False, index=True) # SHA-256 of token
|
||||
expires_at = Column(DateTime, nullable=False) # Token's original exp claim
|
||||
revoked_at = Column(DateTime, nullable=False, default=datetime.utcnow)
|
||||
revoked_at = Column(DateTime, nullable=False, default=lambda: datetime.now(UTC))
|
||||
|
||||
|
||||
# #endregion TokenBlacklist
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
# @DATA_CONTRACT Model[ReleaseCandidate, CandidateArtifact, DistributionManifest, ComplianceRun, ComplianceReport]
|
||||
# @INVARIANT Immutable snapshots are never mutated; forbidden lifecycle transitions are rejected.
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
from enum import Enum
|
||||
from typing import Any
|
||||
|
||||
@@ -237,7 +237,7 @@ class ReleaseCandidate(Base):
|
||||
version = Column(String, nullable=False)
|
||||
source_snapshot_ref = Column(String, nullable=False)
|
||||
build_id = Column(String, nullable=True)
|
||||
created_at = Column(DateTime, default=datetime.utcnow)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC))
|
||||
created_by = Column(String, nullable=False)
|
||||
status = Column(String, default=CandidateStatus.DRAFT)
|
||||
|
||||
@@ -333,7 +333,7 @@ class DistributionManifest(Base):
|
||||
manifest_version = Column(Integer, nullable=False)
|
||||
manifest_digest = Column(String, nullable=False)
|
||||
artifacts_digest = Column(String, nullable=False)
|
||||
created_at = Column(DateTime, default=datetime.utcnow)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC))
|
||||
created_by = Column(String, nullable=False)
|
||||
source_snapshot_ref = Column(String, nullable=False)
|
||||
content_json = Column(JSON, nullable=False)
|
||||
@@ -418,7 +418,7 @@ class SourceRegistrySnapshot(Base):
|
||||
id = Column(String, primary_key=True)
|
||||
registry_id = Column(String, nullable=False)
|
||||
registry_version = Column(String, nullable=False)
|
||||
created_at = Column(DateTime, default=datetime.utcnow)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC))
|
||||
allowed_hosts = Column(JSON, nullable=False) # List[str]
|
||||
allowed_schemes = Column(JSON, nullable=False) # List[str]
|
||||
allowed_source_types = Column(JSON, nullable=False) # List[str]
|
||||
@@ -433,7 +433,7 @@ class CleanPolicySnapshot(Base):
|
||||
id = Column(String, primary_key=True)
|
||||
policy_id = Column(String, nullable=False)
|
||||
policy_version = Column(String, nullable=False)
|
||||
created_at = Column(DateTime, default=datetime.utcnow)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC))
|
||||
content_json = Column(JSON, nullable=False)
|
||||
registry_snapshot_id = Column(String, ForeignKey("clean_release_registry_snapshots.id"), nullable=False)
|
||||
immutable = Column(Boolean, default=True)
|
||||
@@ -451,7 +451,7 @@ class ComplianceRun(Base):
|
||||
policy_snapshot_id = Column(String, ForeignKey("clean_release_policy_snapshots.id"), nullable=False)
|
||||
registry_snapshot_id = Column(String, ForeignKey("clean_release_registry_snapshots.id"), nullable=False)
|
||||
requested_by = Column(String, nullable=False)
|
||||
requested_at = Column(DateTime, default=datetime.utcnow)
|
||||
requested_at = Column(DateTime, default=lambda: datetime.now(UTC))
|
||||
started_at = Column(DateTime, nullable=True)
|
||||
finished_at = Column(DateTime, nullable=True)
|
||||
status = Column(String, default=RunStatus.PENDING)
|
||||
@@ -584,7 +584,7 @@ class ComplianceReport(Base):
|
||||
candidate_id = Column(String, ForeignKey("clean_release_candidates.id"), nullable=False)
|
||||
final_status = Column(String, nullable=False) # ComplianceDecision
|
||||
summary_json = Column(JSON, nullable=False)
|
||||
generated_at = Column(DateTime, default=datetime.utcnow)
|
||||
generated_at = Column(DateTime, default=lambda: datetime.now(UTC))
|
||||
immutable = Column(Boolean, default=True)
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
@@ -657,7 +657,7 @@ class ApprovalDecision(Base):
|
||||
report_id = Column(String, ForeignKey("clean_release_compliance_reports.id"), nullable=False)
|
||||
decision = Column(String, nullable=False) # ApprovalDecisionType
|
||||
decided_by = Column(String, nullable=False)
|
||||
decided_at = Column(DateTime, default=datetime.utcnow)
|
||||
decided_at = Column(DateTime, default=lambda: datetime.now(UTC))
|
||||
comment = Column(String, nullable=True)
|
||||
# #endregion ApprovalDecision
|
||||
|
||||
@@ -670,7 +670,7 @@ class PublicationRecord(Base):
|
||||
candidate_id = Column(String, ForeignKey("clean_release_candidates.id"), nullable=False)
|
||||
report_id = Column(String, ForeignKey("clean_release_compliance_reports.id"), nullable=False)
|
||||
published_by = Column(String, nullable=False)
|
||||
published_at = Column(DateTime, default=datetime.utcnow)
|
||||
published_at = Column(DateTime, default=lambda: datetime.now(UTC))
|
||||
target_channel = Column(String, nullable=False)
|
||||
publication_ref = Column(String, nullable=True)
|
||||
status = Column(String, default=PublicationStatus.ACTIVE)
|
||||
@@ -688,7 +688,7 @@ class CleanReleaseAuditLog(Base):
|
||||
candidate_id = Column(String, index=True, nullable=True)
|
||||
action = Column(String, nullable=False) # e.g. "TRANSITION", "APPROVE", "PUBLISH"
|
||||
actor = Column(String, nullable=False)
|
||||
timestamp = Column(DateTime, default=datetime.utcnow)
|
||||
timestamp = Column(DateTime, default=lambda: datetime.now(UTC))
|
||||
details_json = Column(JSON, default=dict)
|
||||
# #endregion CleanReleaseAuditLog
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
# @SIDE_EFFECT Defines dataset review clarification tables
|
||||
# @DATA_CONTRACT ClarificationData -> ClarificationRecord
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import (
|
||||
@@ -45,8 +45,8 @@ class ClarificationSession(Base):
|
||||
resolved_count = Column(Integer, nullable=False, default=0)
|
||||
remaining_count = Column(Integer, nullable=False, default=0)
|
||||
summary_delta = Column(Text, nullable=True)
|
||||
started_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
started_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False)
|
||||
updated_at = Column(DateTime, default=lambda: datetime.now(UTC), onupdate=lambda: datetime.now(UTC), nullable=False)
|
||||
completed_at = Column(DateTime, nullable=True)
|
||||
|
||||
session = relationship("DatasetReviewSession", back_populates="clarification_sessions")
|
||||
@@ -70,8 +70,8 @@ class ClarificationQuestion(Base):
|
||||
current_guess = Column(Text, nullable=True)
|
||||
priority = Column(Integer, nullable=False, default=0)
|
||||
state = Column(SQLEnum(QuestionState), nullable=False, default=QuestionState.OPEN)
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False)
|
||||
updated_at = Column(DateTime, default=lambda: datetime.now(UTC), onupdate=lambda: datetime.now(UTC), nullable=False)
|
||||
|
||||
clarification_session = relationship("ClarificationSession", back_populates="questions")
|
||||
options = relationship("ClarificationOption", back_populates="question", cascade="all, delete-orphan")
|
||||
@@ -113,7 +113,7 @@ class ClarificationAnswer(Base):
|
||||
answered_by_user_id = Column(String, nullable=False)
|
||||
impact_summary = Column(Text, nullable=True)
|
||||
user_feedback = Column(Text, nullable=True)
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False)
|
||||
|
||||
question = relationship("ClarificationQuestion", back_populates="answer")
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
# @RELATION DEPENDS_ON -> [DatasetReviewEnums]
|
||||
# @RELATION DEPENDS_ON -> [MappingModels]
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import (
|
||||
@@ -46,7 +46,7 @@ class CompiledPreview(Base):
|
||||
error_code = Column(String, nullable=True)
|
||||
error_details = Column(Text, nullable=True)
|
||||
compiled_at = Column(DateTime, nullable=True)
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False)
|
||||
|
||||
session = relationship("DatasetReviewSession", back_populates="previews")
|
||||
|
||||
@@ -75,7 +75,7 @@ class DatasetRunContext(Base):
|
||||
open_warning_refs = Column(JSON, nullable=False)
|
||||
launch_status = Column(SQLEnum(LaunchStatus), nullable=False)
|
||||
launch_error = Column(Text, nullable=True)
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False)
|
||||
|
||||
session = relationship("DatasetReviewSession", back_populates="run_contexts")
|
||||
|
||||
@@ -101,7 +101,7 @@ class SessionEvent(Base):
|
||||
current_phase = Column(String, nullable=True)
|
||||
readiness_state = Column(String, nullable=True)
|
||||
event_details = Column(JSON, nullable=False, default=dict)
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False)
|
||||
|
||||
session = relationship("DatasetReviewSession", back_populates="events")
|
||||
actor = relationship("User")
|
||||
@@ -124,7 +124,7 @@ class ExportArtifact(Base):
|
||||
format = Column(SQLEnum(ArtifactFormat), nullable=False)
|
||||
storage_ref = Column(String, nullable=False)
|
||||
created_by_user_id = Column(String, nullable=False)
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False)
|
||||
|
||||
session = relationship("DatasetReviewSession", back_populates="export_artifacts")
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
# @RELATION DEPENDS_ON -> [DatasetReviewEnums]
|
||||
# @RELATION DEPENDS_ON -> [MappingModels]
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import (
|
||||
@@ -49,9 +49,9 @@ class ImportedFilter(Base):
|
||||
requires_confirmation = Column(Boolean, nullable=False, default=False)
|
||||
recovery_status = Column(SQLEnum(FilterRecoveryStatus), nullable=False)
|
||||
notes = Column(Text, nullable=True)
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False)
|
||||
updated_at = Column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
|
||||
DateTime, default=lambda: datetime.now(UTC), onupdate=lambda: datetime.now(UTC), nullable=False
|
||||
)
|
||||
|
||||
session = relationship("DatasetReviewSession", back_populates="imported_filters")
|
||||
@@ -78,9 +78,9 @@ class TemplateVariable(Base):
|
||||
mapping_status = Column(
|
||||
SQLEnum(MappingStatus), nullable=False, default=MappingStatus.UNMAPPED
|
||||
)
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False)
|
||||
updated_at = Column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
|
||||
DateTime, default=lambda: datetime.now(UTC), onupdate=lambda: datetime.now(UTC), nullable=False
|
||||
)
|
||||
|
||||
session = relationship("DatasetReviewSession", back_populates="template_variables")
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
# @RELATION DEPENDS_ON -> [DatasetReviewEnums]
|
||||
# @RELATION DEPENDS_ON -> [MappingModels]
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import (
|
||||
@@ -45,7 +45,7 @@ class ValidationFinding(Base):
|
||||
)
|
||||
resolution_note = Column(Text, nullable=True)
|
||||
caused_by_ref = Column(String, nullable=True)
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False)
|
||||
resolved_at = Column(DateTime, nullable=True)
|
||||
|
||||
session = relationship("DatasetReviewSession", back_populates="findings")
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
# @RELATION DEPENDS_ON -> [DatasetReviewEnums]
|
||||
# @RELATION DEPENDS_ON -> [MappingModels]
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import (
|
||||
@@ -47,8 +47,8 @@ class ExecutionMapping(Base):
|
||||
approval_state = Column(SQLEnum(ApprovalState), nullable=False, default=ApprovalState.NOT_REQUIRED)
|
||||
approved_by_user_id = Column(String, nullable=True)
|
||||
approved_at = Column(DateTime, nullable=True)
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False)
|
||||
updated_at = Column(DateTime, default=lambda: datetime.now(UTC), onupdate=lambda: datetime.now(UTC), nullable=False)
|
||||
|
||||
session = relationship("DatasetReviewSession", back_populates="execution_mappings")
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
# @RELATION DEPENDS_ON -> [DatasetReviewEnums]
|
||||
# @RELATION DEPENDS_ON -> [MappingModels]
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import (
|
||||
@@ -52,9 +52,9 @@ class DatasetProfile(Base):
|
||||
has_blocking_findings = Column(Boolean, nullable=False, default=False)
|
||||
has_warning_findings = Column(Boolean, nullable=False, default=False)
|
||||
manual_summary_locked = Column(Boolean, nullable=False, default=False)
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False)
|
||||
updated_at = Column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
|
||||
DateTime, default=lambda: datetime.now(UTC), onupdate=lambda: datetime.now(UTC), nullable=False
|
||||
)
|
||||
|
||||
session = relationship("DatasetReviewSession", back_populates="profile")
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
# @SIDE_EFFECT Defines dataset review semantic tables
|
||||
# @DATA_CONTRACT SemanticData -> SemanticFieldEntry
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import (
|
||||
@@ -58,7 +58,7 @@ class SemanticSource(Base):
|
||||
nullable=False,
|
||||
default=SemanticSourceStatus.AVAILABLE,
|
||||
)
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False)
|
||||
|
||||
session = relationship("DatasetReviewSession", back_populates="semantic_sources")
|
||||
|
||||
@@ -94,9 +94,9 @@ class SemanticFieldEntry(Base):
|
||||
needs_review = Column(Boolean, nullable=False, default=True)
|
||||
last_changed_by = Column(String, nullable=False)
|
||||
user_feedback = Column(String, nullable=True)
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False)
|
||||
updated_at = Column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
|
||||
DateTime, default=lambda: datetime.now(UTC), onupdate=lambda: datetime.now(UTC), nullable=False
|
||||
)
|
||||
|
||||
session = relationship("DatasetReviewSession", back_populates="semantic_fields")
|
||||
@@ -128,7 +128,7 @@ class SemanticCandidate(Base):
|
||||
status = Column(
|
||||
SQLEnum(CandidateStatus), nullable=False, default=CandidateStatus.PROPOSED
|
||||
)
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False)
|
||||
|
||||
field = relationship("SemanticFieldEntry", back_populates="candidates")
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
# @SIDE_EFFECT Defines dataset review session tables
|
||||
# @DATA_CONTRACT SessionData -> SessionRecord
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import (
|
||||
@@ -44,7 +44,7 @@ class SessionCollaborator(Base):
|
||||
)
|
||||
user_id = Column(String, ForeignKey("users.id"), nullable=False)
|
||||
role = Column(SQLEnum(SessionCollaboratorRole), nullable=False)
|
||||
added_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
added_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False)
|
||||
|
||||
session = relationship("DatasetReviewSession", back_populates="collaborators")
|
||||
user = relationship("User")
|
||||
@@ -99,11 +99,11 @@ class DatasetReviewSession(Base):
|
||||
active_task_id = Column(String, nullable=True)
|
||||
last_preview_id = Column(String, nullable=True)
|
||||
last_run_context_id = Column(String, nullable=True)
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False)
|
||||
updated_at = Column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
|
||||
DateTime, default=lambda: datetime.now(UTC), onupdate=lambda: datetime.now(UTC), nullable=False
|
||||
)
|
||||
last_activity_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
last_activity_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False)
|
||||
closed_at = Column(DateTime, nullable=True)
|
||||
|
||||
owner = relationship("User")
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# #region GitModels [TYPE Module] [SEMANTICS sqlalchemy, git, model, config, sync]
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
import enum
|
||||
import uuid
|
||||
|
||||
@@ -37,7 +37,7 @@ class GitServerConfig(Base):
|
||||
default_repository = Column(String(255), nullable=True)
|
||||
default_branch = Column(String(255), default="main")
|
||||
status = Column(Enum(GitStatus), default=GitStatus.UNKNOWN)
|
||||
last_validated = Column(DateTime, default=datetime.utcnow)
|
||||
last_validated = Column(DateTime, default=lambda: datetime.now(UTC))
|
||||
# #endregion GitServerConfig
|
||||
|
||||
# #region GitRepository [C:1] [TYPE Class]
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
# @LAYER Domain
|
||||
# @RELATION INHERITS -> [MappingModels]
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import JSON, Boolean, Column, DateTime, String, Text, Time
|
||||
@@ -32,8 +32,8 @@ class ValidationPolicy(Base):
|
||||
notify_owners = Column(Boolean, default=True)
|
||||
custom_channels = Column(JSON, nullable=True) # List of external channels
|
||||
alert_condition = Column(String, default="FAIL_ONLY") # FAIL_ONLY, WARN_AND_FAIL, ALWAYS
|
||||
created_at = Column(DateTime, default=datetime.utcnow)
|
||||
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC))
|
||||
updated_at = Column(DateTime, default=lambda: datetime.now(UTC), onupdate=lambda: datetime.now(UTC))
|
||||
# #endregion ValidationPolicy
|
||||
|
||||
# #region LLMProvider [TYPE Class]
|
||||
@@ -49,7 +49,7 @@ class LLMProvider(Base):
|
||||
default_model = Column(String, nullable=False)
|
||||
is_active = Column(Boolean, default=True)
|
||||
is_multimodal = Column(Boolean, default=False)
|
||||
created_at = Column(DateTime, default=datetime.utcnow)
|
||||
created_at = Column(DateTime, default=lambda: datetime.now(UTC))
|
||||
# #endregion LLMProvider
|
||||
|
||||
# #region ValidationRecord [TYPE Class]
|
||||
@@ -62,7 +62,7 @@ class ValidationRecord(Base):
|
||||
policy_id = Column(String, nullable=True, index=True) # Reference to ValidationPolicy.id
|
||||
dashboard_id = Column(String, nullable=False, index=True)
|
||||
environment_id = Column(String, nullable=True, index=True)
|
||||
timestamp = Column(DateTime, default=datetime.utcnow)
|
||||
timestamp = Column(DateTime, default=lambda: datetime.now(UTC))
|
||||
status = Column(String, nullable=False) # PASS, WARN, FAIL, UNKNOWN
|
||||
screenshot_path = Column(String, nullable=True)
|
||||
issues = Column(JSON, nullable=False)
|
||||
|
||||
@@ -10,6 +10,7 @@ import enum
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import (
|
||||
JSON,
|
||||
CheckConstraint,
|
||||
Column,
|
||||
DateTime,
|
||||
@@ -17,7 +18,6 @@ from sqlalchemy import (
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
JSON,
|
||||
String,
|
||||
Text,
|
||||
)
|
||||
|
||||
@@ -16,7 +16,7 @@ import enum
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import Boolean, Column, DateTime, Enum as SQLEnum, ForeignKey, String
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import declarative_base
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
# #region Base [C:1] [TYPE Class]
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
# @SIDE_EFFECT Defines user profile/preference tables
|
||||
# @DATA_CONTRACT ProfileData -> PreferenceRecord
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import Boolean, Column, DateTime, ForeignKey, String
|
||||
@@ -48,12 +48,12 @@ class UserDashboardPreference(Base):
|
||||
email_address = Column(String, nullable=True)
|
||||
notify_on_fail = Column(Boolean, nullable=False, default=True)
|
||||
|
||||
created_at = Column(DateTime, nullable=False, default=datetime.utcnow)
|
||||
created_at = Column(DateTime, nullable=False, default=lambda: datetime.now(UTC))
|
||||
updated_at = Column(
|
||||
DateTime,
|
||||
nullable=False,
|
||||
default=datetime.utcnow,
|
||||
onupdate=datetime.utcnow,
|
||||
default=lambda: datetime.now(UTC),
|
||||
onupdate=lambda: datetime.now(UTC),
|
||||
)
|
||||
|
||||
user = relationship("User")
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
# @RATIONALE Fixed typo 'repositorys' → 'repositories' in FileCategory.REPOSITORY and StorageConfig.repo_path default. Breaking change documented for existing installations.
|
||||
from datetime import datetime
|
||||
from enum import Enum
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
# #region FileCategory [C:1] [TYPE Class]
|
||||
# @BRIEF Enumeration of supported file categories in the storage system.
|
||||
class FileCategory(str, Enum):
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
# @LAYER Domain
|
||||
# @RELATION DEPENDS_ON -> [EXT:Library:pydantic]
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
from enum import Enum
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
@@ -53,7 +53,7 @@ class DetectedIssue(BaseModel):
|
||||
class ValidationResult(BaseModel):
|
||||
id: str | None = None
|
||||
dashboard_id: str
|
||||
timestamp: datetime = Field(default_factory=datetime.utcnow)
|
||||
timestamp: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
||||
status: ValidationStatus
|
||||
screenshot_path: str | None = None
|
||||
issues: list[DetectedIssue]
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
# @INVARIANT All LLM interactions must be executed as asynchronous tasks.
|
||||
# @DATA_CONTRACT AnalysisRequest -> AnalysisResult
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import UTC, datetime, timedelta
|
||||
import json
|
||||
import os
|
||||
from typing import Any
|
||||
@@ -99,7 +99,7 @@ class DashboardValidationPlugin(PluginBase):
|
||||
# @SIDE_EFFECT Captures a screenshot, calls LLM API, and writes to the database.
|
||||
async def execute(self, params: dict[str, Any], context: TaskContext | None = None):
|
||||
with belief_scope("execute", f"plugin_id={self.id}"):
|
||||
validation_started_at = datetime.utcnow()
|
||||
validation_started_at = datetime.now(UTC)
|
||||
# Use TaskContext logger if available, otherwise fall back to app logger
|
||||
log = context.logger if context else logger
|
||||
|
||||
@@ -165,15 +165,15 @@ class DashboardValidationPlugin(PluginBase):
|
||||
filename = f"{dashboard_id}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
|
||||
screenshot_path = os.path.join(screenshots_dir, filename)
|
||||
|
||||
screenshot_started_at = datetime.utcnow()
|
||||
screenshot_started_at = datetime.now(UTC)
|
||||
screenshot_log.info(f"Capturing screenshot for dashboard {dashboard_id}")
|
||||
await screenshot_service.capture_dashboard(dashboard_id, screenshot_path)
|
||||
screenshot_log.debug(f"Screenshot saved to: {screenshot_path}")
|
||||
screenshot_finished_at = datetime.utcnow()
|
||||
screenshot_finished_at = datetime.now(UTC)
|
||||
|
||||
# 4. Fetch Logs (from Environment /api/v1/log/)
|
||||
logs = []
|
||||
logs_fetch_started_at = datetime.utcnow()
|
||||
logs_fetch_started_at = datetime.now(UTC)
|
||||
try:
|
||||
client = SupersetClient(env)
|
||||
|
||||
@@ -214,7 +214,7 @@ class DashboardValidationPlugin(PluginBase):
|
||||
except Exception as e:
|
||||
superset_log.warning(f"Failed to fetch logs from environment: {e}")
|
||||
logs = [f"Error fetching remote logs: {e!s}"]
|
||||
logs_fetch_finished_at = datetime.utcnow()
|
||||
logs_fetch_finished_at = datetime.now(UTC)
|
||||
|
||||
# 5. Analyze with LLM
|
||||
llm_client = LLMClient(
|
||||
@@ -230,13 +230,13 @@ class DashboardValidationPlugin(PluginBase):
|
||||
"dashboard_validation_prompt",
|
||||
DEFAULT_LLM_PROMPTS["dashboard_validation_prompt"],
|
||||
)
|
||||
llm_call_started_at = datetime.utcnow()
|
||||
llm_call_started_at = datetime.now(UTC)
|
||||
analysis = await llm_client.analyze_dashboard(
|
||||
screenshot_path,
|
||||
logs,
|
||||
prompt_template=dashboard_prompt,
|
||||
)
|
||||
llm_call_finished_at = datetime.utcnow()
|
||||
llm_call_finished_at = datetime.now(UTC)
|
||||
|
||||
# Log analysis summary to task logs for better visibility
|
||||
llm_log.info(f"[ANALYSIS_SUMMARY] Status: {analysis['status']}")
|
||||
@@ -254,9 +254,9 @@ class DashboardValidationPlugin(PluginBase):
|
||||
screenshot_path=screenshot_path,
|
||||
raw_response=str(analysis)
|
||||
)
|
||||
validation_finished_at = datetime.utcnow()
|
||||
validation_finished_at = datetime.now(UTC)
|
||||
|
||||
result_payload = _json_safe_value(validation_result.dict())
|
||||
result_payload = _json_safe_value(validation_result.model_dump())
|
||||
result_payload["screenshot_paths"] = [screenshot_path]
|
||||
result_payload["logs_sent_to_llm"] = logs
|
||||
result_payload["logs_sent_count"] = len(logs)
|
||||
@@ -291,7 +291,7 @@ class DashboardValidationPlugin(PluginBase):
|
||||
environment_id=env_id,
|
||||
status=validation_result.status.value,
|
||||
summary=validation_result.summary,
|
||||
issues=[issue.dict() for issue in validation_result.issues],
|
||||
issues=[issue.model_dump() for issue in validation_result.issues],
|
||||
screenshot_path=validation_result.screenshot_path,
|
||||
raw_response=json.dumps(result_payload, ensure_ascii=False)
|
||||
)
|
||||
|
||||
@@ -842,7 +842,7 @@ class ScreenshotService:
|
||||
await asyncio.sleep(0.5)
|
||||
except Exception:
|
||||
pass
|
||||
except asyncio.TimeoutError:
|
||||
except TimeoutError:
|
||||
logger.error(f"Screenshot capture timed out after {SCREENSHOT_SERVICE_TIMEOUT_MS}ms")
|
||||
try:
|
||||
await page.screenshot(path=output_path, timeout=PLAYWRIGHT_SHORT_TIMEOUT_MS)
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
# @TEST_EDGE non_timestamp_string -> passed through unchanged
|
||||
|
||||
import logging
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from src.plugins.translate.sql_generator import (
|
||||
|
||||
@@ -11,10 +11,10 @@
|
||||
# @REJECTED Keeping 1199-line test module violates module < 400 lines constraint.
|
||||
|
||||
# All tests have been migrated to the following modules:
|
||||
from .test_dictionary_correction import * # noqa: F401, F403
|
||||
from .test_dictionary_crud import * # noqa: F401, F403
|
||||
from .test_dictionary_filter import * # noqa: F401, F403
|
||||
from .test_dictionary_import import * # noqa: F401, F403
|
||||
from .test_dictionary_prompt_builder import * # noqa: F401, F403
|
||||
from .test_dictionary_utils import * # noqa: F401, F403
|
||||
from .test_dictionary_correction import * # noqa: F403
|
||||
from .test_dictionary_crud import * # noqa: F403
|
||||
from .test_dictionary_filter import * # noqa: F403
|
||||
from .test_dictionary_import import * # noqa: F403
|
||||
from .test_dictionary_prompt_builder import * # noqa: F403
|
||||
from .test_dictionary_utils import * # noqa: F403
|
||||
# #endregion TestDictionaryLegacyHub
|
||||
|
||||
@@ -10,7 +10,6 @@ from sqlalchemy.orm import Session, sessionmaker
|
||||
from src.models.translate import (
|
||||
Base,
|
||||
DictionaryEntry,
|
||||
TerminologyDictionary,
|
||||
TranslationBatch,
|
||||
TranslationJob,
|
||||
TranslationLanguage,
|
||||
|
||||
@@ -12,7 +12,7 @@ import pytest
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from src.models.translate import Base, DictionaryEntry, TerminologyDictionary, TranslationJob, TranslationJobDictionary
|
||||
from src.models.translate import Base, TranslationJob, TranslationJobDictionary
|
||||
from src.plugins.translate.dictionary import DictionaryManager
|
||||
|
||||
|
||||
|
||||
@@ -14,7 +14,6 @@ from src.models.translate import (
|
||||
TranslationJob,
|
||||
TranslationRun,
|
||||
)
|
||||
from src.plugins.translate._batch_sizer import AdaptiveBatchSizer
|
||||
from src.plugins.translate.executor import TranslationExecutor, estimate_row_tokens
|
||||
|
||||
|
||||
|
||||
@@ -298,9 +298,7 @@ class TestBulkFindReplaceService:
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from src.models.translate import TranslationLanguage, TranslationRecord
|
||||
from src.plugins.translate.prompt_builder import ContextAwarePromptBuilder
|
||||
from src.plugins.translate.service import InlineCorrectionService
|
||||
|
||||
|
||||
# region TestContextCapture [TYPE Class]
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
from datetime import UTC, datetime
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, PropertyMock, patch
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from src.models.translate import (
|
||||
TranslationJob,
|
||||
|
||||
@@ -18,7 +18,6 @@ from src.plugins.translate.service_target_schema import (
|
||||
validate_target_table_schema,
|
||||
)
|
||||
from src.schemas.translate import (
|
||||
TargetSchemaColumnInfo,
|
||||
TargetSchemaValidationRequest,
|
||||
)
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@
|
||||
# @REJECTED Inline insert logic in process_batch — made the function 583 lines.
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ from ...core.logger import belief_scope, logger
|
||||
from ...models.translate import TranslationBatch, TranslationJob, TranslationLanguage, TranslationRecord
|
||||
from ...services.llm_provider import LLMProviderService
|
||||
from ._batch_insert import insert_batch_to_target
|
||||
from ._lang_detect import batch_detect, get_detector
|
||||
from ._lang_detect import batch_detect
|
||||
from ._llm_call import LLMTranslationService
|
||||
from ._token_budget import estimate_token_budget
|
||||
from ._utils import _check_translation_cache, _compute_key_hash, _compute_source_hash
|
||||
|
||||
@@ -11,8 +11,6 @@
|
||||
# @REJECTED Fixed batch_size of 50 — causes truncation on long-content rows.
|
||||
# Single monolithic batch — would lose all progress on any failure.
|
||||
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
|
||||
@@ -30,7 +30,6 @@ from ...services.llm_prompt_templates import render_prompt
|
||||
from ...services.llm_provider import LLMProviderService
|
||||
from ._llm_http import call_openai_compatible
|
||||
from ._llm_parse import parse_llm_response
|
||||
from ._token_budget import estimate_token_budget
|
||||
from ._utils import _enforce_dictionary
|
||||
from .preview import DEFAULT_EXECUTION_PROMPT_TEMPLATE
|
||||
from .prompt_builder import ContextAwarePromptBuilder
|
||||
|
||||
@@ -35,7 +35,6 @@ def call_openai_compatible(
|
||||
if not base_url:
|
||||
raise ValueError("LLM provider has no base_url configured")
|
||||
|
||||
import requests as http_requests
|
||||
|
||||
url = f"{base_url.rstrip('/')}/chat/completions"
|
||||
headers = {
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from ...core.logger import logger
|
||||
|
||||
|
||||
@@ -12,15 +12,13 @@
|
||||
# @REJECTED Keeping all run orchestration inside TranslationExecutor — caused class to exceed INV_7.
|
||||
|
||||
from collections.abc import Callable
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ...core.config_manager import ConfigManager
|
||||
from ...core.logger import belief_scope, logger
|
||||
from ...models.translate import TranslationJob, TranslationRecord, TranslationRun, TranslationRunLanguageStats
|
||||
from ._batch_sizer import AdaptiveBatchSizer
|
||||
from ...models.translate import TranslationRecord, TranslationRun, TranslationRunLanguageStats
|
||||
from ._run_source import _extract_chart_data_rows, fetch_source_rows
|
||||
|
||||
|
||||
@@ -97,7 +95,7 @@ class RunExecutionService:
|
||||
|
||||
def _load_preview_edits(self, job_id: str) -> None:
|
||||
"""Load preview edits for carry-forward during execution."""
|
||||
from ...models.translate import TranslationPreviewLanguage, TranslationPreviewRecord, TranslationPreviewSession
|
||||
from ...models.translate import TranslationPreviewRecord, TranslationPreviewSession
|
||||
|
||||
with belief_scope("RunExecutionService._load_preview_edits"):
|
||||
session = (
|
||||
|
||||
@@ -17,7 +17,7 @@ import unicodedata
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from ...core.logger import logger
|
||||
from ...models.translate import TranslationLanguage, TranslationRecord
|
||||
from ...models.translate import TranslationRecord
|
||||
|
||||
|
||||
# #region _normalize_term [TYPE Function]
|
||||
|
||||
@@ -12,18 +12,13 @@
|
||||
# @PRE Database session is open and valid.
|
||||
# @SIDE_EFFECT Creates, updates, deletes TerminologyDictionary and DictionaryEntry rows; enforces deletion guards.
|
||||
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ...core.logger import belief_scope
|
||||
from ...models.translate import DictionaryEntry, TerminologyDictionary
|
||||
from .dictionary_correction import DictionaryCorrectionService
|
||||
from .dictionary_crud import DictionaryCRUD
|
||||
from .dictionary_entries import DictionaryEntryCRUD
|
||||
from .dictionary_filter import DictionaryBatchFilter
|
||||
from .dictionary_import_export import DictionaryImportExport
|
||||
from .dictionary_validation import _validate_bcp47
|
||||
|
||||
|
||||
# #region DictionaryManager [C:4] [TYPE Class]
|
||||
|
||||
@@ -28,12 +28,14 @@ from ...core.logger import logger
|
||||
from ...models.translate import TranslationJob, TranslationRun, TranslationRunLanguageStats
|
||||
from ...services.llm_provider import LLMProviderService
|
||||
from ._run_service import RunExecutionService
|
||||
from ._token_budget import estimate_token_budget
|
||||
from ._utils import _check_translation_cache, _compute_source_hash, _enforce_dictionary, estimate_row_tokens
|
||||
|
||||
__all__ = [
|
||||
"TranslationExecutor", "estimate_row_tokens",
|
||||
"_enforce_dictionary", "_compute_source_hash", "_check_translation_cache",
|
||||
"TranslationExecutor",
|
||||
"_check_translation_cache",
|
||||
"_compute_source_hash",
|
||||
"_enforce_dictionary",
|
||||
"estimate_row_tokens",
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
# @REJECTED Querying all events for all time — would be slow; MetricSnapshot provides historical summary.
|
||||
# @COMPLEXITY 4
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func
|
||||
@@ -20,7 +19,6 @@ from sqlalchemy.orm import Session
|
||||
from ...core.logger import belief_scope
|
||||
from ...models.translate import (
|
||||
MetricSnapshot,
|
||||
TranslationEvent,
|
||||
TranslationRun,
|
||||
TranslationRunLanguageStats,
|
||||
TranslationSchedule,
|
||||
|
||||
@@ -23,12 +23,11 @@ from typing import Any
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ...core.config_manager import ConfigManager
|
||||
from ...core.logger import belief_scope, logger
|
||||
from ...core.logger import belief_scope
|
||||
from ...models.translate import (
|
||||
TranslationRun,
|
||||
)
|
||||
from .events import TranslationEventLog
|
||||
from .executor import TranslationExecutor
|
||||
from .orchestrator_aggregator import TranslationResultAggregator
|
||||
from .orchestrator_planner import TranslationPlanner
|
||||
from .orchestrator_runner import TranslationStageRunner
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
# @RELATION DEPENDS_ON -> [TranslationRunLanguageStats]
|
||||
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
|
||||
@@ -19,7 +19,6 @@ from sqlalchemy.orm import Session
|
||||
from ...core.logger import belief_scope, logger
|
||||
from ...models.translate import (
|
||||
TranslationJob,
|
||||
TranslationPreviewSession,
|
||||
TranslationRun,
|
||||
)
|
||||
from .events import TranslationEventLog
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
# @RELATION DEPENDS_ON -> [TranslationEventLog]
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from ...core.logger import logger
|
||||
from ...models.translate import TranslationJob, TranslationRun, TranslationRunLanguageStats
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
# @RELATION DEPENDS_ON -> [TranslationJob]
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from ...models.translate import TranslationJob, TranslationRecord
|
||||
from .sql_generator import _normalize_timestamp_value
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user