From 6054eaba2927b6f77dc567599d0d8adcbacafc00 Mon Sep 17 00:00:00 2001 From: Lan_zhijiang Date: Sat, 28 Nov 2026 22:17:18 +0800 Subject: [PATCH] =?UTF-8?q?fix(core):=20=E7=94=B1=E6=89=A7=E8=A1=8C=20Job?= =?UTF-8?q?=20=E7=9A=84=20Peer=20=E5=86=99=E5=85=A5=E7=BB=88=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .changes/job-closure-ownership.fixed.md | 1 + docs/40-deployment/runtime-orchestration.md | 2 + inkcre_core/business/job.py | 77 +++++------ .../test_job_completion_ownership.py | 121 ++++++++++++++++++ 4 files changed, 165 insertions(+), 36 deletions(-) create mode 100644 .changes/job-closure-ownership.fixed.md create mode 100644 tests/peer/integration/test_job_completion_ownership.py diff --git a/.changes/job-closure-ownership.fixed.md b/.changes/job-closure-ownership.fixed.md new file mode 100644 index 00000000..a1b28bb1 --- /dev/null +++ b/.changes/job-closure-ownership.fixed.md @@ -0,0 +1 @@ +保持仍在释放资源的 Job 为运行中,由实际执行者发布终态。单个处理操作提前超时会记录为失败,并保留原因。 diff --git a/docs/40-deployment/runtime-orchestration.md b/docs/40-deployment/runtime-orchestration.md index 8c91f298..92754228 100644 --- a/docs/40-deployment/runtime-orchestration.md +++ b/docs/40-deployment/runtime-orchestration.md @@ -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。 diff --git a/inkcre_core/business/job.py b/inkcre_core/business/job.py index 2459a0ce..874e3d2a 100644 --- a/inkcre_core/business/job.py +++ b/inkcre_core/business/job.py @@ -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: @@ -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: diff --git a/tests/peer/integration/test_job_completion_ownership.py b/tests/peer/integration/test_job_completion_ownership.py new file mode 100644 index 00000000..14465489 --- /dev/null +++ b/tests/peer/integration/test_job_completion_ownership.py @@ -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())