diff --git a/src/twinkle/protocol/types/lifecycle.py b/src/twinkle/protocol/types/lifecycle.py index 799c2b38b..cfa2317f2 100644 --- a/src/twinkle/protocol/types/lifecycle.py +++ b/src/twinkle/protocol/types/lifecycle.py @@ -96,3 +96,4 @@ class TaskEnvelope(ResponseModel): queue_state: QueueState | None = None queue_state_reason: str | None = None progress: UploadProgress | None = None + execution_finished: bool | None = None # tracked backend work has stopped diff --git a/src/twinkle/protocol/types/sampler.py b/src/twinkle/protocol/types/sampler.py index 46109cd27..db8381a4d 100644 --- a/src/twinkle/protocol/types/sampler.py +++ b/src/twinkle/protocol/types/sampler.py @@ -17,7 +17,8 @@ """ from __future__ import annotations -from pydantic import Field, JsonValue +from hmac import digest +from pydantic import UUID4, Field, JsonValue from typing import Any, Dict, List, Literal, Optional, Tuple from .base import ResponseModel, StrictRequest, passthrough @@ -38,11 +39,18 @@ class SampleRequest(StrictRequest): inputs: WireInputBatch = Field(..., description='Trajectory or InputFeature entries to sample from') sampling_params: dict[str, JsonValue] | None = Field( None, description='Sampling parameters (max_tokens, temperature, num_samples, etc.)') + client_sample_id: UUID4 | None = None adapter_name: str = Field('', description='Adapter name for LoRA inference') adapter_uri: str | None = Field(None, description='Adapter URI (twinkle:// path or local path) for LoRA inference') token_only: bool = Field( False, description='Return sampled tokens/logprobs only; encoded inputs are engine ids, media alongside') + def tracked_request_id(self, token: str) -> str | None: + if self.client_sample_id is None: + return None + identity = digest(token.encode(), self.client_sample_id.bytes, 'sha256') + return f'req_sample_{identity.hex()}' + class SampledSequenceModel(ResponseModel): """A single sampled sequence, mirroring twinkle.data_format.SampledSequence.""" diff --git a/src/twinkle/server/lifecycle/envelope.py b/src/twinkle/server/lifecycle/envelope.py index 64714d972..8fab006cb 100644 --- a/src/twinkle/server/lifecycle/envelope.py +++ b/src/twinkle/server/lifecycle/envelope.py @@ -59,6 +59,7 @@ def envelope_from_record( queue_state=record.get('queue_state'), queue_state_reason=record.get('queue_state_reason'), progress=record.get('progress'), + execution_finished=record.get('execution_finished'), ) if status in ('failed', 'cancelled'): return TaskEnvelope( diff --git a/src/twinkle/server/sampler/twinkle_handlers.py b/src/twinkle/server/sampler/twinkle_handlers.py index 29a82e016..5807ca29b 100644 --- a/src/twinkle/server/sampler/twinkle_handlers.py +++ b/src/twinkle/server/sampler/twinkle_handlers.py @@ -9,6 +9,7 @@ from __future__ import annotations import asyncio +import hashlib import json import uuid from collections.abc import Callable, Mapping @@ -277,12 +278,24 @@ async def generate(adapter_path): # Calculate metrics for queue scheduling. The body is wire-validated, so the # entries are models and ``input_ids`` is absent or a list of ints. input_tokens = sum(len(getattr(entry, 'input_ids', None) or ()) for entry in body.inputs) - return await self.submit_concurrent_and_peek( + request_id = body.tracked_request_id(token) + schedule = {} + if request_id is not None: + fingerprint = hashlib.sha256(f'{request.url.path}\n{body.model_dump_json()}'.encode()).hexdigest() + schedule = dict(request_id=request_id, submission_fingerprint=fingerprint, track_execution=True) + + reply = await self.submit_concurrent_and_peek( _task, token=token, input_tokens=input_tokens, task_type='sample', - execution_scope=request_execution_scope(request)) + execution_scope=request_execution_scope(request), + **schedule) + if request_id is not None: + record = await self.state.get_future(request_id) + if record is not None and record.get('submission_fingerprint') != fingerprint: + raise RequestRejectedError('client_sample_id is already bound to a different sampler request') + return reply @app.post('/twinkle/sample_to_data_plane', response_model=types.TaskEnvelope) async def sample_to_data_plane( diff --git a/src/twinkle/server/state/future_manager.py b/src/twinkle/server/state/future_manager.py index effc9ca54..47ab80532 100644 --- a/src/twinkle/server/state/future_manager.py +++ b/src/twinkle/server/state/future_manager.py @@ -122,6 +122,12 @@ def report_progress(existing: dict | None, *, progress: dict) -> dict | None: snapshot = {**progress, 'sequence': previous.get('sequence', 0) + 1} return {**existing, 'progress': snapshot} + @staticmethod + def finish_execution(existing: dict | None) -> dict | None: + if existing is None or existing.get('execution_finished') is not False: + return None + return {**existing, 'execution_finished': True} + @staticmethod def cancel(existing: dict | None, *, failure: dict, now: str) -> dict | None: """Atomic transform: cancel iff the task has not started (pending/queued). @@ -227,6 +233,9 @@ async def report_progress(self, request_id: str, progress: dict[str, Any]) -> No await self._backend.update_atomic( self._make_key(request_id), functools.partial(FutureTransitions.report_progress, progress=progress)) + async def mark_execution_finished(self, request_id: str) -> None: + await self._backend.update_atomic(self._make_key(request_id), FutureTransitions.finish_execution) + async def cancel_if_pending(self, request_id: str) -> str | None: """Cancel a task iff it has not started; return the resulting status. diff --git a/src/twinkle/server/state/models.py b/src/twinkle/server/state/models.py index 8fb693e41..112509217 100644 --- a/src/twinkle/server/state/models.py +++ b/src/twinkle/server/state/models.py @@ -83,6 +83,7 @@ class FutureRecord(BaseModel): queue_state_reason: str | None = None progress: dict[str, Any] | None = None submission_fingerprint: str | None = None + execution_finished: bool | None = None # Replica ownership and deadline are fixed when the record is created. replica_id: str | None = None absolute_deadline: float | None = None diff --git a/src/twinkle/server/state/server_state.py b/src/twinkle/server/state/server_state.py index 150ee0325..b0e49b814 100644 --- a/src/twinkle/server/state/server_state.py +++ b/src/twinkle/server/state/server_state.py @@ -467,6 +467,9 @@ async def report_future_progress(self, request_id: str, progress: dict[str, Any] async def create_pending_future(self, request_id: str, **fields: Any) -> bool: return await self._future_mgr.create_pending(request_id, **fields) + async def mark_future_execution_finished(self, request_id: str) -> None: + await self._future_mgr.mark_execution_finished(request_id) + async def assert_future_owner(self, request_id: str, token: str) -> None: record = await self._future_mgr.get(request_id) owner = record.owner_token if record is not None else None diff --git a/src/twinkle/server/task_queue/mixin.py b/src/twinkle/server/task_queue/mixin.py index 9f46439f8..dde063896 100644 --- a/src/twinkle/server/task_queue/mixin.py +++ b/src/twinkle/server/task_queue/mixin.py @@ -357,6 +357,7 @@ async def schedule_concurrent_task( request_id: str | None = None, execution_scope: ExecutionScope | None = None, submission_fingerprint: str | None = None, + track_execution: bool = False, ) -> dict[str, Any]: """Schedule a compute task that runs now instead of in serial order. @@ -386,7 +387,8 @@ async def schedule_concurrent_task( self._queue_key(model_id=model_id, token=token), replica_id=getattr(self, 'replica_id', None), absolute_deadline=self._future_deadline(), - submission_fingerprint=submission_fingerprint) + submission_fingerprint=submission_fingerprint, + track_execution=track_execution) if started: logger.info(f'[TaskQueue] Task {request_id} started concurrently, type={task_type or "unknown"}, ' f'model_id={model_id}, input_tokens={input_tokens}') @@ -400,7 +402,18 @@ async def schedule_concurrent_task( async def submit_concurrent_and_peek(self, coro_factory: Callable[[], Coroutine], **schedule_kwargs) -> TaskEnvelope: """Concurrent compute submission with the existing Twinkle future envelope.""" - ref = await self.schedule_concurrent_task(coro_factory, **schedule_kwargs) + admission = self.schedule_concurrent_task(coro_factory, **schedule_kwargs) + if schedule_kwargs.get('track_execution'): + # Once the tracked request is admitted it must be queryable even if the POST disconnects. + submission = asyncio.create_task(admission) + try: + ref = await asyncio.shield(submission) + except asyncio.CancelledError: + self._queue_tasks.add(submission) + submission.add_done_callback(self._queue_task_done) + raise + else: + ref = await admission return await self._peek_terminal(ref['request_id'], fallback_status='pending') async def _peek_terminal(self, request_id: str, *, fallback_status: str) -> TaskEnvelope: diff --git a/src/twinkle/server/task_queue/worker.py b/src/twinkle/server/task_queue/worker.py index d03e234f7..8954766e9 100644 --- a/src/twinkle/server/task_queue/worker.py +++ b/src/twinkle/server/task_queue/worker.py @@ -349,7 +349,8 @@ async def _execute_task(self, task: QueuedTask, queue_key: str, q: asyncio.Queue q.task_done() async def submit_detached(self, task: QueuedTask, queue_key: str, *, replica_id: str | None, - absolute_deadline: float, submission_fingerprint: str | None = None) -> bool: + absolute_deadline: float, submission_fingerprint: str | None = None, + track_execution: bool = False) -> bool: """Own admission, future persistence and startup as one lifecycle.""" self.reserve_detached() wrote_status = False @@ -360,6 +361,8 @@ async def submit_detached(self, task: QueuedTask, queue_key: str, *, replica_id: replica_id=replica_id, absolute_deadline=absolute_deadline, owner_token=task.token) + if track_execution: + fields['execution_finished'] = False if submission_fingerprint is None: await self._state.store_future_status(task.request_id, TaskStatus.PENDING.value, **fields) elif not await self._state.create_pending_future( @@ -367,7 +370,7 @@ async def submit_detached(self, task: QueuedTask, queue_key: str, *, replica_id: self.release_detached() return False wrote_status = True - self.run_detached(task, queue_key) + self.run_detached(task, queue_key, track_execution=track_execution) return True except BaseException: self.release_detached() @@ -389,7 +392,7 @@ def reserve_detached(self) -> None: def release_detached(self) -> None: self._detached_reserved -= 1 - def run_detached(self, task: QueuedTask, queue_key: str) -> None: + def run_detached(self, task: QueuedTask, queue_key: str, *, track_execution: bool = False) -> None: """Start ``task`` now, beside the serial loop instead of in its turn. For backends that batch concurrent requests themselves (vLLM). The task @@ -425,6 +428,8 @@ async def run(): break if not execution.cancelled(): execution.exception() + if track_execution: + await self._state.mark_future_execution_finished(task.request_id) running = asyncio.create_task(run()) self._detached_tasks[running] = task diff --git a/src/twinkle_client/_future.py b/src/twinkle_client/_future.py index a4af80791..37c417cd7 100644 --- a/src/twinkle_client/_future.py +++ b/src/twinkle_client/_future.py @@ -126,6 +126,7 @@ def resolve( total_timeout: float = _DEFAULT_TOTAL_TIMEOUT, transport: ClientTransport | None = None, on_progress: Callable[[UploadProgress], None] | None = None, + on_terminal: Callable[[TaskEnvelope], None] | None = None, ) -> Any: """Block until ``submit``'s task reaches a terminal state, then return its result. @@ -146,9 +147,14 @@ def report_progress(envelope: TaskEnvelope) -> None: cursor = progress.sequence on_progress(progress) + def unwrap(envelope: TaskEnvelope): + if on_terminal is not None: + on_terminal(envelope) + return _unwrap(envelope, model_cls) + if submit.status in TERMINAL_STATUSES: report_progress(submit) - return _unwrap(submit, model_cls) # same call as the retrieve path + return unwrap(submit) resolved_transport = capture_transport(transport) deadline = time.monotonic() + total_timeout @@ -186,7 +192,7 @@ def report_progress(envelope: TaskEnvelope) -> None: continue report_progress(reply) if reply.status in TERMINAL_STATUSES: - return _unwrap(reply, model_cls) # same call as the submit path + return unwrap(reply) _log_queue_state(reply) poll_request_id = uuid.uuid4().hex except (KeyboardInterrupt, SystemExit): @@ -209,3 +215,36 @@ def resolve_response( # Older servers reject unknown retrieve fields and omit progress in submit replies. on_progress=on_progress if 'progress' in payload else None, ) + + +def submit_tracked_task(transport, url, body, model_cls, on_outcome_unknown, *, request_id=None): + """Notify the caller only when a submitted task may still be running.""" + try: + response = transport.post_model(url, body) + except (requests.ConnectTimeout, requests.exceptions.InvalidHeader, requests.exceptions.InvalidURL, + requests.exceptions.InvalidSchema, requests.exceptions.MissingSchema): + raise + except requests.HTTPError as exc: + status = _status_of(exc) + if status is None or status in (408, 499) or status >= 500: + on_outcome_unknown(request_id) + raise + except (requests.RequestException, KeyboardInterrupt, SystemExit): + on_outcome_unknown(request_id) + raise + + def record_terminal(envelope): + if envelope.status == 'failed' and envelope.execution_finished is False: + on_outcome_unknown(envelope.request_id) + + try: + submit = TaskEnvelope.model_validate(response.json()) + request_id = submit.request_id + result = resolve(submit, model_cls=None, transport=transport, on_terminal=record_terminal) + except (TaskFailedError, TaskCancelledError): + raise + except BaseException: + on_outcome_unknown(request_id) + raise + # Response-model validation is local. The remote operation has ended. + return model_cls.model_validate(result) if model_cls is not None else result diff --git a/src/twinkle_client/manager.py b/src/twinkle_client/manager.py index 85323e6dd..58ce6dbfd 100644 --- a/src/twinkle_client/manager.py +++ b/src/twinkle_client/manager.py @@ -416,6 +416,14 @@ def get_checkpoint_twinkle_path(self, run_id: str, checkpoint_id: str) -> str: """ return self.get_checkpoint_path(run_id, checkpoint_id).twinkle_path + def retrieve_task(self, request_id: str): + """Retrieve a task envelope with a short, bounded wait for reconciliation.""" + from twinkle.protocol.types.lifecycle import TaskEnvelope + + response = self._transport.post(self._get_url('/retrieve_future'), json_data={'request_id': request_id}, + timeout=2) + return TaskEnvelope.model_validate(response.json()) + def delete_checkpoint(self, run_id: str, checkpoint_id: str) -> DeleteCheckpointResponse: """ Delete a checkpoint. diff --git a/src/twinkle_client/rollout/_http_sampler.py b/src/twinkle_client/rollout/_http_sampler.py index 47e80d32d..04fe06d5c 100644 --- a/src/twinkle_client/rollout/_http_sampler.py +++ b/src/twinkle_client/rollout/_http_sampler.py @@ -3,6 +3,8 @@ from __future__ import annotations import base64 import threading +from contextlib import nullcontext +from functools import partial from io import BytesIO from typing import Any, Dict, List, Optional @@ -30,6 +32,8 @@ def __init__(self, sampler, template, *, adapter_name: str = ''): self.template = template self.adapter_name = adapter_name self.adapter_path: Optional[str] = None + self.adapter_lease = None + self.on_adapter_task_unknown = None def sample(self, inputs: Any, @@ -42,9 +46,13 @@ def sample(self, del session_id if adapter_path and use_base_model: raise ValueError('adapter_path and use_base_model=True ask for opposite weights.') - adapter_uri = None if use_base_model else (adapter_path or self.adapter_path) items = inputs if isinstance(inputs, list) else [inputs] - return [self._sample_one(item, sampling_params, adapter_uri) for item in items] + if self.adapter_lease is not None and not use_base_model: + scope = self.adapter_lease(adapter_path or None) + else: + scope = nullcontext(None if use_base_model else (adapter_path or self.adapter_path)) + with scope as adapter_uri: + return [self._sample_one(item, sampling_params, adapter_uri) for item in items] def _sample_one(self, item: Any, sampling_params: Any, adapter_uri: Optional[str]) -> SampleResponse: media = getattr(item, 'media', None) @@ -52,8 +60,12 @@ def _sample_one(self, item: Any, sampling_params: Any, adapter_uri: Optional[str entry = {'input_ids': list(item.engine_input_ids), **_wire_media(media)} else: entry = dict(getattr(item, 'feature', item)) + options = {} + if adapter_uri is not None and self.on_adapter_task_unknown is not None: + options['on_outcome_unknown'] = partial(self.on_adapter_task_unknown, adapter_uri) responses = self.sampler.sample( - [entry], sampling_params, adapter_name=self.adapter_name, adapter_uri=adapter_uri, token_only=bool(media)) + [entry], sampling_params, adapter_name=self.adapter_name, adapter_uri=adapter_uri, + token_only=bool(media), **options) if len(responses) != 1: raise RuntimeError(f'the server returned {len(responses)} responses for one prompt.') response = responses[0] diff --git a/src/twinkle_client/sampler/vllm_sampler.py b/src/twinkle_client/sampler/vllm_sampler.py index 7d93c4cdc..5bc888df4 100644 --- a/src/twinkle_client/sampler/vllm_sampler.py +++ b/src/twinkle_client/sampler/vllm_sampler.py @@ -1,6 +1,7 @@ import asyncio from dataclasses import asdict from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union +from uuid import uuid4 from twinkle.data_format import InputFeature, SamplingParams, Trajectory from twinkle.protocol.json_utils import json_safe @@ -86,6 +87,7 @@ def sample( session_id: Optional[str] = None, num_samples: int = 1, token_only: bool = False, + on_outcome_unknown=None, ) -> List[SampleResponseModel]: """Sample from the model. @@ -111,15 +113,18 @@ def sample( """ if adapter_uri is None: adapter_uri = adapter_path if adapter_path is not None else getattr(self, 'adapter_uri', None) - response = self._transport.post_model( - f'{self.server_url}/sample', - build_request( - SampleRequest, - inputs=_json_safe(inputs), - sampling_params=self._sampling_params(sampling_params, num_samples), - adapter_name=adapter_name, - adapter_uri=adapter_uri, - token_only=token_only)) + url = f'{self.server_url}/sample' + body = build_request( + SampleRequest, inputs=_json_safe(inputs), sampling_params=self._sampling_params(sampling_params, num_samples), + adapter_name=adapter_name, adapter_uri=adapter_uri, token_only=token_only, + client_sample_id=uuid4() if on_outcome_unknown is not None else None) + if on_outcome_unknown is not None: + from twinkle_client._future import submit_tracked_task + + request_id = body.tracked_request_id(self._transport.context.api_key) + return submit_tracked_task( + self._transport, url, body, SampleResponseModelList, on_outcome_unknown, request_id=request_id).samples + response = self._transport.post_model(url, body) return self._await_task(response, SampleResponseModelList).samples @staticmethod diff --git a/tests/server/task_queue/test_task_queue_mixin.py b/tests/server/task_queue/test_task_queue_mixin.py index e2f111e66..e0538ffa1 100644 --- a/tests/server/task_queue/test_task_queue_mixin.py +++ b/tests/server/task_queue/test_task_queue_mixin.py @@ -755,3 +755,49 @@ async def work(): envelope = envelope_from_record(ref['request_id'], record) assert envelope.error.error_code == 503 assert envelope.error.category == 'server' + + +@pytest.mark.asyncio +async def test_tracked_sampler_failure_remains_unsettled_until_execution_exits(make_concurrent_queue): + from tests.server.state.fake_backend import FakeBackend + from twinkle.server.state.future_manager import FutureManager + + class State(FutureManager): + + async def get_future(self, request_id): + record = await self.get(request_id) + return record.model_dump() if record is not None else None + + create_pending_future = FutureManager.create_pending + store_future_status = FutureManager.store_status + try_start_future = FutureManager.try_start + mark_future_execution_finished = FutureManager.mark_execution_finished + + queue = make_concurrent_queue(TaskQueueConfig(execution_timeout=0.05, inline_fast_path_timeout=0.2)) + queue.state = State(FakeBackend(), expiration_timeout=300) + queue._compute_worker._state = queue.state + cancelled = asyncio.Event() + release = asyncio.Event() + + async def work(): + try: + await asyncio.Future() + except asyncio.CancelledError: + cancelled.set() + await release.wait() + raise + + try: + reply = await queue.submit_concurrent_and_peek( + work, token='token1', task_type='sample', request_id='req_sample_known', + submission_fingerprint='sample', track_execution=True) + assert reply.status == 'failed' and reply.execution_finished is False + await asyncio.wait_for(cancelled.wait(), 1) + assert (await queue.state.get('req_sample_known')).execution_finished is False + finally: + release.set() + for _ in range(100): + if (await queue.state.get('req_sample_known')).execution_finished is True: + break + await asyncio.sleep(0.01) + assert (await queue.state.get('req_sample_known')).execution_finished is True