Skip to content

[FEATURE] Language-neutral query job lifecycle - #5818

Merged
penghuo merged 1 commit into
opensearch-project:mainfrom
penghuo:feat/query-job-lifecycle-mvp
Sep 29, 2026
Merged

penghuo merged 1 commit into
opensearch-project:mainfrom
penghuo:feat/query-job-lifecycle-mvp

Conversation

@penghuo

@penghuo penghuo commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Introduces org.opensearch.sql.job — a language-neutral, engine-neutral query job lifecycle that PPL, SQL, and analytics-engine can all sit behind. This PR does not touch existing API. REST / transport wiring lands in a follow-up.

Scope

  • In: the core/job/* package (interface + value types + state machine + engine SPI + in-memory store + exceptions), the OpenSearch-side impl in opensearch/, unit tests.
  • Out (deferred; each lands behind an existing interface without touching QueryJob): REST endpoints, transport wiring, PPL/SQL runner adapters, Guice bindings, retention timers, admission control, persistent store.

Class diagram

classDiagram
    class QueryJobService {
        <<interface>>
        +submit(QueryRunner, Principal) QueryJob
        +get(QueryJobId, Principal) QueryJobStatus
        +cancel(QueryJobId, Principal) QueryJobStatus
    }
    class OpenSearchQueryJobService {
        -QueryJobStore store
        -ClusterService clusterService
        -Clock clock
    }
    class QueryJob {
        -QueryJobId id
        -Principal owner
        -QueryRunner runner
        -QueryJobState state
        +id() QueryJobId
        +owner() Principal
        +status() QueryJobStatus
        +completion() CompletionStage~QueryResult~
        +cancel() void
        ~startRunner() void
    }
    class QueryJobStore {
        <<interface>>
        +register(QueryJob) QueryJob
        +find(QueryJobId) Optional~QueryJob~
        +remove(QueryJobId, QueryJob) boolean
        +jobs() Collection~QueryJob~
        +close() void
    }
    class InMemoryQueryJobStore
    class QueryRunner {
        <<interface>>
        +run() CompletionStage~QueryResult~
        +cancel() void
    }
    class QueryJobId {
        <<record>>
        +ownerNodeId String
        +contextId String
        +encode() String
        +parse(String)$ QueryJobId
    }
    class QueryJobStatus {
        <<record>>
        +id QueryJobId
        +state QueryJobState
        +submittedAtMillis long
        +startedAtMillis OptionalLong
        +completedAtMillis OptionalLong
        +failure Optional~QueryFailure~
        +result Optional~QueryResult~
    }
    class QueryJobState {
        <<enum>>
        PENDING
        RUNNING
        SUCCEEDED
        FAILED
        CANCELLED
        +isTerminal() boolean
    }
    class Principal {
        <<record>>
        +name String
        +tenant String
        +backendRoles List~String~
        +allows(Principal) boolean
    }
    class SecurityAdapter {
        <<interface>>
        +current() Principal
    }
    class QueryResult {
        <<record>>
        +schema Schema
        +rows List~ExprValue~
        +cursor Cursor
        +warnings List~Warning~
        +tookMillis long
    }
    class QueryFailure {
        <<record>>
        +type String
        +reason String
        +of(Throwable)$ QueryFailure
    }

    OpenSearchQueryJobService ..|> QueryJobService
    OpenSearchQueryJobService --> QueryJobStore
    OpenSearchQueryJobService --> QueryJob : creates
    QueryJob --> QueryRunner : delegates
    QueryJob --> QueryJobId
    QueryJob --> Principal : owner
    QueryJob --> QueryJobStatus : projects
    QueryJobStore --> QueryJob : holds
    InMemoryQueryJobStore ..|> QueryJobStore
    QueryJobStatus --> QueryJobState
    QueryJobStatus --> QueryFailure
    QueryJobStatus --> QueryResult
Loading

State machine

              submit()
               │
               ▼
           ┌───────┐  runner starts   ┌────────┐
           │PENDING│─────────────────▶│RUNNING │
           └───┬───┘                   └───┬────┘
               │                           │
               │ cancel()   ┌──────────────┼──────────────┐
               ▼            ▼              ▼              ▼
                       ┌─────────┐    ┌────────┐   ┌─────────┐
                       │SUCCEEDED│    │ FAILED │   │CANCELLED│
                       └─────────┘    └────────┘   └─────────┘

Terminal transitions are idempotent. cancel() from PENDING or RUNNING moves to CANCELLED; from a terminal state it is a no-op.

Sequence diagrams

submit — happy path
sequenceDiagram
    autonumber
    participant Caller as Caller (transport)
    participant Service as OpenSearchQueryJobService
    participant Store as QueryJobStore
    participant Job as QueryJob
    participant Runner as QueryRunner
    participant Engine as PPL / SQL / AE

    Caller->>Service: submit(runner, principal)
    Service->>Store: register(new QueryJob)  [state=PENDING]
    Service->>Job: startRunner()
    Job->>Job: state PENDING → RUNNING
    Job->>Runner: run()
    Runner->>Engine: (engine-specific execution)
    Service-->>Caller: QueryJob
    Note over Caller,Job: Caller thread free. Runner completes on worker thread.
    Engine-->>Runner: result
    Runner-->>Job: future.complete(QueryResult)
    Job->>Job: state RUNNING → SUCCEEDED, record result + completedAt
    Note over Job: completion() listeners fire on the completing thread
Loading
get — authorization + snapshot
sequenceDiagram
    autonumber
    participant Caller
    participant Service as OpenSearchQueryJobService
    participant Store
    participant Job

    Caller->>Service: get(jobId, principal)
    Service->>Store: find(jobId)
    alt not found
        Store-->>Service: Optional.empty
        Service-->>Caller: QueryJobNotFoundException
    else found
        Store-->>Service: QueryJob
        Service->>Job: owner().allows(principal) ?
        alt forbidden
            Service-->>Caller: QueryJobForbiddenException
        else allowed
            Service->>Job: status()
            Job-->>Service: QueryJobStatus (immutable snapshot)
            Service-->>Caller: QueryJobStatus
        end
    end
Loading
cancel — idempotent transition
sequenceDiagram
    autonumber
    participant Caller
    participant Service
    participant Job
    participant Runner

    Caller->>Service: cancel(jobId, principal)
    Service->>Job: owner().allows(principal) ?  (see get flow)
    Service->>Job: cancel()
    alt state was PENDING / RUNNING
        Job->>Job: state → CANCELLED, record completedAt
        Job->>Runner: cancel()   [best-effort]
        Job->>Job: completion.cancel(false)
    else state already terminal
        Note over Job: no-op (idempotent)
    end
    Service-->>Caller: QueryJobStatus
Loading

Follow-ups (deferred behind existing interfaces)

Feature Landing point
wait_for_completion_timeout (BigQuery-style submit-response wait) Transport calls completion().orTimeout(...); job unchanged
keep_alive / retention New RetentionPolicy composed into QueryJobService; job unchanged
Admission control AdmissionController invoked before store.register; job unchanged
Persistent cluster-visible metadata Alternate QueryJobStore implementation
SQL / AE support Additional QueryRunner implementations
Fetch / cancel via existing /_plugins/_async_query Id-shape routing behind AsyncQueryExecutorService; no new REST endpoint

Related Issues

Redesign of #5809.

Check List

  • New functionality includes testing.
  • New functionality has been documented.
    • New functionality has javadoc added.
    • New functionality has a user manual doc added. — N/A: no user-visible endpoint in this PR (design + tests only).
  • New PPL command checklist all confirmed. — N/A: no PPL command change.
  • API changes companion pull request created. — N/A: no wire-facing API change.
  • Commits are signed per the DCO using --signoff or -s.
  • Public documentation issue/PR created. — N/A: no user-visible feature yet.

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.
For more information on following Developer Certificate of Origin and signing off your commits, please check here.

…s only

Introduces org.opensearch.sql.job — a five-state query lifecycle
(PENDING, RUNNING, SUCCEEDED, FAILED, CANCELLED) — in response to
review of opensearch-project#5809.

Design-only PR: adds the neutral SPI, the state machine, the registry,
the OpenSearch-side lifecycle service, and their tests. No existing
API is touched. PPL / SQL / transport wiring lands in a follow-up.

Addresses @dai-chen's three review comments:

  1. Lifecycle layer is language-neutral, Livy-style. The job package
     does not import PPL; each engine implements the QueryRunner SPI.
  2. Execution boundary is engine-neutral. QueryRunner returns a
     neutral QueryResult (schema/rows/cursor/warnings/tookMillis);
     the same shape fits SQL and AE.
  3. Execution state is decoupled from retention. State stays RUNNING
     regardless of whether a caller is still waiting. Service
     responsibilities split into QueryJobService (public interface),
     QueryJobStore (in-memory registry SPI), and QueryJob (state
     machine active object). SecurityAdapter SPI keeps OpenSearch
     types out of core.

Module layout:

  core/job/       neutral interface + value types + reference
                  in-memory store + engine SPI
  opensearch/job/ OpenSearchQueryJobService — symmetric with the
                  existing OpenSearchQueryManager

Public surface (all in core/job/):

  QueryJobService        submit(runner, submitter) / get / cancel
  QueryJob               state machine active object (5-state)
  QueryJobId             opaque, node-routable, URL-safe
  QueryJobState          PENDING / RUNNING / SUCCEEDED / FAILED / CANCELLED
  QueryJobStatus         immutable snapshot with invariant checks
  QueryJobStore          registry SPI + InMemoryQueryJobStore
  QueryRunner            engine SPI: run() / cancel()
  QueryResult            neutral final result
  QueryFailure           neutral failure descriptor
  Principal              caller identity for owner authorization
  SecurityAdapter        SPI: runtime context -> Principal

Verification (rerun against the reduced scope):
  ./gradlew :core:test :opensearch:test    -> 39 job tests, 0 failures

MVP scope intentionally excludes wait_for_completion_timeout,
keep_alive, retention, admission control, and REST wiring. Every
deferred feature lands behind an existing interface without touching
QueryJob.

Design doc: docs/dev/query-job-mvp-design.md (design/query-job-mvp branch).

Signed-off-by: Peng Huo <[email protected]>
@github-actions

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🧪 PR contains tests
🔒 No security concerns identified
✅ No TODO sections
🔀 No multiple PR themes
⚡ Recommended focus areas for review

Race Condition

In onRunnerSuccess and onRunnerFailure, the check if (state != QueryJobState.RUNNING) does not account for the PENDING state when a synchronous exception occurs in startRunner(). If the runner throws synchronously, onRunnerFailure is called while still in PENDING, but the guard only checks for RUNNING. This means a synchronous failure from PENDING will be ignored if a concurrent cancel() has already moved the state to CANCELLED, potentially leaving the completion future in an inconsistent state.

private void onRunnerFailure(Throwable throwable) {
  synchronized (this) {
    if (state != QueryJobState.RUNNING && state != QueryJobState.PENDING) {
      return;
    }
Possible Issue

The close() method sets closed = true and then iterates over jobs.values() to cancel each job. However, between setting closed and iterating, another thread could call register(), pass the closed check (if it reads the old value), and insert a new job. That job would not be cancelled by the iteration that has already started, leaving an uncancelled job in a closed store.

public void close() {
  if (closed) {
    return;
  }
  closed = true;
  for (QueryJob job : jobs.values()) {
    job.cancel();
  }
  jobs.clear();

@github-actions

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Prevent concurrent modification during iteration

The close() method iterates over jobs.values() without synchronization, which can
lead to a ConcurrentModificationException if another thread modifies the map during
iteration. Wrap the iteration in a synchronized block or create a defensive copy
before iterating.

core/src/main/java/org/opensearch/sql/job/InMemoryQueryJobStore.java [56-65]

 @Override
 public void close() {
   if (closed) {
     return;
   }
   closed = true;
-  for (QueryJob job : jobs.values()) {
+  for (QueryJob job : List.copyOf(jobs.values())) {
     job.cancel();
   }
   jobs.clear();
 }
Suggestion importance[1-10]: 9

__

Why: The close() method iterates over jobs.values() without synchronization on a ConcurrentHashMap, which can lead to a ConcurrentModificationException if the map is modified during iteration. Using List.copyOf(jobs.values()) creates a defensive snapshot that prevents this race condition. This is a critical concurrency bug that could cause runtime failures.

High
Use readFully for reliable byte reading

The readNBytes() method can return fewer bytes than requested if the stream ends
prematurely, but the check bytes.length != length may not catch all truncation cases
reliably. Use readFully() instead to ensure all bytes are read or an exception is
thrown.

core/src/main/java/org/opensearch/sql/job/QueryJobId.java [137-147]

 private static String readString(DataInputStream in, int maxLength) throws IOException {
   int length = in.readInt();
   if (length < 0 || length > maxLength) {
     throw new IllegalArgumentException("Invalid query job ID component length");
   }
-  byte[] bytes = in.readNBytes(length);
-  if (bytes.length != length) {
-    throw new IllegalArgumentException("Truncated query job ID");
-  }
+  byte[] bytes = new byte[length];
+  in.readFully(bytes);
   return new String(bytes, StandardCharsets.UTF_8);
 }
Suggestion importance[1-10]: 8

__

Why: The readNBytes() method may return fewer bytes than requested if the stream ends prematurely, and while the code checks bytes.length != length, using readFully() is more robust and idiomatic for ensuring all bytes are read or an exception is thrown. This prevents potential data corruption in job ID parsing.

Medium
General
Remove redundant boolean flag

The shouldCancelRunner variable is always set to true when the synchronized block
completes, making it redundant. The check for state.isTerminal() already ensures the
runner should be cancelled. Simplify by removing the unnecessary variable.

core/src/main/java/org/opensearch/sql/job/QueryJob.java [104-118]

 public void cancel() {
-  boolean shouldCancelRunner;
   synchronized (this) {
     if (state.isTerminal()) {
       return;
     }
     state = QueryJobState.CANCELLED;
     completedAtMillis = OptionalLong.of(clock.millis());
-    shouldCancelRunner = true;
   }
-  if (shouldCancelRunner) {
-    safeCancelRunner();
-  }
+  safeCancelRunner();
   completion.cancel(false);
 }
Suggestion importance[1-10]: 4

__

Why: The shouldCancelRunner variable is always true when the synchronized block completes successfully, making it redundant. Removing it simplifies the code without changing behavior, improving readability and maintainability.

Low

@penghuo penghuo self-assigned this Sep 28, 2026
@penghuo penghuo added PPL Piped processing language enhancement New feature or request labels Sep 28, 2026
@penghuo penghuo changed the title [FEATURE] Language-neutral query job lifecycle (design + tests) [FEATURE] Language-neutral query job lifecycle Sep 28, 2026
@codecov

codecov Bot commented Sep 28, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 76.75439% with 53 lines in your changes missing coverage. Please review.
✅ Project coverage is 63.31%. Comparing base (f2f4893) to head (990c47b).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
...src/main/java/org/opensearch/sql/job/QueryJob.java 83.33% 8 Missing and 4 partials ⚠️
...c/main/java/org/opensearch/sql/job/QueryJobId.java 72.09% 6 Missing and 6 partials ⚠️
...in/java/org/opensearch/sql/job/QueryJobStatus.java 44.44% 5 Missing and 5 partials ⚠️
.../main/java/org/opensearch/sql/job/QueryResult.java 28.57% 7 Missing and 3 partials ⚠️
.../org/opensearch/sql/job/InMemoryQueryJobStore.java 90.00% 1 Missing and 1 partial ⚠️
...sql/job/exceptions/QueryJobForbiddenException.java 0.00% 2 Missing ⚠️
.../sql/job/exceptions/QueryJobNotFoundException.java 0.00% 2 Missing ⚠️
.../opensearch/sql/job/OpenSearchQueryJobService.java 92.85% 1 Missing and 1 partial ⚠️
...n/java/org/opensearch/sql/job/SecurityAdapter.java 0.00% 1 Missing ⚠️

❌ Your project check has failed because the head coverage (63.31%) is below the target coverage (99.00%). You can increase the head coverage or adjust the target coverage.

Additional details and impacted files
@@             Coverage Diff              @@
##               main    #5818      +/-   ##
============================================
+ Coverage     63.23%   63.31%   +0.07%     
- Complexity     8823     8892      +69     
============================================
  Files           938      950      +12     
  Lines         40236    40464     +228     
  Branches       4537     4569      +32     
============================================
+ Hits          25445    25620     +175     
- Misses        13966    13999      +33     
- Partials        825      845      +20     
Flag Coverage Δ
sql-engine 63.31% <76.75%> (+0.07%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@dai-chen dai-chen left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Thanks!

Minor: there seems a race condition between register() and close().

@penghuo

penghuo commented Sep 29, 2026

Copy link
Copy Markdown
Collaborator Author

LGTM. Thanks!

Minor: there seems a race condition between register() and close().

Ack, will address in API hookup PR.

@penghuo
penghuo merged commit 67aed0e into opensearch-project:main Sep 29, 2026
44 of 53 checks passed
@penghuo penghuo mentioned this pull request Sep 29, 2026
5 of 8 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request PPL Piped processing language

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants