Xiao-zhen-Liu commented on code in PR #6436:
URL: https://github.com/apache/texera/pull/6436#discussion_r4672832169


##########
agent-service/src/operator-recommendation/operator-recommender.ts:
##########
@@ -0,0 +1,127 @@
+/**
+ * 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_OPERATOR_RECOMMENDATION_LIMIT,
+  DEFAULT_SOURCE_PORT_ID,
+  MAX_OPERATOR_RECOMMENDATION_LIMIT,
+  type OperatorRecommendation,
+  type OperatorRecommendationRequest,
+  type OperatorRecommendationResponse,
+} from "./operator-recommendation-types";
+import {
+  candidateSuccessors,
+  categoryOf,
+  rationaleFor,
+  targetPortIdFor,
+  type OperatorCatalogEntry,
+} from "./operator-recommendation-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 uninitialized path).
+ */
+export interface OperatorCatalog {
+  isInitialized(): boolean;
+  getSchema(operatorType: string): unknown;
+  getAdditionalMetadata(operatorType: string): OperatorCatalogEntry | 
undefined;
+}
+
+// Top suggestion scores 0.9 and each lower rank drops one step, floored at 
0.3.
+// With MAX_OPERATOR_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;
+
+const OUTPUT_PORT_ID = /^output-(\d+)$/;
+
+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_OPERATOR_RECOMMENDATION_LIMIT;
+  return Math.min(MAX_OPERATOR_RECOMMENDATION_LIMIT, Math.max(1, 
Math.floor(limit)));
+}
+
+/** Whether `portId` names an output port the operator actually has. */
+function hasOutputPort(entry: OperatorCatalogEntry | undefined, portId: 
string): boolean {
+  const match = OUTPUT_PORT_ID.exec(portId);
+  if (!match) return false;
+  // Without metadata, or with user-added ports, any well-formed port may 
exist.
+  if (!entry?.outputPorts || entry.dynamicOutputPorts) return true;
+  return Number(match[1]) < entry.outputPorts.length;
+}
+
+/**
+ * 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, the operator is classified from its metadata,
+ * suggestions are filtered to operator types that actually exist (so a stale
+ * rule never yields an unusable suggestion), and each suggestion is enriched
+ * with its display name and the input port to wire to. Without an initialized
+ * catalog, only the per-operator overrides and the generic fallback apply, and
+ * the raw ranked candidates are returned unvalidated.
+ */
+export function recommendOperators(
+  req: OperatorRecommendationRequest,
+  catalog?: OperatorCatalog
+): OperatorRecommendationResponse {
+  const operatorType = req.operatorType?.trim();
+  const limit = clampLimit(req.limit);
+  const empty: OperatorRecommendationResponse = { recommendations: [], 
strategy: "hardcoded" };
+
+  if (!operatorType) return empty;
+
+  const catalogReady = catalog?.isInitialized() ?? false;

Review Comment:
   Because classification and port checks depend on loaded catalog metadata, 
returning raw candidates when the catalog is unavailable breaks those rules: 
during a backend 503, Bar Chart or Training: Logistic Regression suggests 
Filter, Projection, and unvalidated Python UDF, and nonexistent output ports 
return suggestions. Even after loading, unknown operator types still return 
suggestions on nonexistent ports. Could we return an empty list whenever the 
catalog is uninitialized or does not contain the requested operator?



##########
agent-service/src/server.ts:
##########
@@ -389,6 +401,65 @@ const agentsRouter = new Elysia({ prefix: "/agents" })
     }
   );
 
+// The process-wide operator catalog, loading it first if startup could not
+// (for example because the backend was not ready yet). Concurrent requests
+// share one load; a failed load is logged and retried on the next request, and
+// the caller proceeds with the catalog uninitialized.
+let operatorCatalogLoad: Promise<unknown> | null = null;
+
+async function getOperatorCatalog(): Promise<WorkflowSystemMetadata> {
+  const catalog = WorkflowSystemMetadata.getInstance();
+  if (!catalog.isInitialized()) {
+    operatorCatalogLoad ??= WorkflowSystemMetadata.initializeGlobal()
+      .catch(error => log.warn({ err: error }, "failed to load operator 
catalog; will retry on next request"))
+      .finally(() => {
+        operatorCatalogLoad = null;
+      });
+    await operatorCatalogLoad;
+  }
+  return WorkflowSystemMetadata.getInstance();
+}
+
+// Stateless 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, but still requires the signed-in user's token, as agent 
creation
+// does, so that Version 2 can call the LLM gateway as that user without
+// changing the auth contract.
+const operatorRecommendationsRouter = new Elysia({ prefix: 
"/operator-recommendations" })
+  // 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 }, "operator recommendation 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 = ERROR_STATUS[errorMessage] ?? 500;
+    return { error: errorMessage || "Internal server error" };
+  })
+  .post(
+    "/",
+    async ({ body, headers, set }) => {
+      requireUserToken(headers.authorization);
+      const req = body as OperatorRecommendationRequest;
+      const operatorType = req.operatorType.trim();
+      if (!operatorType) {
+        set.status = 400;
+        return { error: "operatorType must be a non-empty string" };
+      }
+      return recommendOperators({ ...req, operatorType }, await 
getOperatorCatalog());
+    },
+    {
+      body: t.Object({
+        operatorType: t.String({ minLength: 1, maxLength: 
MAX_OPERATOR_TYPE_LENGTH }),
+        sourcePortID: t.Optional(t.String({ pattern: "^output-[0-9]+$" })),

Review Comment:
   Unlike the operator type field above, the source port field has no maximum 
length bound and accepts leading zeros, so a multi-megabyte digit string passes 
validation and non-canonical values like output-00 map to the first port. Could 
we add a short maximum length (such as 16 characters) and disallow leading 
zeros in both the route validator and the recommender's port check?



##########
agent-service/src/operator-recommendation/operator-recommender.ts:
##########
@@ -0,0 +1,127 @@
+/**
+ * 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_OPERATOR_RECOMMENDATION_LIMIT,
+  DEFAULT_SOURCE_PORT_ID,
+  MAX_OPERATOR_RECOMMENDATION_LIMIT,
+  type OperatorRecommendation,
+  type OperatorRecommendationRequest,
+  type OperatorRecommendationResponse,
+} from "./operator-recommendation-types";
+import {
+  candidateSuccessors,
+  categoryOf,
+  rationaleFor,
+  targetPortIdFor,
+  type OperatorCatalogEntry,
+} from "./operator-recommendation-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 uninitialized path).
+ */
+export interface OperatorCatalog {
+  isInitialized(): boolean;
+  getSchema(operatorType: string): unknown;
+  getAdditionalMetadata(operatorType: string): OperatorCatalogEntry | 
undefined;
+}
+
+// Top suggestion scores 0.9 and each lower rank drops one step, floored at 
0.3.
+// With MAX_OPERATOR_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;
+
+const OUTPUT_PORT_ID = /^output-(\d+)$/;
+
+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_OPERATOR_RECOMMENDATION_LIMIT;
+  return Math.min(MAX_OPERATOR_RECOMMENDATION_LIMIT, Math.max(1, 
Math.floor(limit)));
+}
+
+/** Whether `portId` names an output port the operator actually has. */
+function hasOutputPort(entry: OperatorCatalogEntry | undefined, portId: 
string): boolean {
+  const match = OUTPUT_PORT_ID.exec(portId);
+  if (!match) return false;
+  // Without metadata, or with user-added ports, any well-formed port may 
exist.
+  if (!entry?.outputPorts || entry.dynamicOutputPorts) return true;
+  return Number(match[1]) < entry.outputPorts.length;
+}
+
+/**
+ * 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, the operator is classified from its metadata,
+ * suggestions are filtered to operator types that actually exist (so a stale
+ * rule never yields an unusable suggestion), and each suggestion is enriched
+ * with its display name and the input port to wire to. Without an initialized
+ * catalog, only the per-operator overrides and the generic fallback apply, and
+ * the raw ranked candidates are returned unvalidated.
+ */
+export function recommendOperators(
+  req: OperatorRecommendationRequest,
+  catalog?: OperatorCatalog
+): OperatorRecommendationResponse {
+  const operatorType = req.operatorType?.trim();
+  const limit = clampLimit(req.limit);
+  const empty: OperatorRecommendationResponse = { recommendations: [], 
strategy: "hardcoded" };
+
+  if (!operatorType) return empty;
+
+  const catalogReady = catalog?.isInitialized() ?? false;
+  const metadataOf = (type: string) => (catalogReady ? 
catalog!.getAdditionalMetadata(type) : undefined);
+
+  const source = metadataOf(operatorType);
+  if (!hasOutputPort(source, req.sourcePortID ?? DEFAULT_SOURCE_PORT_ID)) 
return empty;
+  const sourceCategory = categoryOf(operatorType, source);
+
+  const seen = new Set<string>();
+  const recommendations: OperatorRecommendation[] = [];
+
+  for (const candidate of candidateSuccessors(operatorType, sourceCategory)) {
+    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: an
+    // operator exists in the catalog exactly when its schema was loaded.
+    if (catalogReady && catalog!.getSchema(candidate) === undefined) continue;
+    seen.add(candidate);
+
+    const target = metadataOf(candidate);

Review Comment:
   Each candidate is checked for existence in the catalog, but not for whether 
it has an input port to wire to, so a future rule change or V2 model suggesting 
a source operator would still return a target port that does not exist on that 
operator. Could we skip candidates whose catalog entry has no input ports (and 
does not support dynamic input ports)?



##########
agent-service/src/server.operator-recommendation.spec.ts:
##########
@@ -0,0 +1,180 @@
+/**
+ * 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 { afterEach, beforeEach, describe, expect, spyOn, test, type Mock } 
from "bun:test";
+import { buildApp } from "./server";
+import { env } from "./config/env";
+import { WorkflowSystemMetadata } from "./agent/util/workflow-system-metadata";
+import { OPERATOR_CATALOG_FIXTURE } from 
"./operator-recommendation/operator-catalog.fixture";
+import type { OperatorRecommendationResponse } from 
"./operator-recommendation/operator-recommendation-types";
+
+const API = env.API_PREFIX;
+const ROUTE = `http://localhost${API}/operator-recommendations`;
+const app = buildApp();
+
+function mintTestToken(expiresInSeconds = 3600): string {
+  const header = Buffer.from(JSON.stringify({ alg: "HS256", typ: "JWT" 
})).toString("base64url");
+  const payload = Buffer.from(
+    JSON.stringify({
+      sub: "tester",
+      userId: 1,
+      role: "REGULAR",
+      exp: Math.floor(Date.now() / 1000) + expiresInSeconds,
+    })
+  ).toString("base64url");
+  return `${header}.${payload}.test-signature`;
+}
+
+const TOKEN = mintTestToken();
+
+async function postRecommend(body: unknown, token: string | null = TOKEN): 
Promise<Response> {
+  return app.handle(
+    new Request(ROUTE, {
+      method: "POST",
+      headers: {
+        "Content-Type": "application/json",
+        ...(token ? { Authorization: `Bearer ${token}` } : {}),
+      },
+      body: JSON.stringify(body),
+    })
+  );
+}
+
+async function recommend(body: unknown): 
Promise<OperatorRecommendationResponse> {
+  const res = await postRecommend(body);
+  expect(res.status).toBe(200);
+  return (await res.json()) as OperatorRecommendationResponse;
+}
+
+// Each test gets a fresh, unloaded catalog singleton, and the backend's
+// operator-metadata endpoint is served by a fetch mock, so the route loads the
+// real WorkflowSystemMetadata class from the fixture on its first request.
+let savedCatalog: unknown;
+let fetchSpy: Mock<typeof fetch>;
+
+function respondWith(makeResponse: () => Response): void {
+  fetchSpy.mockImplementation((async () => makeResponse()) as unknown as 
typeof fetch);
+}
+
+function serveCatalog(): void {
+  respondWith(() => Response.json(OPERATOR_CATALOG_FIXTURE));
+}
+
+function failCatalog(): void {
+  respondWith(() => new Response("backend not ready", { status: 503 }));
+}
+
+beforeEach(() => {
+  savedCatalog = (WorkflowSystemMetadata as any).instance;
+  (WorkflowSystemMetadata as any).instance = undefined;
+  fetchSpy = spyOn(globalThis, "fetch");
+  serveCatalog();
+});
+
+afterEach(() => {
+  fetchSpy.mockRestore();
+  (WorkflowSystemMetadata as any).instance = savedCatalog;
+});
+
+describe("POST /operator-recommendations", () => {
+  test("returns validated, named suggestions from the loaded catalog", async 
() => {
+    const data = await recommend({ operatorType: "CSVFileScan" });
+    expect(data.strategy).toBe("hardcoded");
+    expect(data.recommendations.map(r => r.operatorType)).toEqual(["Filter", 
"Projection", "KeywordSearch"]);
+    expect(data.recommendations.map(r => 
r.userFriendlyName)).toEqual(["Filter", "Projection", "Keyword Search"]);
+    for (const rec of data.recommendations) {
+      expect(rec.targetPortID).toBe("input-0");
+      expect(rec.score).toBeGreaterThan(0);
+      expect(rec.reason.length).toBeGreaterThan(0);
+    }
+  });
+
+  test("classifies from catalog metadata and targets the model port", async () 
=> {
+    const trained = await recommend({ operatorType: 
"SklearnTrainingLogisticRegression" });
+    expect(trained.recommendations.map(r => [r.operatorType, 
r.targetPortID])).toEqual([
+      ["SklearnPrediction", "input-0"],
+      ["SklearnTesting", "input-0"],
+    ]);
+    expect((await recommend({ operatorType: "Scatterplot" 
})).recommendations).toEqual([]);
+  });
+
+  test("honors the requested source port and limit", async () => {
+    expect((await recommend({ operatorType: "Split", sourcePortID: "output-1" 
})).recommendations.length).toBe(3);
+    expect((await recommend({ operatorType: "Filter", sourcePortID: "output-1" 
})).recommendations).toEqual([]);
+    expect((await recommend({ operatorType: "Filter", limit: 1 
})).recommendations).toHaveLength(1);
+  });
+
+  test("retries loading the catalog on a later request when the backend was 
not ready", async () => {

Review Comment:
   Nit: This test covers sequential retry after a backend 503, while the shared 
in-flight promise that deduplicates concurrent catalog loads is not yet 
exercised. Could we add a test sending two concurrent requests against a 
pending metadata fetch and asserting the catalog endpoint is called only once?



-- 
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