Skip to content
Merged
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
52 changes: 52 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,58 @@ int echoed = client.ping(3); // 3
int randomEcho = client.ping();
```

## Offline Query

The HTTP client supports offline query submission and status polling. Use
`ChalkClient.create()` or `ChalkClient.builder().build()` without `withGrpc()`.

Inputs may be a Chalk SQL query (`withInputSql`), an existing Parquet URI
(`withInputUri`), or omitted to sample the offline store. Outputs are exported
as Parquet. This API returns metadata and signed download URLs; it does not
upload local inputs or load result files into Java tables.

```java
import ai.chalk.models.OfflineQueryParams;
import ai.chalk.models.OfflineQueryResult;
import ai.chalk.models.GetOfflineQueryStatusParams;
import ai.chalk.models.OfflineQueryStatus;

try (ChalkClient client = ChalkClient.create()) {
OfflineQueryResult result = client.offlineQuery(OfflineQueryParams.builder()
.withOutputs("user.id", "user.score")
.withInputSql("select user.id from user")
.withRunAsynchronously(true)
.build());
if (!result.getErrors().isEmpty()) {
throw new IllegalStateException(result.getErrors().toString());
}
OfflineQueryResult.Revision revision = result.getRevisions().get(0);
if (!revision.getErrors().isEmpty()) {
throw new IllegalStateException(revision.getErrors().toString());
}
GetOfflineQueryStatusParams statusParams = GetOfflineQueryStatusParams.builder()
.withJobId(revision.getRevisionId())
.withEnvironmentId(revision.getEnvironmentId())
.withBranch(revision.getBranch())
.build();
OfflineQueryStatus status = client.getOfflineQueryStatus(statusParams);
// Poll again with a bounded delay/deadline until status.isFinished().
// A finished job may have failed: always check getErrors().
if (!status.getErrors().isEmpty()) {
throw new IllegalStateException(status.getErrors().toString());
}
if (status.isFinished()) {
System.out.println(status.getUrls());
}
}
```

Signed URLs expire; call `getOfflineQueryStatus` again for fresh URLs. Download
them with a separate HTTP client without attaching Chalk credentials.
`withTimeout(Duration)` bounds an individual HTTP call, not the lifetime of
the offline job. Environment and branch overrides should be carried from
submission to subsequent status calls.

## Memory management
Chalk uses Arrow objects during serialization of requests and deserialization of responses. These objects need to be
closed to free up memory.
Expand Down
20 changes: 20 additions & 0 deletions src/main/java/ai/chalk/client/ChalkClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,26 @@ default OnlineQueryMultiResult onlineQueryMulti(OnlineQueryParamsComplete... par
*/
UploadFeaturesResult uploadFeatures(UploadFeaturesParams params) throws ChalkException;

/**
* Submit an offline query through the HTTP API. Returns dataset/revision metadata;
* use a revision id with {@link #getOfflineQueryStatus} to retrieve result URLs.
* Check errors on the response and revisions. Available on the HTTP client only.
*/
default OfflineQueryResult offlineQuery(OfflineQueryParams params) throws ChalkException {
throw new ClientException("offlineQuery requires the HTTP client. Use ChalkClient.create() "
+ "or ChalkClient.builder().build() without withGrpc().");
}

/**
* Get completion, errors and signed Parquet download URLs for an offline query.
* Available on the HTTP client only. Completion alone does not imply success.
*/
default OfflineQueryStatus getOfflineQueryStatus(GetOfflineQueryStatusParams params)
throws ChalkException {
throw new ClientException("getOfflineQueryStatus requires the HTTP client. Use ChalkClient.create() "
+ "or ChalkClient.builder().build() without withGrpc().");
}

/**
* DeleteFeatures targets feature observation values for deletion and performs
* deletion online and offline.
Expand Down
38 changes: 38 additions & 0 deletions src/main/java/ai/chalk/client/ChalkClientImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@
import ai.chalk.models.DeleteFeaturesParams;
import ai.chalk.models.DeleteFeaturesResult;
import ai.chalk.models.GetAggregateBackfillJobParams;
import ai.chalk.models.GetOfflineQueryStatusParams;
import ai.chalk.models.OfflineQueryParams;
import ai.chalk.models.OfflineQueryResult;
import ai.chalk.models.OfflineQueryStatus;
import ai.chalk.models.OnlineQueryParamsComplete;
import ai.chalk.models.OnlineQueryResult;
import ai.chalk.models.QueryMeta;
Expand Down Expand Up @@ -120,6 +124,40 @@ public int ping(int num) throws ChalkException {
return this.handler.deserializeResponseBody(response.body(), PingResponse.class).num();
}

@Override
public OfflineQueryResult offlineQuery(OfflineQueryParams params) throws ChalkException {
Map<String, Object> body = OfflineQueries.request(params);
var request = new SendRequestParams.Builder(params.getTimeout())
.path("/v4/offline_query")
.method("POST")
.body(body)
.environmentOverride(params.getEnvironmentId())
.branch(params.getBranch())
// Submission must go through the API server, even with a query-server override.
.isEngineRequest(false)
.build();
var response = this.handler.sendRequest(request);
return this.handler.deserializeResponseBody(response.body(), OfflineQueryResult.class);
}

@Override
public OfflineQueryStatus getOfflineQueryStatus(GetOfflineQueryStatusParams params)
throws ChalkException {
if (params == null || params.getJobId() == null || params.getJobId().isBlank()) {
throw new ClientException("An offline query job id is required");
}
var request = new SendRequestParams.Builder(params.getTimeout())
.path("/v4/offline_query/status")
.method("POST")
.body(Map.of("job_id", params.getJobId()))
.environmentOverride(params.getEnvironmentId())
.branch(params.getBranch())
.isEngineRequest(true)
.build();
var response = this.handler.sendRequest(request);
return this.handler.deserializeResponseBody(response.body(), OfflineQueryStatus.class);
}

private OnlineQueryResult onlineQueryFeather(OnlineQueryParamsComplete params) throws ChalkException {
byte[] bodyBytes;
try (
Expand Down
61 changes: 61 additions & 0 deletions src/main/java/ai/chalk/client/OfflineQueries.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package ai.chalk.client;

import ai.chalk.exceptions.ClientException;
import ai.chalk.models.OfflineQueryParams;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/** Translation to the existing /v4/offline_query JSON contract. */
final class OfflineQueries {
private OfflineQueries() {}

static Map<String, Object> request(OfflineQueryParams params) throws ClientException {
if (params == null) {
throw new ClientException("Offline query parameters are required");
}
if ((params.getOutputs() == null || params.getOutputs().isEmpty())
&& (params.getRequiredOutputs() == null || params.getRequiredOutputs().isEmpty())) {
throw new ClientException("At least one output or required output is required");
}
if (params.getInputSql() != null && params.getInputUri() != null) {
throw new ClientException("Specify only one of inputSql and inputUri");
}
if ((params.getNumShards() != null && params.getNumShards() < 1)
|| (params.getNumWorkers() != null && params.getNumWorkers() < 1)) {
throw new ClientException("numShards and numWorkers must be positive");
}
Map<String, Object> body = new LinkedHashMap<>();
body.put("output", params.getOutputs() == null ? List.of() : params.getOutputs());
body.put("required_output", params.getRequiredOutputs() == null ? List.of() : params.getRequiredOutputs());
body.put("destination_format", "PARQUET");
if (params.getInputSql() != null) {
body.put("input", Map.of("input_sql", params.getInputSql()));
} else if (params.getInputUri() != null) {
body.put("input", Map.of("parquet_uri", params.getInputUri()));
}
put(body, "dataset_name", params.getDatasetName());
put(body, "branch", params.getBranch());
put(body, "observed_at_lower_bound", params.getLowerBound() == null ? null : params.getLowerBound().toString());
put(body, "observed_at_upper_bound", params.getUpperBound() == null ? null : params.getUpperBound().toString());
put(body, "max_samples", params.getMaxSamples());
put(body, "num_shards", params.getNumShards());
put(body, "num_workers", params.getNumWorkers());
put(body, "use_metaplanner", params.getUseMetaplanner());
put(body, "planner_options", params.getPlannerOptions());
body.put("use_multiple_computers", params.isRunAsynchronously()
|| params.getNumShards() != null || params.getNumWorkers() != null
|| Boolean.TRUE.equals(params.getUseMetaplanner()));
body.put("recompute_features", params.isRecomputeFeatures());
body.put("store_online", params.isStoreOnline());
body.put("store_offline", params.isStoreOffline());
return body;
}

private static void put(Map<String, Object> body, String key, Object value) {
if (value != null) {
body.put(key, value);
}
}
}
16 changes: 16 additions & 0 deletions src/main/java/ai/chalk/models/GetOfflineQueryStatusParams.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package ai.chalk.models;

import lombok.Builder;
import lombok.Value;

import java.time.Duration;

/** The job id is the revision id returned by {@link OfflineQueryResult}. */
@Value
@Builder(setterPrefix = "with")
public class GetOfflineQueryStatusParams {
String jobId;
String environmentId;
String branch;
Duration timeout;
}
61 changes: 61 additions & 0 deletions src/main/java/ai/chalk/models/OfflineQueryParams.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package ai.chalk.models;

import lombok.Builder;
import lombok.Value;

import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
* Parameters for an offline query. Inputs may be a Chalk SQL query, an existing
* Parquet URI, or omitted to sample the offline store. Results are exported as Parquet.
* Local input upload and loading result files into Java tables are not supported.
*/
@Value
@Builder(setterPrefix = "with")
public class OfflineQueryParams {
List<String> outputs;
List<String> requiredOutputs;
String inputSql;
String inputUri;
String datasetName;
String environmentId;
String branch;
Duration timeout;
Instant lowerBound;
Instant upperBound;
Integer maxSamples;
Integer numShards;
Integer numWorkers;
Boolean useMetaplanner;
boolean runAsynchronously;
boolean recomputeFeatures;
boolean storeOnline;
boolean storeOffline;
Map<String, Object> plannerOptions;

public static class OfflineQueryParamsBuilder {
public OfflineQueryParamsBuilder withOutputs(List<String> outputs) {
this.outputs = outputs;
return this;
}

public OfflineQueryParamsBuilder withRequiredOutputs(List<String> outputs) {
this.requiredOutputs = outputs;
return this;
}

public OfflineQueryParamsBuilder withOutputs(String... outputs) {
this.outputs = Arrays.asList(outputs);
return this;
}

public OfflineQueryParamsBuilder withRequiredOutputs(String... outputs) {
this.requiredOutputs = Arrays.asList(outputs);
return this;
}
}
}
45 changes: 45 additions & 0 deletions src/main/java/ai/chalk/models/OfflineQueryResult.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package ai.chalk.models;

import ai.chalk.exceptions.ServerError;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSetter;
import com.fasterxml.jackson.annotation.Nulls;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

/** Dataset metadata returned by submission. Check errors before using revisions. */
@Data
@NoArgsConstructor
public class OfflineQueryResult {
@JsonProperty("is_finished")
private boolean finished;
private int version;
private String environmentId;
private String datasetId;
private String datasetName;
private List<Revision> revisions = new ArrayList<>();
@JsonSetter(nulls = Nulls.AS_EMPTY)
private List<ServerError> errors = new ArrayList<>();

/** Use revisionId as the jobId when polling for completion and download URLs. */
@Data
@NoArgsConstructor
public static class Revision {
private String revisionId;
private String environmentId;
private String branch;
/** Numeric QueryStatus value returned by the server. */
private int status;
private List<String> outputs = new ArrayList<>();
private Integer numPartitions;
private Integer numComputers;
private Long numRows;
private Long numBytes;
private String dashboardUrl;
@JsonSetter(nulls = Nulls.AS_EMPTY)
private List<ServerError> errors = new ArrayList<>();
}
}
27 changes: 27 additions & 0 deletions src/main/java/ai/chalk/models/OfflineQueryStatus.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package ai.chalk.models;

import ai.chalk.exceptions.ServerError;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSetter;
import com.fasterxml.jackson.annotation.Nulls;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

/**
* Completion and result URLs for an offline query. A finished job may have failed:
* check errors before consuming urls. URLs are signed and short-lived; poll again
* to obtain fresh URLs. Download files without attaching Chalk credentials.
*/
@Data
@NoArgsConstructor
public class OfflineQueryStatus {
@JsonProperty("is_finished")
private boolean finished;
private int version;
private List<String> urls = new ArrayList<>();
@JsonSetter(nulls = Nulls.AS_EMPTY)
private List<ServerError> errors = new ArrayList<>();
}
Loading
Loading