sailfork / t3code-github / .repos/ alchemy-effect/ packages/ gcp/ src/ AIPlatform/ NasJob.ts

import * as aiplatform from "@distilled.cloud/gcp/aiplatform_v1";
import { Unowned } from "alchemy/AdoptPolicy";
import { isResolved } from "alchemy/Diff";
import * as Provider from "alchemy/Provider";
import { Resource } from "alchemy/Resource";
import { tagRecord } from "alchemy/Tags";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schedule from "effect/Schedule";
import * as Stream from "effect/Stream";
import { GcpEnvironment } from "../Environment.ts";
import { hasAlchemyLabels } from "../Labels.ts";
import type { Providers } from "../Providers.ts";
import { isJobTerminal } from "./internal.ts";
import {
  alchemyIdFilter,
  createInternalLabels,
  hasAlchemyPrefix,
  listLocations,
  locationOf,
  lastSegment,
  normalizeLocation,
  projectOf,
  stableJson,
  toDisplayName,
  toLabels,
  userLabels,
} from "./names.ts";
import { waitForOperation } from "./operations.ts";

export type NasJobProps = {
  /**
   * Vertex AI location. Immutable — changing it replaces the job.
   * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
   */
  location?: string;
  /**
   * Display name (max 128 Unicode characters). Generated from the stack,
   * stage, and logical id when omitted.
   */
  displayName?: string;
  /**
   * User labels. Alchemy ownership labels are merged in automatically.
   */
  labels?: Record<string, string>;
  /**
   * Neural Architecture Search specification.
   */
  nasJobSpec: aiplatform.GoogleCloudAiplatformV1NasJobSpec;
  /**
   * Enable restricted-image training for the tenant project.
   * @default false
   */
  enableRestrictedImageTraining?: boolean;
  /**
   * Customer-managed encryption key. Immutable.
   */
  encryptionSpec?: aiplatform.GoogleCloudAiplatformV1EncryptionSpec;
};

export type NasJob = Resource<
  "GCP.AIPlatform.NasJob",
  NasJobProps,
  {
    /** Full resource name. */
    name: string;
    /** Job id (last path segment). */
    nasJobId: string;
    /** Project id. */
    project: string;
    /** Location id. */
    location: string;
    /** Display name. */
    displayName: string | undefined;
    /** User labels (Alchemy ownership labels stripped). */
    labels: Record<string, string>;
    /** Job state. */
    state: string | undefined;
    /** Whether restricted-image training is enabled. */
    enableRestrictedImageTraining: boolean;
    /** RFC3339 creation timestamp. */
    createTime: string | undefined;
    /** RFC3339 start timestamp. */
    startTime: string | undefined;
    /** RFC3339 end timestamp. */
    endTime: string | undefined;
  },
  never,
  Providers
>;

/**
 * A Vertex AI Neural Architecture Search job.
 *
 * The API assigns the job id. There is no update method — changing display
 * name, labels, or `nasJobSpec` replaces the job. Delete cancels a running
 * job first.
 *
 * ### Creating a NasJob
 * **Example:** Multi-trial search
 * ```typescript
 * const job = yield* GCP.AIPlatform.NasJob("Search", {
 *   nasJobSpec: {
 *     searchSpaceSpec: "{}",
 *     multiTrialAlgorithmSpec: {
 *       metric: { metricId: "accuracy", goal: "MAXIMIZE" },
 *       searchTrialSpec: {
 *         maxTrialCount: 1,
 *         maxParallelTrialCount: 1,
 *         searchTrialJobSpec: {
 *           workerPoolSpecs: [{
 *             machineSpec: { machineType: "n1-standard-4" },
 *             replicaCount: "1",
 *             containerSpec: { imageUri: "gcr.io/cloud-aiplatform/training/tf-cpu.2-8:latest" },
 *           }],
 *         },
 *       },
 *     },
 *   },
 * });
 * ```
 *
 * @resource
 * @category AIPlatform
 */
export const NasJob = Resource<NasJob>("GCP.AIPlatform.NasJob");

export class NasJobNotResolved extends Data.TaggedError("GCP.AIPlatform.NasJobNotResolved")<{
  resourceName: string;
}> {}

export class NasJobStillExists extends Data.TaggedError("GCP.AIPlatform.NasJobStillExists")<{
  resourceName: string;
}> {}

const toAttrs = (job: aiplatform.GoogleCloudAiplatformV1NasJob, project: string) => {
  const name = job.name ?? "";
  return {
    name,
    nasJobId: lastSegment(name),
    project: projectOf(name, project),
    location: locationOf(name),
    displayName: job.displayName,
    labels: userLabels(job.labels),
    state: job.state,
    enableRestrictedImageTraining: job.enableRestrictedImageTraining === true,
    createTime: job.createTime,
    startTime: job.startTime,
    endTime: job.endTime,
  };
};

const getByName = (name: string) =>
  aiplatform
    .getProjectsLocationsNasJobs({ name })
    .pipe(Effect.catchTag("NotFound", () => Effect.undefined));

const listPage = (parent: string, filter?: string) =>
  aiplatform.listProjectsLocationsNasJobs.pages({ parent, pageSize: 100, filter }).pipe(
    Stream.runCollect,
    Effect.map((pages) => Array.from(pages).flatMap((page) => page.nasJobs ?? [])),
    Effect.catchTag("NotFound", () =>
      Effect.succeed([] as aiplatform.GoogleCloudAiplatformV1NasJob[]),
    ),
  );

const findOwned = (project: string, location: string, labels: Record<string, string>) =>
  listPage(`projects/${project}/locations/${location}`, alchemyIdFilter(labels)).pipe(
    Effect.map((items) => items.find((item) => hasAlchemyPrefix(item.labels)) ?? undefined),
  );

const waitUntilGone = (name: string) =>
  getByName(name).pipe(
    Effect.filterOrFail(
      (job) => job === undefined,
      () => new NasJobStillExists({ resourceName: name }),
    ),
    Effect.asVoid,
    Effect.retry({
      while: (error) => error._tag === "GCP.AIPlatform.NasJobStillExists",
      times: 10,
      schedule: Schedule.spaced("2 seconds"),
    }),
  );

export const NasJobProvider = () =>
  Provider.succeed(NasJob, {
    stables: ["name", "nasJobId", "project", "location", "createTime"],

    diff: Effect.fn(function* ({ news, olds, output }) {
      const env = yield* GcpEnvironment.current;
      if (!isResolved(news)) return undefined;
      const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
      const nextLocation = normalizeLocation(
        news.location ?? olds?.location ?? output?.location,
        env.region,
      );
      const previousDisplay = olds?.displayName ?? output?.displayName;
      const displayChanged =
        news.displayName !== undefined &&
        previousDisplay !== undefined &&
        news.displayName !== previousDisplay;
      const specsChanged =
        olds !== undefined && stableJson(olds.nasJobSpec) !== stableJson(news.nasJobSpec);
      if (previousLocation !== nextLocation || displayChanged || specsChanged) {
        return { action: "replace" as const, deleteFirst: false };
      }
      return undefined;
    }),

    read: Effect.fn(function* ({ id, olds, output }) {
      const env = yield* GcpEnvironment.current;
      const location = normalizeLocation(olds?.location ?? output?.location, env.region);
      const ownership = yield* createInternalLabels(id);
      const existing =
        (output?.name !== undefined ? yield* getByName(output.name) : undefined) ??
        (yield* findOwned(env.project, location, ownership));
      if (existing === undefined) return undefined;
      const attrs = toAttrs(existing, env.project);
      return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
    }),

    list: () =>
      Effect.gen(function* () {
        const env = yield* GcpEnvironment.current;
        const pages = yield* Effect.forEach(
          listLocations(env.region),
          (location) => listPage(`projects/${env.project}/locations/${location}`),
          { concurrency: 4 },
        );
        return pages
          .flat()
          .filter((job) => hasAlchemyPrefix(job.labels))
          .map((job) => toAttrs(job, env.project));
      }),

    reconcile: Effect.fn(function* ({ id, news, output }) {
      const env = yield* GcpEnvironment.current;
      const location = normalizeLocation(news.location ?? output?.location, env.region);
      const displayName = yield* toDisplayName(id, news.displayName, output?.displayName);
      const desiredLabels = {
        ...toLabels(news.labels),
        ...(yield* createInternalLabels(id)),
      };

      let current =
        (output?.name !== undefined ? yield* getByName(output.name) : undefined) ??
        (yield* findOwned(env.project, location, desiredLabels));

      if (current === undefined) {
        const created = yield* aiplatform
          .createProjectsLocationsNasJobs({
            parent: `projects/${env.project}/locations/${location}`,
            body: {
              displayName,
              labels: desiredLabels,
              nasJobSpec: news.nasJobSpec,
              enableRestrictedImageTraining: news.enableRestrictedImageTraining === true,
              encryptionSpec: news.encryptionSpec,
            },
          })
          .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
        current = created ?? (yield* findOwned(env.project, location, desiredLabels));
      }

      if (current === undefined || current.name === undefined) {
        return yield* new NasJobNotResolved({
          resourceName: output?.name ?? `${location}/nasJobs`,
        });
      }

      return toAttrs(current, env.project);
    }),

    delete: Effect.fn(function* ({ output }) {
      yield* aiplatform
        .cancelProjectsLocationsNasJobs({
          name: output.name,
          body: {},
        })
        .pipe(Effect.catchTag(["NotFound", "BadRequest", "Conflict"], () => Effect.void));
      // Running jobs reject deletes; wait for the cancel to land.
      yield* getByName(output.name).pipe(
        Effect.repeat({
          schedule: Schedule.spaced("4 seconds"),
          until: (job) => job === undefined || isJobTerminal(job.state),
          times: 45,
        }),
      );
      const operation = yield* aiplatform
        .deleteProjectsLocationsNasJobs({ name: output.name })
        .pipe(
          Effect.retry({
            while: (error) => error._tag === "Conflict",
            times: 8,
            schedule: Schedule.spaced("2 seconds"),
          }),
          Effect.catchTag("NotFound", () => Effect.undefined),
        );
      if (operation !== undefined) {
        yield* waitForOperation(operation, { notFoundOk: true });
      }
      yield* waitUntilGone(output.name);
    }),
  });