gupta-sahil01 commented on code in PR #6436: URL: https://github.com/apache/texera/pull/6436#discussion_r4687887051
########## 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: Done in 4ba64c9a0. Candidates whose catalog entry has no input ports are skipped unless the operator supports dynamic input ports. Unit tests cover both cases. ########## 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: Added in 4ba64c9a0. The new route test holds the metadata fetch pending, sends two concurrent requests, and asserts the catalog endpoint is called once and both responses come back validated. I also checked that it fails (two fetches) when the shared in-flight promise is removed. -- 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]
