Xiao-zhen-Liu commented on code in PR #6436:
URL: https://github.com/apache/texera/pull/6436#discussion_r4556612888
##########
agent-service/src/server.ts:
##########
@@ -388,6 +390,45 @@ const agentsRouter = new Elysia({ prefix: "/agents" })
}
);
+// Stateless ambient operator recommender (apache/texera#5240). Given the
+// operator a user just added, returns a short ranked list of likely next
+// operators for the canvas to render as suggestions. Version 1 uses a
+// hardcoded rule table with no LLM call, so it needs no user token and no
+// per-request model configuration; it only reads the process-wide operator
+// catalog to validate and label its suggestions.
+const recommendRouter = new Elysia({ prefix: "/recommend" })
Review Comment:
On its own, this PR leaves the new endpoint unreachable from the browser:
the frontend dev proxy, single-node web server config, and Kubernetes gateway
only forward the existing agents route to the agent service (#6437 adds the
first two, while the gateway route was dropped in a merge conflict). Could we
wire all three routes here, using a separate Kubernetes route so stateless
calls bypass workflow-header consistent hashing?
##########
agent-service/src/recommender/recommender.ts:
##########
@@ -0,0 +1,97 @@
+/**
+ * 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 {
+ DEFAULT_RECOMMENDATION_LIMIT,
+ MAX_RECOMMENDATION_LIMIT,
+ type OperatorRecommendation,
+ type RecommendationRequest,
+ type RecommendationResponse,
+} from "./recommender-types";
+import { candidateSuccessors, rationaleFor } from "./hardcoded-rules";
+
+/**
+ * Minimal read-only view of the operator catalog the recommender needs. The
+ * `WorkflowSystemMetadata` singleton satisfies this structurally; tests can
pass
+ * a stub (or omit it entirely to exercise the un-initialized path).
+ */
+export interface OperatorCatalog {
+ isInitialized(): boolean;
+ operatorTypeExists(operatorType: string): boolean;
+ getAdditionalMetadata(operatorType: string): { userFriendlyName?: string } |
undefined;
+}
+
+// Top suggestion scores 0.9 and each lower rank drops one step, floored at
0.3.
+// With MAX_RECOMMENDATION_LIMIT = 5 this yields 0.9 / 0.75 / 0.6 / 0.45 / 0.3.
+const TOP_SCORE = 0.9;
+const SCORE_STEP = 0.15;
+const MIN_SCORE = 0.3;
+
+function scoreForRank(rank: number): number {
+ return Math.max(MIN_SCORE, +(TOP_SCORE - rank * SCORE_STEP).toFixed(2));
+}
+
+function clampLimit(limit: number | undefined): number {
+ if (limit === undefined || !Number.isFinite(limit)) return
DEFAULT_RECOMMENDATION_LIMIT;
+ return Math.min(MAX_RECOMMENDATION_LIMIT, Math.max(1, Math.floor(limit)));
+}
+
+/**
+ * Version 1 hardcoded recommender: given the operator just added, return a
+ * short ranked list of likely successors drawn from {@link
candidateSuccessors}.
+ *
+ * The result is deterministic and requires no LLM call. When a `catalog` is
+ * supplied and initialized, suggestions are filtered to operator types that
+ * actually exist (so a stale rule never yields an unusable suggestion) and
enriched
+ * with the operator's display name; without an initialized catalog the raw
+ * ranked candidates are returned as-is.
+ */
+export function recommendOperators(req: RecommendationRequest, catalog?:
OperatorCatalog): RecommendationResponse {
+ const operatorType = req.operatorType?.trim();
+ const limit = clampLimit(req.limit);
+
+ if (!operatorType) {
+ return { recommendations: [], strategy: "hardcoded" };
+ }
+
+ const catalogReady = catalog?.isInitialized() ?? false;
+
+ const seen = new Set<string>();
+ const recommendations: OperatorRecommendation[] = [];
+
+ for (const candidate of candidateSuccessors(operatorType)) {
+ if (recommendations.length >= limit) break;
+ // Never suggest the operator itself, and never suggest the same type
twice.
+ if (candidate === operatorType || seen.has(candidate)) continue;
+ // Drop suggestions the running system can't actually instantiate.
+ if (catalogReady && !catalog!.operatorTypeExists(candidate)) continue;
Review Comment:
Main has removed this existence helper from the operator catalog (#9239).
Once merged with main, typechecking fails and every request returns 500 after
startup loads the catalog (for example, requesting suggestions after adding CSV
File Scan throws because the method is missing). Could we merge main and check
existence through what the catalog still exposes, such as looking up the
operator's schema?
##########
agent-service/src/server.ts:
##########
@@ -388,6 +390,45 @@ const agentsRouter = new Elysia({ prefix: "/agents" })
}
);
+// Stateless ambient operator recommender (apache/texera#5240). Given the
+// operator a user just added, returns a short ranked list of likely next
+// operators for the canvas to render as suggestions. Version 1 uses a
+// hardcoded rule table with no LLM call, so it needs no user token and no
Review Comment:
Leaving this endpoint unauthenticated will force a breaking change in V2:
the agent service holds no LLM key of its own and forwards the signed-in user's
Bearer token to the LLM gateway (#5421), while the Kubernetes gateway does not
enforce auth on agent-service routes. Because the workflow editor already
attaches the user's Bearer token on HTTP requests, could we validate it here
just like agent creation does so V2 needs no auth contract change?
##########
agent-service/src/server.recommend.spec.ts:
##########
@@ -0,0 +1,85 @@
+/**
+ * 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 { describe, expect, test } from "bun:test";
+import { buildApp } from "./server";
+import { env } from "./config/env";
+import type { RecommendationResponse } from "./recommender/recommender-types";
+
+const API = env.API_PREFIX;
+const app = buildApp();
Review Comment:
These route tests never initialize the real operator catalog, so catalog
validation and display-name lookup are only exercised against the unit-test
stub (which hid the removed catalog method on main). Could we add a route test
with an initialized catalog fixture so mismatches with the real catalog class
are caught?
##########
agent-service/src/recommender/hardcoded-rules.ts:
##########
@@ -0,0 +1,210 @@
+/**
+ * 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.
+ */
+
+/**
+ * Hardcoded "what usually comes next" table for the Version 1 operator
+ * recommender (apache/texera#5240). Kept deliberately small and readable: a
+ * coarse category per operator, a ranked successor list per category, plus a
+ * handful of specific overrides for the most common dataflow patterns.
+ *
+ * Operator type strings here must match the `@JsonSubTypes` names registered
on
+ * `LogicalOp` (the catalog the frontend and compiler use). Suggestions are
+ * validated against the live operator catalog before being returned, so a
stale
+ * entry here degrades to "not suggested" rather than to a broken suggestion.
+ */
+
+export type OperatorCategory = "source" | "transform" | "aggregate" | "join" |
"rowOps" | "udf" | "ml" | "sink";
+
+/**
+ * Explicit category for operators whose successors don't follow from a naming
+ * heuristic. Operators absent here fall back to {@link inferCategory}.
+ */
+const OPERATOR_CATEGORY: Record<string, OperatorCategory> = {
+ // Sources — read data into the workflow.
+ CSVFileScan: "source",
+ CSVOldFileScan: "source",
+ ParallelCSVFileScan: "source",
+ JSONLFileScan: "source",
+ FileScan: "source",
+ ArrowSource: "source",
+ TextInput: "source",
+ URLFetcher: "source",
+ FileLister: "source",
+ PostgreSQLSource: "source",
+ MySQLSource: "source",
+ AsterixDBSource: "source",
+ SQLSource: "source",
Review Comment:
Nit: This entry refers to an abstract base descriptor rather than a
registered operator (and Parallel CSV File Scan above is disabled in the
catalog). Could we keep only concrete registered operators in this table?
##########
agent-service/src/recommender/recommender-types.ts:
##########
@@ -0,0 +1,81 @@
+/**
+ * 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.
+ */
+
+/**
+ * Wire types for the ambient operator recommender (discussion
apache/texera#5240).
+ *
+ * The recommender is a stateless endpoint that, given the operator a user just
+ * added to the canvas, returns a short ranked list of likely "next" operators
+ * to render as suggestion chips on the output port.
+ *
+ * Version 1 (this file's consumer, `recommendOperators`) produces suggestions
+ * from a hardcoded rule table — no LLM call, no persistent state — so it can
+ * ship and validate the full canvas pipeline at zero API cost. Version 2 will
+ * swap the ranking strategy for a small LLM behind the same request/response
+ * shape; the `strategy` discriminator on the response lets clients tell the
two
+ * apart without a breaking change.
+ */
+
+/** Ranking strategy that produced a response. `llm` is reserved for V2. */
+export type RecommendationStrategy = "hardcoded" | "llm";
+
+/** Hard ceiling on how many suggestions a single request may ask for. */
+export const MAX_RECOMMENDATION_LIMIT = 5;
+
+/** Default number of suggestions when the request does not specify a limit. */
+export const DEFAULT_RECOMMENDATION_LIMIT = 3;
+
+export interface RecommendationRequest {
+ /**
+ * The operator type that was just added and whose output port we are
+ * suggesting successors for (e.g. `"CSVFileScan"`). Primary ranking signal.
+ */
+ operatorType: string;
Review Comment:
Neither the request nor each returned suggestion identifies a port, which
forces the canvas to hardcode the first output port and first input port. That
breaks multi-output operators like Split and multi-input targets like Sklearn
Prediction, whose first input port expects a trained model while its second
expects data rows. Could we include the source output port in the request and
the target input port on each suggestion so multi-port operators work without a
future contract break?
##########
agent-service/src/recommender/hardcoded-rules.ts:
##########
@@ -0,0 +1,210 @@
+/**
+ * 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.
+ */
+
+/**
+ * Hardcoded "what usually comes next" table for the Version 1 operator
+ * recommender (apache/texera#5240). Kept deliberately small and readable: a
+ * coarse category per operator, a ranked successor list per category, plus a
+ * handful of specific overrides for the most common dataflow patterns.
+ *
+ * Operator type strings here must match the `@JsonSubTypes` names registered
on
+ * `LogicalOp` (the catalog the frontend and compiler use). Suggestions are
+ * validated against the live operator catalog before being returned, so a
stale
+ * entry here degrades to "not suggested" rather than to a broken suggestion.
+ */
+
+export type OperatorCategory = "source" | "transform" | "aggregate" | "join" |
"rowOps" | "udf" | "ml" | "sink";
+
+/**
+ * Explicit category for operators whose successors don't follow from a naming
+ * heuristic. Operators absent here fall back to {@link inferCategory}.
+ */
+const OPERATOR_CATEGORY: Record<string, OperatorCategory> = {
+ // Sources — read data into the workflow.
Review Comment:
Nit: Could we replace the em-dashes in the comments across these files with
colons or parentheses to match project style?
##########
agent-service/src/recommender/recommender-types.ts:
##########
@@ -0,0 +1,81 @@
+/**
+ * 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.
+ */
+
+/**
+ * Wire types for the ambient operator recommender (discussion
apache/texera#5240).
+ *
+ * The recommender is a stateless endpoint that, given the operator a user just
+ * added to the canvas, returns a short ranked list of likely "next" operators
+ * to render as suggestion chips on the output port.
+ *
+ * Version 1 (this file's consumer, `recommendOperators`) produces suggestions
+ * from a hardcoded rule table — no LLM call, no persistent state — so it can
+ * ship and validate the full canvas pipeline at zero API cost. Version 2 will
+ * swap the ranking strategy for a small LLM behind the same request/response
+ * shape; the `strategy` discriminator on the response lets clients tell the
two
+ * apart without a breaking change.
+ */
+
+/** Ranking strategy that produced a response. `llm` is reserved for V2. */
+export type RecommendationStrategy = "hardcoded" | "llm";
+
+/** Hard ceiling on how many suggestions a single request may ask for. */
+export const MAX_RECOMMENDATION_LIMIT = 5;
+
+/** Default number of suggestions when the request does not specify a limit. */
+export const DEFAULT_RECOMMENDATION_LIMIT = 3;
+
+export interface RecommendationRequest {
+ /**
+ * The operator type that was just added and whose output port we are
+ * suggesting successors for (e.g. `"CSVFileScan"`). Primary ranking signal.
+ */
+ operatorType: string;
+
+ /**
+ * Optional: operator types already present on the canvas. Unused by the V1
+ * hardcoded ranker; reserved so V2 can bias suggestions with graph context
+ * without a request-shape change.
+ */
+ existingOperatorTypes?: string[];
Review Comment:
This field is unused in V1, has no length bound in the request validator,
and a flat list of operator types on the canvas still omits the upstream
connections and output schemas that V2's LLM ranker will need. Could we omit
this unused field (and bound the operator-type string length on the route) in
V1 so V2 can introduce structured upstream graph and schema context without
carrying a redundant field?
##########
agent-service/src/server.ts:
##########
@@ -388,6 +390,45 @@ const agentsRouter = new Elysia({ prefix: "/agents" })
}
);
+// Stateless ambient operator recommender (apache/texera#5240). Given the
+// operator a user just added, returns a short ranked list of likely next
+// operators for the canvas to render as suggestions. Version 1 uses a
+// hardcoded rule table with no LLM call, so it needs no user token and no
+// per-request model configuration; it only reads the process-wide operator
+// catalog to validate and label its suggestions.
+const recommendRouter = new Elysia({ prefix: "/recommend" })
+ // Local-scoped error handler, mirroring agentsRouter: body-schema and
+ // malformed-JSON failures are client errors (400), not 500s.
+ .onError(({ code, error, set }) => {
+ log.error({ err: error }, "recommend request error");
+ const errorMessage = error instanceof Error ? error.message :
String(error);
+ if (code === "VALIDATION" || code === "PARSE") {
+ set.status = 400;
+ return { error: errorMessage || "Invalid request body" };
+ }
+ set.status = 500;
+ return { error: errorMessage || "Internal server error" };
+ })
+ .post(
+ "/",
+ ({ body, set }) => {
+ const req = body as RecommendationRequest;
+ const operatorType = req.operatorType.trim();
+ if (!operatorType) {
+ set.status = 400;
+ return { error: "operatorType must be a non-empty string" };
+ }
+ return recommendOperators({ ...req, operatorType },
WorkflowSystemMetadata.getInstance());
Review Comment:
If the agent service starts before the backend is ready, startup logs a
warning and leaves the catalog uninitialized. Chat agents retry loading the
catalog on creation, whereas this handler keeps reading the uninitialized
catalog on every request, returning unvalidated operator types with no display
names until someone creates a chat agent. Could we lazily retry initializing
the catalog here when it is not ready yet?
##########
agent-service/src/recommender/hardcoded-rules.ts:
##########
@@ -0,0 +1,210 @@
+/**
+ * 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.
+ */
+
+/**
+ * Hardcoded "what usually comes next" table for the Version 1 operator
+ * recommender (apache/texera#5240). Kept deliberately small and readable: a
+ * coarse category per operator, a ranked successor list per category, plus a
+ * handful of specific overrides for the most common dataflow patterns.
+ *
+ * Operator type strings here must match the `@JsonSubTypes` names registered
on
+ * `LogicalOp` (the catalog the frontend and compiler use). Suggestions are
+ * validated against the live operator catalog before being returned, so a
stale
+ * entry here degrades to "not suggested" rather than to a broken suggestion.
+ */
+
+export type OperatorCategory = "source" | "transform" | "aggregate" | "join" |
"rowOps" | "udf" | "ml" | "sink";
+
+/**
+ * Explicit category for operators whose successors don't follow from a naming
+ * heuristic. Operators absent here fall back to {@link inferCategory}.
+ */
+const OPERATOR_CATEGORY: Record<string, OperatorCategory> = {
+ // Sources — read data into the workflow.
+ CSVFileScan: "source",
+ CSVOldFileScan: "source",
+ ParallelCSVFileScan: "source",
+ JSONLFileScan: "source",
+ FileScan: "source",
+ ArrowSource: "source",
+ TextInput: "source",
+ URLFetcher: "source",
+ FileLister: "source",
+ PostgreSQLSource: "source",
+ MySQLSource: "source",
+ AsterixDBSource: "source",
+ SQLSource: "source",
+ TwitterSearch: "source",
+ TwitterFullArchiveSearch: "source",
+ RedditSearch: "source",
+ PythonUDFSourceV2: "source",
+ RUDFSource: "source",
+
+ // Transforms — reshape rows/columns.
+ Filter: "transform",
+ Projection: "transform",
+ TypeCasting: "transform",
+ Regex: "transform",
+ KeywordSearch: "transform",
+ SubstringSearch: "transform",
+ DictionaryMatcher: "transform",
+ UnnestString: "transform",
+ Split: "transform",
+
+ // Aggregations / reducers.
+ Aggregate: "aggregate",
+ PythonTableReducer: "aggregate",
+ Scorer: "aggregate",
+
+ // Joins and set operations (multi-input).
+ HashJoin: "join",
+ IntervalJoin: "join",
+ CartesianProduct: "join",
+ Union: "join",
+ Intersect: "join",
+ Difference: "join",
+ SymmetricDifference: "join",
+
+ // Ordering / sampling / row-count operators.
+ Sort: "rowOps",
+ SortPartitions: "rowOps",
+ StableMergeSort: "rowOps",
+ Limit: "rowOps",
+ Distinct: "rowOps",
+ RandomKSampling: "rowOps",
+ ReservoirSampling: "rowOps",
+
+ // User-defined functions.
+ PythonUDFV2: "udf",
+ DualInputPortsPythonUDFV2: "udf",
+ PythonLambdaFunction: "udf",
+ JavaUDF: "udf",
+ RUDF: "udf",
+};
+
+/** Ranked successor list per category, most-likely first. */
+const CATEGORY_SUCCESSORS: Record<OperatorCategory, string[]> = {
+ source: ["Filter", "Projection", "TypeCasting", "KeywordSearch"],
+ transform: ["Aggregate", "Projection", "Sort", "PythonUDFV2"],
+ aggregate: ["BarChart", "LineChart", "Sort"],
+ join: ["Projection", "Aggregate", "Filter"],
+ rowOps: ["Aggregate", "Projection", "BarChart"],
+ udf: ["Filter", "Projection", "Aggregate"],
+ ml: ["Scorer", "PythonUDFV2"],
Review Comment:
Scikit-learn training and model operators output a fitted model row rather
than predicted labels, so after adding Training: Logistic Regression the top
suggestion is Machine Learning Scorer, which has no prediction column to score.
Could we suggest Sklearn Prediction (and Sklearn Testing) after model-producing
operators, and keep Machine Learning Scorer for operators that output
predictions such as Sklearn Prediction and Hugging Face operators?
##########
agent-service/src/recommender/hardcoded-rules.ts:
##########
@@ -0,0 +1,210 @@
+/**
+ * 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.
+ */
+
+/**
+ * Hardcoded "what usually comes next" table for the Version 1 operator
+ * recommender (apache/texera#5240). Kept deliberately small and readable: a
+ * coarse category per operator, a ranked successor list per category, plus a
+ * handful of specific overrides for the most common dataflow patterns.
+ *
+ * Operator type strings here must match the `@JsonSubTypes` names registered
on
+ * `LogicalOp` (the catalog the frontend and compiler use). Suggestions are
+ * validated against the live operator catalog before being returned, so a
stale
+ * entry here degrades to "not suggested" rather than to a broken suggestion.
+ */
+
+export type OperatorCategory = "source" | "transform" | "aggregate" | "join" |
"rowOps" | "udf" | "ml" | "sink";
+
+/**
+ * Explicit category for operators whose successors don't follow from a naming
+ * heuristic. Operators absent here fall back to {@link inferCategory}.
+ */
+const OPERATOR_CATEGORY: Record<string, OperatorCategory> = {
+ // Sources — read data into the workflow.
+ CSVFileScan: "source",
+ CSVOldFileScan: "source",
+ ParallelCSVFileScan: "source",
+ JSONLFileScan: "source",
+ FileScan: "source",
+ ArrowSource: "source",
+ TextInput: "source",
+ URLFetcher: "source",
+ FileLister: "source",
+ PostgreSQLSource: "source",
+ MySQLSource: "source",
+ AsterixDBSource: "source",
+ SQLSource: "source",
+ TwitterSearch: "source",
+ TwitterFullArchiveSearch: "source",
+ RedditSearch: "source",
+ PythonUDFSourceV2: "source",
+ RUDFSource: "source",
+
+ // Transforms — reshape rows/columns.
+ Filter: "transform",
+ Projection: "transform",
+ TypeCasting: "transform",
+ Regex: "transform",
+ KeywordSearch: "transform",
+ SubstringSearch: "transform",
+ DictionaryMatcher: "transform",
+ UnnestString: "transform",
+ Split: "transform",
+
+ // Aggregations / reducers.
+ Aggregate: "aggregate",
+ PythonTableReducer: "aggregate",
+ Scorer: "aggregate",
+
+ // Joins and set operations (multi-input).
+ HashJoin: "join",
+ IntervalJoin: "join",
+ CartesianProduct: "join",
+ Union: "join",
+ Intersect: "join",
+ Difference: "join",
+ SymmetricDifference: "join",
+
+ // Ordering / sampling / row-count operators.
+ Sort: "rowOps",
+ SortPartitions: "rowOps",
+ StableMergeSort: "rowOps",
+ Limit: "rowOps",
+ Distinct: "rowOps",
+ RandomKSampling: "rowOps",
+ ReservoirSampling: "rowOps",
+
+ // User-defined functions.
+ PythonUDFV2: "udf",
+ DualInputPortsPythonUDFV2: "udf",
+ PythonLambdaFunction: "udf",
+ JavaUDF: "udf",
+ RUDF: "udf",
+};
+
+/** Ranked successor list per category, most-likely first. */
+const CATEGORY_SUCCESSORS: Record<OperatorCategory, string[]> = {
+ source: ["Filter", "Projection", "TypeCasting", "KeywordSearch"],
+ transform: ["Aggregate", "Projection", "Sort", "PythonUDFV2"],
+ aggregate: ["BarChart", "LineChart", "Sort"],
+ join: ["Projection", "Aggregate", "Filter"],
+ rowOps: ["Aggregate", "Projection", "BarChart"],
+ udf: ["Filter", "Projection", "Aggregate"],
+ ml: ["Scorer", "PythonUDFV2"],
+ // Sinks (charts / visualizers) are terminal: no successor is suggested.
+ sink: [],
+};
+
+/**
+ * Per-operator overrides for the highest-value flows. Takes precedence over
the
+ * category successors above.
+ */
+const SPECIFIC_SUCCESSORS: Record<string, string[]> = {
+ CSVFileScan: ["Filter", "Projection", "KeywordSearch"],
+ JSONLFileScan: ["Projection", "Filter", "UnnestString"],
+ Filter: ["Aggregate", "Projection", "Sort"],
+ Projection: ["Aggregate", "Filter", "Sort"],
+ KeywordSearch: ["Aggregate", "Projection", "Filter"],
+ Sort: ["BarChart", "Projection", "Limit"],
+};
+
+/** Fallback successors for operators with no category-specific rule. */
+export const DEFAULT_SUCCESSORS: string[] = ["Filter", "Projection",
"PythonUDFV2"];
+
+/**
+ * Short rationale per recommended (target) operator, describing why it is a
+ * sensible next step. Falls back to a generic phrase for anything not listed.
+ */
+const RATIONALE: Record<string, string> = {
+ Filter: "Keep only the rows you care about",
+ Projection: "Select, drop, or rename columns",
+ TypeCasting: "Convert column types before further processing",
+ KeywordSearch: "Search a text column for keywords",
+ Aggregate: "Summarize the data with group-by aggregations",
+ Sort: "Order the rows by one or more columns",
+ Limit: "Keep only the first N rows",
+ BarChart: "Visualize the results as a bar chart",
+ LineChart: "Visualize the results as a line chart",
+ PythonUDFV2: "Run custom Python logic on the rows",
+ UnnestString: "Split a delimited string column into rows",
+ Scorer: "Evaluate model predictions against labels",
+};
+
+const GENERIC_RATIONALE = "A common next step for this operator";
+
+/** Suffixes that reliably identify terminal visualization/sink operators. */
+const SINK_SUFFIXES = ["Chart", "Plot", "Visualizer"];
+
+/** Explicit sink operators whose names don't end in a {@link SINK_SUFFIXES}.
*/
+const EXTRA_SINKS = new Set([
+ "Histogram",
+ "Histogram2D",
+ "HeatMap",
+ "NetworkGraph",
+ "SankeyDiagram",
+ "NestedTable",
+ "FigureFactoryTable",
+ "TablesPlot",
+]);
+
+/**
+ * Best-effort category for an operator not listed in {@link
OPERATOR_CATEGORY},
+ * using naming heuristics. Returns `undefined` when nothing matches so the
+ * caller can fall back to {@link DEFAULT_SUCCESSORS}.
+ */
+export function inferCategory(operatorType: string): OperatorCategory |
undefined {
+ if (isSink(operatorType)) return "sink";
+ if (operatorType.startsWith("Sklearn") ||
operatorType.startsWith("HuggingFace")) return "ml";
+ if (operatorType.endsWith("Source")) return "source";
+ if (operatorType.endsWith("FileScan")) return "source";
+ if (operatorType.endsWith("UDF") || operatorType.endsWith("UDFV2")) return
"udf";
+ return undefined;
+}
+
+/** Whether an operator is a terminal visualization/sink with no useful
successor. */
+export function isSink(operatorType: string): boolean {
+ if (EXTRA_SINKS.has(operatorType)) return true;
+ if (OPERATOR_CATEGORY[operatorType] === "sink") return true;
Review Comment:
Nit: None of the entries in the category map above use the sink label, so
this check never matches. Could we drop it?
##########
agent-service/src/recommender/hardcoded-rules.ts:
##########
@@ -0,0 +1,210 @@
+/**
+ * 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.
+ */
+
+/**
+ * Hardcoded "what usually comes next" table for the Version 1 operator
+ * recommender (apache/texera#5240). Kept deliberately small and readable: a
+ * coarse category per operator, a ranked successor list per category, plus a
+ * handful of specific overrides for the most common dataflow patterns.
+ *
+ * Operator type strings here must match the `@JsonSubTypes` names registered
on
+ * `LogicalOp` (the catalog the frontend and compiler use). Suggestions are
+ * validated against the live operator catalog before being returned, so a
stale
+ * entry here degrades to "not suggested" rather than to a broken suggestion.
+ */
+
+export type OperatorCategory = "source" | "transform" | "aggregate" | "join" |
"rowOps" | "udf" | "ml" | "sink";
+
+/**
+ * Explicit category for operators whose successors don't follow from a naming
+ * heuristic. Operators absent here fall back to {@link inferCategory}.
+ */
+const OPERATOR_CATEGORY: Record<string, OperatorCategory> = {
+ // Sources — read data into the workflow.
+ CSVFileScan: "source",
+ CSVOldFileScan: "source",
+ ParallelCSVFileScan: "source",
+ JSONLFileScan: "source",
+ FileScan: "source",
+ ArrowSource: "source",
+ TextInput: "source",
+ URLFetcher: "source",
+ FileLister: "source",
+ PostgreSQLSource: "source",
+ MySQLSource: "source",
+ AsterixDBSource: "source",
+ SQLSource: "source",
+ TwitterSearch: "source",
+ TwitterFullArchiveSearch: "source",
+ RedditSearch: "source",
+ PythonUDFSourceV2: "source",
+ RUDFSource: "source",
+
+ // Transforms — reshape rows/columns.
+ Filter: "transform",
+ Projection: "transform",
+ TypeCasting: "transform",
+ Regex: "transform",
+ KeywordSearch: "transform",
+ SubstringSearch: "transform",
+ DictionaryMatcher: "transform",
+ UnnestString: "transform",
+ Split: "transform",
+
+ // Aggregations / reducers.
+ Aggregate: "aggregate",
+ PythonTableReducer: "aggregate",
+ Scorer: "aggregate",
+
+ // Joins and set operations (multi-input).
+ HashJoin: "join",
+ IntervalJoin: "join",
+ CartesianProduct: "join",
+ Union: "join",
+ Intersect: "join",
+ Difference: "join",
+ SymmetricDifference: "join",
+
+ // Ordering / sampling / row-count operators.
+ Sort: "rowOps",
+ SortPartitions: "rowOps",
+ StableMergeSort: "rowOps",
+ Limit: "rowOps",
+ Distinct: "rowOps",
+ RandomKSampling: "rowOps",
+ ReservoirSampling: "rowOps",
+
+ // User-defined functions.
+ PythonUDFV2: "udf",
+ DualInputPortsPythonUDFV2: "udf",
+ PythonLambdaFunction: "udf",
+ JavaUDF: "udf",
+ RUDF: "udf",
+};
+
+/** Ranked successor list per category, most-likely first. */
+const CATEGORY_SUCCESSORS: Record<OperatorCategory, string[]> = {
+ source: ["Filter", "Projection", "TypeCasting", "KeywordSearch"],
+ transform: ["Aggregate", "Projection", "Sort", "PythonUDFV2"],
+ aggregate: ["BarChart", "LineChart", "Sort"],
+ join: ["Projection", "Aggregate", "Filter"],
+ rowOps: ["Aggregate", "Projection", "BarChart"],
+ udf: ["Filter", "Projection", "Aggregate"],
+ ml: ["Scorer", "PythonUDFV2"],
+ // Sinks (charts / visualizers) are terminal: no successor is suggested.
+ sink: [],
+};
+
+/**
+ * Per-operator overrides for the highest-value flows. Takes precedence over
the
+ * category successors above.
+ */
+const SPECIFIC_SUCCESSORS: Record<string, string[]> = {
+ CSVFileScan: ["Filter", "Projection", "KeywordSearch"],
+ JSONLFileScan: ["Projection", "Filter", "UnnestString"],
+ Filter: ["Aggregate", "Projection", "Sort"],
+ Projection: ["Aggregate", "Filter", "Sort"],
+ KeywordSearch: ["Aggregate", "Projection", "Filter"],
+ Sort: ["BarChart", "Projection", "Limit"],
+};
+
+/** Fallback successors for operators with no category-specific rule. */
+export const DEFAULT_SUCCESSORS: string[] = ["Filter", "Projection",
"PythonUDFV2"];
+
+/**
+ * Short rationale per recommended (target) operator, describing why it is a
+ * sensible next step. Falls back to a generic phrase for anything not listed.
+ */
+const RATIONALE: Record<string, string> = {
+ Filter: "Keep only the rows you care about",
+ Projection: "Select, drop, or rename columns",
+ TypeCasting: "Convert column types before further processing",
+ KeywordSearch: "Search a text column for keywords",
+ Aggregate: "Summarize the data with group-by aggregations",
+ Sort: "Order the rows by one or more columns",
+ Limit: "Keep only the first N rows",
+ BarChart: "Visualize the results as a bar chart",
+ LineChart: "Visualize the results as a line chart",
+ PythonUDFV2: "Run custom Python logic on the rows",
+ UnnestString: "Split a delimited string column into rows",
+ Scorer: "Evaluate model predictions against labels",
+};
+
+const GENERIC_RATIONALE = "A common next step for this operator";
+
+/** Suffixes that reliably identify terminal visualization/sink operators. */
+const SINK_SUFFIXES = ["Chart", "Plot", "Visualizer"];
+
+/** Explicit sink operators whose names don't end in a {@link SINK_SUFFIXES}.
*/
+const EXTRA_SINKS = new Set([
+ "Histogram",
+ "Histogram2D",
+ "HeatMap",
+ "NetworkGraph",
+ "SankeyDiagram",
+ "NestedTable",
+ "FigureFactoryTable",
+ "TablesPlot",
+]);
+
+/**
+ * Best-effort category for an operator not listed in {@link
OPERATOR_CATEGORY},
+ * using naming heuristics. Returns `undefined` when nothing matches so the
+ * caller can fall back to {@link DEFAULT_SUCCESSORS}.
+ */
+export function inferCategory(operatorType: string): OperatorCategory |
undefined {
Review Comment:
Guessing categories from case-sensitive name prefixes and suffixes misses 7
visualizations (such as Scatterplot and Word Cloud, which then suggest Filter,
Projection, and Python UDF on their HTML output port) and 4 trainers (such as
SVM Classifier), and will silently misclassify future operators whose names do
not match those suffixes. Because the loaded catalog metadata already includes
each operator's group name and port list, could we classify from catalog
metadata instead of name suffixes?
##########
agent-service/src/server.ts:
##########
@@ -388,6 +390,45 @@ const agentsRouter = new Elysia({ prefix: "/agents" })
}
);
+// Stateless ambient operator recommender (apache/texera#5240). Given the
+// operator a user just added, returns a short ranked list of likely next
+// operators for the canvas to render as suggestions. Version 1 uses a
+// hardcoded rule table with no LLM call, so it needs no user token and no
+// per-request model configuration; it only reads the process-wide operator
+// catalog to validate and label its suggestions.
+const recommendRouter = new Elysia({ prefix: "/recommend" })
+ // Local-scoped error handler, mirroring agentsRouter: body-schema and
+ // malformed-JSON failures are client errors (400), not 500s.
+ .onError(({ code, error, set }) => {
+ log.error({ err: error }, "recommend request error");
+ const errorMessage = error instanceof Error ? error.message :
String(error);
+ if (code === "VALIDATION" || code === "PARSE") {
+ set.status = 400;
+ return { error: errorMessage || "Invalid request body" };
+ }
+ set.status = 500;
+ return { error: errorMessage || "Internal server error" };
+ })
+ .post(
+ "/",
Review Comment:
Nit: Prettier fails on the 5-space indentation in this handler and in the
whitespace test in the route spec. Could we run the formatter before pushing?
--
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]