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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .changes/job-closure-ownership.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
保持仍在释放资源的 Job 为运行中,由实际执行者发布终态。单个处理操作提前超时会记录为失败,并保留原因。
2 changes: 2 additions & 0 deletions docs/40-deployment/runtime-orchestration.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ by normal lifespan shutdown. Failed restore does not publish a new Peer lease or
before an atomic database claim. Only the winning Peer executes; each run conditionally closes once to a terminal status.
- `abort_requested` is durable intent, not evidence of completion. A pending Job can close immediately; a running Job
remains running until its execution task has exited and released its resources. Repeating abort preserves terminal state.
- 普通轮询只发现待执行任务。执行器仅在本次执行预算实际到期时记录 `timed_out`,Handler 内部操作提前超时属于失败。
进程异常退出留下的 running 记录需要单独维护。只有确认相关执行已停止,才可调用部署级 `JobManager.expire_overdue()`。
- source ordinary collect/backfill、lexical maintain/rebuild、semantic maintain/rebuild and media interpretation are exact Job
types。Their domain Managers do not acquire Cron semantics merely because a Handler calls them。

Expand Down
77 changes: 41 additions & 36 deletions inkcre_core/business/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,50 +346,56 @@ async def run(cls, job_id: JobID) -> bool:
task = asyncio.current_task()
assert task is not None
current_core().active_jobs[job_id] = _Execution(task)
with operation(
"job.execute",
attributes={"inkcre.job.id": job_id},
context=Context(),
links=submission_links(claimed.submission_traceparent, claimed.submission_tracestate),
) as observation:
span = observation.span
emit_event("job.started", {"inkcre.job.id": job_id})
try:
async with asyncio.timeout(claimed.timeout_seconds):
await handler.handle(claimed, parameters)
except asyncio.CancelledError:
LOGGER.info("Job execution aborted", extra={"job_id": job_id})
observation.outcome = "cancelled"
span.set_attribute("inkcre.job.status", "aborted")
await cls._close(claimed, JobStatus.ABORTED)
except TimeoutError:
LOGGER.warning("Job execution timed out", extra={"job_id": job_id})
observation.outcome = "error"
span.set_attribute("inkcre.job.status", "timed_out")
await cls._close(claimed, JobStatus.TIMED_OUT)
except Exception as error:
LOGGER.exception("Job execution failed", extra={"job_id": job_id})
observation.outcome = "error"
span.set_attribute("error.type", type(error).__name__)
span.set_attribute("inkcre.job.status", "failed")
claimed.state = {**claimed.state, "error": str(error)}
await cls._close(claimed, JobStatus.FAILED)
else:
span.set_attribute("inkcre.job.status", "finished")
await cls._close(claimed, JobStatus.FINISHED)
finally:
current_core().active_jobs.pop(job_id, None)
try:
with operation(
"job.execute",
attributes={"inkcre.job.id": job_id},
context=Context(),
links=submission_links(
claimed.submission_traceparent, claimed.submission_tracestate
),
) as observation:
span = observation.span
emit_event("job.started", {"inkcre.job.id": job_id})
budget = asyncio.timeout(claimed.timeout_seconds)
try:
async with budget:
await handler.handle(claimed, parameters)
except asyncio.CancelledError:
LOGGER.info("Job execution aborted", extra={"job_id": job_id})
observation.outcome = "cancelled"
status = JobStatus.ABORTED
except Exception as error:
observation.outcome = "error"
if isinstance(error, TimeoutError) and budget.expired():
LOGGER.warning("Job execution timed out", extra={"job_id": job_id})
status = JobStatus.TIMED_OUT
else:
LOGGER.exception("Job execution failed", extra={"job_id": job_id})
span.set_attribute("error.type", type(error).__name__)
claimed.state = {**claimed.state, "error": str(error)}
status = JobStatus.FAILED
else:
status = JobStatus.FINISHED
span.set_attribute("inkcre.job.status", status.value)
await cls._close(claimed, status)
finally:
current_core().active_jobs.pop(job_id, None)
return True

@classmethod
async def expire_overdue(cls) -> int:
"""Use database time to close abandoned overdue running Jobs."""
"""Close overdue running Jobs after an operator verifies their execution has stopped.

This maintenance operation is deployment-wide. A deadline alone cannot tell
an ordinary worker whether another Peer is still releasing its resources.
"""
async with job_uow() as uow:
return await uow.jobs.expire_overdue()

@classmethod
async def check(cls) -> None:
"""Schedule locally eligible pending Jobs and converge running timeouts."""
"""Schedule locally eligible pending Jobs."""
if not current_core().accepting_jobs:
return
async with job_uow() as uow:
Expand All @@ -406,7 +412,6 @@ async def check(cls) -> None:
task.add_done_callback(
lambda finished, job_id=job.id: core.pending_jobs.pop(job_id, None)
)
await cls.expire_overdue()

@classmethod
async def _run_traced(cls, job_id: JobID) -> bool:
Expand Down
121 changes: 121 additions & 0 deletions tests/peer/integration/test_job_completion_ownership.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
"""Observe Job closure across independent Peers sharing a migrated PostgreSQL."""

import asyncio
import os

import pydantic
import pytest

from inkcre_core import Core
from inkcre_core.business.job import JobHandler, JobManager
from inkcre_core.schemas.job import JobModel, JobStatus


pytestmark = pytest.mark.skipif(
not os.getenv("INKCRE_TEST_DATABASE_URL"),
reason="requires an explicitly selected migrated PostgreSQL runtime",
)


class Parameters(pydantic.BaseModel):
pass


def test_discovery_leaves_timed_out_execution_running_until_cleanup(
async_runner, monkeypatch
):
# Each Core owns independent execution state and database connections.
async def check() -> None:
executor = Core(os.environ["INKCRE_TEST_DATABASE_URL"])
observer = Core(os.environ["INKCRE_TEST_DATABASE_URL"])
executor.accepting_jobs = observer.accepting_jobs = True
cleaning = asyncio.Event()
release = asyncio.Event()

class SlowCleanup(
JobHandler,
job_type="test.peer.job.slow_cleanup.v1",
description="Execution whose resources outlive its deadline",
parameters_model=Parameters,
default_timeout_seconds=1,
):
@classmethod
async def can_handle(cls, parameters: Parameters) -> bool:
return True

@classmethod
async def handle(cls, job: JobModel, parameters: Parameters) -> None:
try:
await asyncio.Event().wait()
finally:
cleaning.set()
await release.wait()
job.state = {"resources_released": True}

try:
with executor.bind():
await JobManager.sync_job_types()
submitted = await JobManager.create(SlowCleanup.type, {})
assert submitted.id is not None
running = asyncio.create_task(JobManager.run(submitted.id))
try:
await asyncio.wait_for(cleaning.wait(), timeout=8)
with observer.bind():
await JobManager.check()
during = await JobManager.get(submitted.id)
assert during is not None
assert (during.status, during.closed_at) == (JobStatus.RUNNING, None)
finally:
release.set()
assert await asyncio.wait_for(running, timeout=8)
with observer.bind():
after = await JobManager.get(submitted.id)
assert after is not None
assert after.status == JobStatus.TIMED_OUT
assert after.closed_at is not None
assert after.state == {"resources_released": True}
finally:
await executor.aclose()
await observer.aclose()

monkeypatch.setattr(JobManager, "_handlers", {})
async_runner.run(check())


def test_handler_timeout_is_failure_when_execution_budget_has_not_elapsed(
async_runner, monkeypatch
):
async def check() -> None:
executor = Core(os.environ["INKCRE_TEST_DATABASE_URL"])
executor.accepting_jobs = True

class OperationTimeout(
JobHandler,
job_type="test.peer.job.operation_timeout.v1",
description="Operation whose own timeout precedes the execution deadline",
parameters_model=Parameters,
default_timeout_seconds=60,
):
@classmethod
async def can_handle(cls, parameters: Parameters) -> bool:
return True

@classmethod
async def handle(cls, job: JobModel, parameters: Parameters) -> None:
raise TimeoutError("upstream operation timed out")

try:
with executor.bind():
await JobManager.sync_job_types()
submitted = await JobManager.create(OperationTimeout.type, {})
assert submitted.id is not None
assert await JobManager.run(submitted.id)
closed = await JobManager.get(submitted.id)
assert closed is not None
assert closed.status == JobStatus.FAILED
assert closed.state["error"] == "upstream operation timed out"
finally:
await executor.aclose()

monkeypatch.setattr(JobManager, "_handlers", {})
async_runner.run(check())