joeyutong commented on code in PR #1382:
URL: https://github.com/apache/flink-agents/pull/1382#discussion_r4677737061


##########
api/src/main/java/org/apache/flink/agents/api/media/AsyncJobModel.java:
##########
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.agents.api.media;
+
+import javax.annotation.Nullable;
+
+import java.time.Duration;
+
+/**
+ * Orthogonal contract implemented by media capabilities backed by resumable 
provider-side jobs.
+ *
+ * <p>Synchronous setups implement only the task-specific setup base class 
(such as {@link
+ * BaseSpeechSynthesisModelSetup} or {@link BaseImageGenerationModelSetup}) 
and do not implement
+ * this interface.
+ *
+ * <p>When a Python-backed async capability is reached across the 
Java-to-Python bridge, the
+ * provider owns {@link #submit(Object)}, single-observation {@link 
#fetch(MediaJob)}, {@link
+ * #cancel(MediaJob)}, and job-ownership validation, while convenience methods 
compose {@code
+ * submit()} + {@code wait()} and the Java bridge drives interruptible polling 
over those primitives
+ * using {@link #DEFAULT_WAIT_TIMEOUT} and {@link #DEFAULT_POLL_INTERVAL}. 
Native Java {@code
+ * AsyncJobModel} implementations supply three-argument {@link #wait(MediaJob, 
Duration, Duration)}
+ * directly.
+ */
+public interface AsyncJobModel<Req, Res extends MediaResult<?>> {
+    /** Default polling budget used by {@link #wait(MediaJob)}. */
+    Duration DEFAULT_WAIT_TIMEOUT = Duration.ofMinutes(30);
+
+    /** Default interval between job status queries. */
+    Duration DEFAULT_POLL_INTERVAL = Duration.ofSeconds(5);
+
+    /** Submit a request and return a durable job handle without waiting. */
+    MediaJob submit(Req request);
+
+    /** Query once, retrieving the typed result when the job has succeeded. */
+    MediaJobState<Res> fetch(MediaJob job);
+
+    /** Wait using {@link #DEFAULT_WAIT_TIMEOUT} and {@link 
#DEFAULT_POLL_INTERVAL}. */
+    default Res wait(MediaJob job) {
+        return wait(job, DEFAULT_WAIT_TIMEOUT);
+    }
+
+    /**
+     * Poll until completion using {@link #DEFAULT_POLL_INTERVAL}. Pass {@code 
null} for unlimited
+     * polling.
+     */
+    default Res wait(MediaJob job, @Nullable Duration timeout) {
+        return wait(job, timeout, DEFAULT_POLL_INTERVAL);
+    }
+
+    /**
+     * Poll until completion. Pass {@code null} timeout for unlimited polling. 
The budget limits
+     * when a new query can start; an in-flight query may return after it 
expires.
+     *
+     * @param job durable job handle returned by {@link #submit(Object)}
+     * @param timeout non-negative polling budget, or {@code null} for 
unlimited polling
+     * @param pollInterval positive delay between status queries
+     * @throws MediaJobException if the job ends without a successful result
+     * @throws MediaJobTimeoutException if the polling budget expires; the job 
remains queryable
+     */
+    Res wait(MediaJob job, @Nullable Duration timeout, Duration pollInterval);

Review Comment:
   Done. Added a default 3-argument `wait()` implementation on `AsyncJobModel` 
(backed by package-private `AsyncJobPolling`) polling via `fetch(job)` while 
preserving cancellation/interruption semantics (stopping local wait without 
canceling the remote job or persisting cancellation as a job failure).



##########
python/flink_agents/api/media/media_model.py:
##########
@@ -0,0 +1,668 @@
+################################################################################
+#  Licensed to the Apache Software Foundation (ASF) under one
+#  or more contributor license agreements.  See the NOTICE file
+#  distributed with this work for additional information
+#  regarding copyright ownership.  The ASF licenses this file
+#  to you under the Apache License, Version 2.0 (the
+#  "License"); you may not use this file except in compliance
+#  with the License.  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+# limitations under the License.
+#################################################################################
+import json
+import math
+import time
+from abc import ABC, abstractmethod
+from enum import Enum
+from typing import TYPE_CHECKING, Any, ClassVar, Generic, Mapping, Sequence, 
TypeVar
+
+from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, field_validator
+from typing_extensions import override
+
+from flink_agents.api.chat_message import (
+    AudioBlock,
+    DataContentBlock,
+    DocumentBlock,
+    ImageBlock,
+    TextBlock,
+    VideoBlock,
+)
+from flink_agents.api.resource import Resource, ResourceType
+
+if TYPE_CHECKING:
+    from flink_agents.api.media.media_model_provider import 
BaseMediaModelProvider
+
+
+class _MediaTask(str, Enum):
+    """Internal identifiers for job validation and cross-language dispatch."""
+
+    IMAGE_GENERATION = "image_generation"
+    VIDEO_GENERATION = "video_generation"
+    TRANSCRIPTION = "transcription"
+    SPEECH_SYNTHESIS = "speech_synthesis"
+
+
+class MediaJobStatus(str, Enum):
+    """Lifecycle state of a submitted asynchronous provider task."""
+
+    PENDING = "pending"
+    RUNNING = "running"
+    SUCCEEDED = "succeeded"
+    FAILED = "failed"
+    CANCELED = "canceled"
+    # The provider can no longer identify the task, for example because its
+    # retention window has passed.
+    UNKNOWN = "unknown"
+
+
+class MediaJob(BaseModel):
+    """Handle of a submitted asynchronous provider task.
+
+    Frozen and JSON-serializable so it can be persisted as the result of a
+    durable execution and replayed across recovery.
+    """
+
+    model_config = ConfigDict(frozen=True, extra="forbid")
+
+    provider: str = Field(description="Provider that owns the task, e.g. 
'dashscope'.")
+    model: str = Field(description="Model the task was submitted to.")
+    task: str = Field(description="Capability identifier recorded when 
submitting.")
+    job_id: str = Field(description="Provider task identifier.")
+    submitted_at_ms: int = Field(description="Local submission time, epoch 
millis.")
+    expires_at_ms: int | None = Field(
+        default=None,
+        description="Time until which the provider can still be queried for 
this task.",
+    )
+
+    @field_validator("task")
+    @classmethod
+    def _validate_task(cls, value: str) -> str:
+        expected = tuple(task.value for task in _MediaTask)
+        if value not in expected:
+            msg = (
+                f"Invalid media task {value!r}; expected one of: {', 
'.join(expected)}."
+            )
+            raise ValueError(msg)
+        return value
+
+
+ContentT = TypeVar("ContentT", bound=DataContentBlock)
+
+
+class MediaResult(BaseModel, Generic[ContentT]):
+    """Output of a finished generation, transcription, or synthesis."""
+
+    model_config = ConfigDict(frozen=True, extra="forbid")
+
+    content: list[ContentT] = Field(
+        description="Generated content, in the order returned by the provider."
+    )
+    expires_at_ms: int | None = Field(
+        default=None,
+        description="Time until which result URLs stay valid, when the 
provider says so.",
+    )
+    usage: dict[str, int | float | str] = Field(
+        default_factory=dict,
+        description="Provider usage counters, kept as reported.",
+    )
+    request_id: str | None = Field(
+        default=None, description="Provider request identifier."
+    )
+    metadata: dict[str, Any] = Field(
+        default_factory=dict,
+        description="Structured provider data that does not fit into a content 
block.",
+    )
+
+
+ResultT = TypeVar("ResultT", bound=MediaResult)
+
+
+class MediaJobState(BaseModel, Generic[ResultT]):
+    """One observation of a job, returned by ``fetch``."""
+
+    model_config = ConfigDict(frozen=True, extra="forbid")
+
+    job: MediaJob
+    status: MediaJobStatus
+    result: ResultT | None = Field(
+        default=None, description="Present only when the status is SUCCEEDED."
+    )
+    error_code: str | None = Field(
+        default=None, description="Present only when the status is FAILED."
+    )
+    error_message: str | None = None
+
+
+class MediaJobError(Exception):
+    """An operation on a media job failed.
+
+    Attributes:
+        job: The job associated with the error.
+        status: The last observed job status, or UNKNOWN if unavailable.
+        code: Provider error code, when the provider reported one.
+        message: Provider error message, when the provider reported one.
+    """
+
+    def __init__(
+        self,
+        job: MediaJob,
+        status: MediaJobStatus,
+        code: str | None = None,
+        message: str | None = None,
+    ) -> None:
+        """Record the job, its observed status, and any provider error."""
+        self.job = job
+        self.status = status
+        self.code = code
+        self.message = message
+        detail = status.value
+        if code is not None:
+            detail = f"{detail} ({code})"
+        if message is not None:
+            detail = f"{detail}: {message}"
+        super().__init__(f"Media job {job.job_id}: {detail}")
+
+    def __reduce__(self) -> tuple[type[Exception], tuple[Any, ...], dict[str, 
Any]]:
+        """Rebuild the exception with its structured constructor arguments."""
+        return type(self), (self.job, self.status, self.code, self.message), 
vars(self)
+
+
+class MediaJobTimeoutError(MediaJobError):
+    """The polling budget for ``wait`` elapsed before a terminal status was 
observed.
+
+    Attributes:
+        timeout: The polling budget in seconds.
+    """
+
+    def __init__(
+        self,
+        job: MediaJob,
+        timeout: float,
+        status: MediaJobStatus = MediaJobStatus.UNKNOWN,
+    ) -> None:
+        """Record the job, its last observed status, and the polling budget."""
+        self.timeout = timeout
+        super().__init__(job, status, message=f"timed out after {timeout} 
seconds")
+
+    def __reduce__(self) -> tuple[type[Exception], tuple[Any, ...], dict[str, 
Any]]:
+        """Rebuild the timeout with its job, budget, and last observed 
status."""
+        return type(self), (self.job, self.timeout, self.status), vars(self)
+
+
+DEFAULT_WAIT_TIMEOUT = 1800.0
+DEFAULT_POLL_INTERVAL = 5.0
+
+
+class AsyncJobModel(Generic[ResultT], ABC):
+    """A media capability with submitted jobs that can be queried and resumed.
+
+    Setups that back a media capability with cloud jobs implement this
+    interface alongside their ``Base*ModelSetup`` base class and own 
``submit``,
+    single-observation ``fetch``, ``cancel``, and job-ownership validation
+    (``_check_job``). Python convenience methods compose ``_submit_and_wait``,
+    and Java-to-Python bridges compose those same primitives with interruptible
+    polling using ``DEFAULT_WAIT_TIMEOUT`` and ``DEFAULT_POLL_INTERVAL``.
+    Native Java ``AsyncJobModel`` implementations supply three-argument 
``wait``
+    directly. Synchronous setups extend only the task-specific setup base 
class.
+
+    Call ``submit`` and persist its returned job separately when waiting must
+    resume after recovery. None of these methods records durable execution or
+    emits events itself.
+    """
+
+    if TYPE_CHECKING:
+        model: str
+        _task: ClassVar[_MediaTask]
+
+    def _submit_and_wait(
+        self,
+        *args: Any,
+        timeout: float | None = None,
+        **kwargs: Any,
+    ) -> ResultT:
+        """Submit a request and wait for its result.
+
+        Args:
+            *args: The inputs accepted by this media capability.
+            timeout: Polling budget in seconds after submission. None uses
+                ``DEFAULT_WAIT_TIMEOUT``. This does not change HTTP request
+                timeouts.
+            **kwargs: Provider parameters for submission.
+        """
+        budget = DEFAULT_WAIT_TIMEOUT if timeout is None else timeout
+        budget = self._validate_wait_timeout(budget, allow_zero=False)
+        job = self.submit(*args, **kwargs)
+        return self.wait(job, timeout=budget)
+
+    @abstractmethod
+    def submit(self, *args: Any, **kwargs: Any) -> MediaJob:
+        """Submit a request and return its job handle without waiting."""
+
+    @abstractmethod
+    def fetch(self, job: MediaJob) -> MediaJobState[ResultT]:
+        """Query the task status once.
+
+        Retrieve the full result when the status is SUCCEEDED.
+        """
+
+    def wait(
+        self,
+        job: MediaJob,
+        *,
+        timeout: float | None = DEFAULT_WAIT_TIMEOUT,
+        poll_interval: float = DEFAULT_POLL_INTERVAL,
+    ) -> ResultT:
+        """Block until the task reaches a terminal status.
+
+        Waits up to ``poll_interval`` seconds between queries. The polling
+        budget limits when a new query can start. A query already in progress
+        can finish and return its result. On timeout ``MediaJobTimeoutError``
+        is raised and the provider task can continue.
+
+        Args:
+            job: Handle returned by ``submit``.
+            timeout: Polling budget in seconds from the start of this wait.
+                Defaults to ``DEFAULT_WAIT_TIMEOUT`` (1800s). Pass ``None`` for
+                unlimited polling.
+            poll_interval: Positive seconds between status queries. Defaults to
+                ``DEFAULT_POLL_INTERVAL`` (5s).
+
+        Raises:
+            MediaJobError: The task ended as FAILED, CANCELED, or UNKNOWN.
+            MediaJobTimeoutError: The polling budget elapsed with no terminal 
result.
+            TypeError: ``timeout`` or ``poll_interval`` has an invalid type.
+            ValueError: ``timeout`` is negative/non-finite or 
``poll_interval`` is
+                non-positive/non-finite.
+        """
+        started_at = time.monotonic()
+        self._check_job(job)
+        wait_timeout = self._validate_wait_timeout(timeout, allow_zero=True)
+        interval = self._validate_poll_interval(poll_interval)
+        status = MediaJobStatus.UNKNOWN
+        while True:
+            if (
+                wait_timeout is not None
+                and time.monotonic() - started_at >= wait_timeout
+            ):
+                raise MediaJobTimeoutError(job, wait_timeout, status)
+            state = self.fetch(job)
+            status = state.status
+            if status is MediaJobStatus.SUCCEEDED:
+                if state.result is None:
+                    msg = f"Media job {job.job_id} succeeded without a result."
+                    raise MediaJobError(job, status, message=msg)
+                return state.result
+            if status in (
+                MediaJobStatus.FAILED,
+                MediaJobStatus.CANCELED,
+                MediaJobStatus.UNKNOWN,
+            ):
+                raise MediaJobError(job, status, state.error_code, 
state.error_message)
+            delay = interval
+            if wait_timeout is not None:
+                elapsed = time.monotonic() - started_at
+                delay = min(delay, wait_timeout - elapsed)
+            if delay > 0:
+                time.sleep(delay)
+
+    @abstractmethod
+    def cancel(self, job: MediaJob) -> None:
+        """Request cancellation of a task.
+
+        Providers that can only cancel queued tasks raise ``MediaJobError`` for
+        any other status.
+        """
+
+    @staticmethod
+    def _validate_wait_timeout(

Review Comment:
   Done. Merged into `validate_positive_seconds()` (rejecting 
zero/non-positive/non-finite values) and aligned Java timeout/poll-interval 
validation to reject `<= 0` consistently, validating before submission in 
`_submit_and_wait()` and in standalone `wait()`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to