Preserve distributed job context and expose grade 4 operational signals

This commit is contained in:
Artyom
2026-11-06 12:57:10 +03:00
parent 1a171d0d0f
commit 44d81fd80e
32 changed files with 1098 additions and 35 deletions
@@ -112,6 +112,8 @@ def test_shared_core_holds_only_platform() -> None:
"logging.py",
"postgres.py",
"telemetry.py",
"trace_context.py",
"runtime_metrics.py",
"readiness.py",
}
+7 -2
View File
@@ -6,6 +6,7 @@ import sys
from collections.abc import AsyncIterator
from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import Any
from uuid import uuid4
import pytest
@@ -15,6 +16,7 @@ from alembic.migration import MigrationContext
from alembic.script import ScriptDirectory
from alembic.util import CommandError
from sqlalchemy import MetaData, Table, case, func, insert, inspect, literal, make_url, select, text
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.pool import NullPool
@@ -44,6 +46,7 @@ VERSIONS = [
"0004_jobs",
"0005_failed_registry",
"0006_attachment_quarantine",
"0007_trace_context",
]
TABLES = [
UserRow,
@@ -247,13 +250,15 @@ async def contents(dsn: str) -> dict:
table = await connection.run_sync(
lambda sync, name=model.__tablename__: Table(name, MetaData(), autoload_with=sync)
)
missing = {}
missing: dict[str, Any] = {}
if model is AttachmentRow and "published_version" not in table.c:
missing = {
"original_key": case((table.c.status == "ready", table.c.object_key)),
"staging_key": case((table.c.status == "pending", table.c.object_key)),
"published_version": case((table.c.status == "ready", 1), else_=0),
}
if model in (JobRow, OutboxRow):
missing["trace_context"] = literal({}, type_=JSONB)
columns = [
table.c[col.name]
if col.name in table.c
@@ -449,7 +454,7 @@ async def test_failed_revision_rolls_back_ddl_and_version(
"from alembic import op\n"
"import sqlalchemy as sa\n"
"revision = '0003_failure'\n"
"down_revision = '0006_attachment_quarantine'\n"
"down_revision = '0007_trace_context'\n"
"def upgrade():\n"
" op.create_table('must_rollback', sa.Column('id', sa.Integer, primary_key=True))\n"
" raise RuntimeError('migration failed')\n"
+65
View File
@@ -0,0 +1,65 @@
import asyncio
from datetime import timedelta
from uuid import UUID
from httpx import AsyncClient
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.trace import SpanKind
from sqlalchemy import select
from test_pipeline import accepted, job_of
from conftest import sql_connection
from messenger.attachments.infrastructure.postgres import JobRow, OutboxRow, PostgresJobRepository
from messenger.shared.infrastructure.trace_context import capture_context, restored_context
from pipeline import pipeline_of
async def test_context_survives_outbox_delivery_and_lease_recovery(client: AsyncClient) -> None:
provider = TracerProvider(shutdown_on_exit=False)
tracer = provider.get_tracer("test")
with tracer.start_as_current_span("upload", kind=SpanKind.SERVER):
origin = capture_context()
_, _, attachment_id = await accepted(client)
job = await job_of(attachment_id)
async with sql_connection() as connection:
assert (
await connection.scalar(select(JobRow.trace_context).where(JobRow.job_id == job.id))
== origin
)
assert (
await connection.scalar(
select(OutboxRow.trace_context).where(OutboxRow.job_id == job.id)
)
== origin
)
pipeline = await pipeline_of(client)
await pipeline.publish()
assert pipeline.publisher.contexts == [origin]
uow = pipeline.uow()
async with uow.transaction():
claim = await uow.jobs.claim(job, UUID(int=1), timedelta(seconds=-1))
assert claim is not None
await uow.commit()
await pipeline.recover()
await asyncio.sleep(0.02)
await pipeline.publish()
assert len(pipeline.publisher.contexts) == 2
assert pipeline.publisher.contexts[-1] == origin
with restored_context(origin), tracer.start_as_current_span("retry", kind=SpanKind.CONSUMER):
retry = capture_context()
async with uow.transaction():
await PostgresJobRepository(uow.session)._enqueue(job)
await uow.commit()
async with sql_connection() as connection:
assert (
await connection.scalar(
select(OutboxRow.trace_context)
.where(OutboxRow.job_id == job.id)
.order_by(OutboxRow.id.desc())
.limit(1)
)
== retry
)
assert retry["traceparent"].split("-")[1] == origin["traceparent"].split("-")[1]
assert retry != origin
provider.shutdown()