sailfork / t3code-github / .repos/ alchemy-effect/ packages/ alchemy/ test/ plan.test.ts

import { describe, expect } from "@alchemy.run/test";
import * as Test from "@alchemy.run/test/Alchemy";
import * as Cause from "effect/Cause";
import * as Config from "effect/Config";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as Redacted from "effect/Redacted";
import { Action } from "@/Action";
import { adopt, AdoptPolicy, Unowned } from "@/AdoptPolicy";
import { AuthProviders } from "@/Auth/AuthProvider.ts";
import { dedupeBindings, isResolved } from "@/Diff";
import { onEvent, type Event } from "@/Events.ts";
import type { Input, InputProps } from "@/Input";
import * as Namespace from "@/Namespace.ts";
import * as Output from "@/Output";
import * as Plan from "@/Plan";
import { UnsatisfiedResourceCycle } from "@/Plan";
import * as Provider from "@/Provider";
import { remote } from "@/ProviderMode.ts";
import { renamedFrom } from "@/Rename.ts";
import { Resource, type ResourceBinding } from "@/Resource";
import { packEnvValue } from "@/RuntimeContext.ts";
import * as Stack from "@/Stack";
import { Stage } from "@/Stage";
import {
  InMemoryService,
  inMemoryState,
  State,
  type ResourceState,
  type ResourceStatus,
} from "@/State";
import { hashInput } from "@/Util/sha256";
import {
  AliasedWidget,
  aliasedWidgetProvider,
  ArtifactProbe,
  BindingTarget,
  Bucket,
  capturedConfigHost,
  Function,
  inDev,
  KindStablesResource,
  ModalResource,
  NoPrecreateBindingTarget,
  OverrideStablesResource,
  ProbeBinding,
  Queue,
  ResourceFailure,
  StaticStablesResource,
  TestLayers,
  TestResource,
  TestResourceHooks,
  type TestResourceProps,
} from "./test.resources";

const TEST_STACK = "test";
const TEST_STAGE = "test";

// Fresh in-memory state per test run so seeded resources from one test
// don't leak into another in the same file.
const freshState = Layer.effect(
  State,
  Effect.sync(() => InMemoryService({})),
);

const { test } = Test.make({ providers: TestLayers(), state: freshState });

// Resolve stack name/stage from ambient Stack if present (for test.provider)
// otherwise fall back to the file-level defaults (for plain test()).
const resolveStackId = Effect.gen(function* () {
  const ambient = yield* Effect.serviceOption(Stack.Stack);
  return Option.match(ambient, {
    onNone: () => ({ name: TEST_STACK, stage: TEST_STAGE }),
    onSome: (s) => ({ name: s.name, stage: s.stage }),
  });
});

const seed = (resources: Record<string, ResourceState>) =>
  Effect.gen(function* () {
    const { name, stage } = yield* resolveStackId;
    const state = yield* yield* State;
    for (const [fqn, value] of Object.entries(resources)) {
      yield* state.set({ stack: name, stage, fqn, value });
    }
  });

const instanceId = "852f6ec2e19b66589825efe14dca2971";

const makePlan = <A, Err = never, Req = never>(
  effect: Effect.Effect<A, Err, Req>,
  options?: Plan.FilteredPlanOptions,
): Effect.Effect<Plan.Plan<A | undefined>, Err, State> =>
  // @ts-expect-error - Stack.make's typing erases R unsoundly here
  Effect.gen(function* () {
    const { name, stage } = yield* resolveStackId;
    // @ts-expect-error
    return yield* effect.pipe(
      // @ts-expect-error
      Stack.make({ name, providers: Layer.empty, state: inMemoryState() }),
      Effect.provideService(Stage, stage),
      Effect.flatMap((stackSpec: any) => Plan.make(stackSpec, options)),
      Effect.provide(TestLayers()),
    );
  });

const makePlanWithCustomStack =
  (stackSpec: any) =>
  <A, Err = never, Req = never>(
    effect: Effect.Effect<A, Err, Req>,
  ): Effect.Effect<Plan.Plan<A>, Err, State> =>
    // @ts-expect-error
    Effect.gen(function* () {
      const { name, stage } = yield* resolveStackId;
      // @ts-expect-error
      return yield* effect.pipe(
        // @ts-expect-error
        Stack.make({ name, providers: Layer.empty, state: inMemoryState(), stack: stackSpec }),
        Effect.provideService(Stage, stage),
        Effect.flatMap(Plan.make),
        Effect.provide(TestLayers()),
      );
    });

describe("Action output convergence", { tags: ["unit", "local"] }, () => {
  const seedAction = (
    id: string,
    input: Record<string, unknown>,
    output: unknown,
    status: "ran" | "running" = "ran",
  ) =>
    Effect.gen(function* () {
      const { name, stage } = yield* resolveStackId;
      const state = yield* yield* State;
      const row = {
        kind: "action" as const,
        fqn: id,
        logicalId: id,
        namespace: undefined,
        actionType: "Compute",
        inputHash: yield* hashInput(input),
        input,
        downstream: ["Host"],
      };
      yield* state.set({
        stack: name,
        stage,
        fqn: id,
        value: status === "ran" ? { ...row, status, output } : { ...row, status },
      });
    });

  const seedHost = (value: string) =>
    seed({
      Host: {
        instanceId,
        providerVersion: 0,
        logicalId: "Host",
        fqn: "Host",
        namespace: undefined,
        resourceType: "Test.Function",
        status: "created",
        props: { name: "host", env: { RESULT: value } },
        attr: { name: "host", env: { RESULT: value }, functionArn: "arn:test:host" },
        bindings: [],
        downstream: [],
      },
    });

  test(
    "unchanged Action output in host env produces repeated noop plans without running the body",
    Effect.gen(function* () {
      let calls = 0;
      const Compute = Action("Compute", (_: { revision: string }) =>
        Effect.sync(() => {
          calls++;
          return { value: "v1" };
        }),
      );
      yield* seedAction("Compute", { revision: "one" }, { value: "v1" });
      yield* seedHost("v1");
      const program = Effect.gen(function* () {
        const result = yield* Compute({ revision: "one" });
        return yield* Function("Host", { name: "host", env: { RESULT: result.value } });
      });
      for (const _ of [1, 2]) {
        const plan = yield* program.pipe(makePlan);
        expect(plan.actions.Compute.action).toBe("noop");
        expect(plan.actions.Compute.downstream).toContain("Host");
        expect(plan.resources.Host.action).toBe("noop");
        expect(calls).toBe(0);
      }
    }),
  );

  test(
    "a new consumer receives the persisted output of a noop Action and retains its dependency edge",
    Effect.gen(function* () {
      const Compute = Action("Compute", (_: {}) => Effect.succeed({ value: "v1" }));
      yield* seedAction("Compute", {}, { value: "v1" });
      const plan = yield* Effect.gen(function* () {
        const result = yield* Compute({});
        return yield* Function("Host", { env: { RESULT: result.value } });
      }).pipe(makePlan);
      expect(plan.actions.Compute.action).toBe("noop");
      expect(plan.actions.Compute.downstream).toContain("Host");
      expect(plan.resources.Host).toMatchObject({
        action: "create",
        props: { env: { RESULT: "v1" } },
      });
    }),
  );

  test(
    "unchanged Action output in binding data does not dirty the host",
    Effect.gen(function* () {
      const Compute = Action("Compute", (_: {}) => Effect.succeed({ value: "v1" }));
      yield* seedAction("Compute", {}, { value: "v1" });
      yield* seed({
        Host: {
          instanceId,
          providerVersion: 0,
          logicalId: "Host",
          fqn: "Host",
          namespace: undefined,
          resourceType: "Test.BindingTarget",
          status: "created",
          props: { name: "host" },
          attr: { name: "host", string: "", env: { RESULT: "v1" }, replaceString: undefined },
          bindings: [{ sid: "Result", data: { env: { RESULT: "v1" } } }],
          downstream: [],
        },
      });
      const plan = yield* Effect.gen(function* () {
        const result = yield* Compute({});
        const host = yield* BindingTarget("Host", { name: "host" });
        yield* host.bind("Result", { env: { RESULT: result.value } });
        return host;
      }).pipe(makePlan);
      expect(plan.actions.Compute.action).toBe("noop");
      expect(plan.actions.Compute.downstream).toContain("Host");
      expect(plan.resources.Host.action).toBe("noop");
      expect(plan.resources.Host.bindings).toEqual([
        { sid: "Result", action: "noop", data: { env: { RESULT: "v1" } } },
      ]);
    }),
  );

  for (const scenario of ["changed input", "force", "unfinished prior run"] as const) {
    test(
      `${scenario} keeps the Action output unresolved instead of substituting stale state`,
      Effect.gen(function* () {
        const Compute = Action("Compute", (input: { revision: string }) =>
          Effect.succeed({ value: input.revision }),
        );
        yield* seedAction(
          "Compute",
          { revision: "one" },
          { value: "old" },
          scenario === "unfinished prior run" ? "running" : "ran",
        );
        yield* seedHost("old");
        const plan = yield* Effect.gen(function* () {
          const result = yield* Compute({ revision: scenario === "changed input" ? "two" : "one" });
          return yield* Function("Host", { name: "host", env: { RESULT: result.value } });
        }).pipe((program) => makePlan(program, { force: scenario === "force" }));
        expect(plan.actions.Compute.action).toBe("run");
        expect(plan.resources.Host.action).toBe("update");
        const host = plan.resources.Host;
        if (host.action !== "update") throw new Error("Expected a host update");
        expect(Output.hasOutputs(host.props.env.RESULT)).toBe(true);
        expect(plan.actions.Compute.downstream).toContain("Host");
      }),
    );
  }

  for (const value of [undefined, null, false, 0, ""] as const) {
    test(
      `persisted ${String(value)} is a valid Action result, not a missing output`,
      Effect.gen(function* () {
        const Compute = Action("Compute", (_: {}) => Effect.succeed(value));
        yield* seedAction("Compute", {}, value);
        yield* seedHost(String(value));
        const plan = yield* Effect.gen(function* () {
          const result = yield* Compute({});
          return yield* Function("Host", {
            name: "host",
            env: { RESULT: Output.map(result, (value) => String(value)) },
          });
        }).pipe(makePlan);
        expect(plan.actions.Compute.action).toBe("noop");
        expect(plan.resources.Host.action).toBe("noop");
      }),
    );
  }

  for (const changed of [false, true]) {
    test(
      `Action chains ${changed ? "invalidate downstream consumers when root input changes" : "converge when all inputs are unchanged"}`,
      Effect.gen(function* () {
        const Compute = Action("Compute", (input: { value: string }) =>
          Effect.succeed({ value: input.value }),
        );
        yield* seedAction("First", { value: "v1" }, { value: "v1" });
        yield* seedAction("Second", { value: "v1" }, { value: "v1" });
        yield* seedHost("v1");
        const plan = yield* Effect.gen(function* () {
          const first = yield* Compute("First", { value: changed ? "v2" : "v1" });
          const second = yield* Compute("Second", { value: first.value });
          return yield* Function("Host", { name: "host", env: { RESULT: second.value } });
        }).pipe(makePlan);
        expect(plan.actions.First.action).toBe(changed ? "run" : "noop");
        expect(plan.actions.Second.action).toBe(changed ? "run" : "noop");
        expect(plan.resources.Host.action).toBe(changed ? "update" : "noop");
        expect(plan.actions.First.downstream).toContain("Second");
        expect(plan.actions.Second.downstream).toContain("Host");
      }),
    );
  }

  test(
    "changing only the Action body preserves the existing input-based invalidation contract",
    Effect.gen(function* () {
      const Compute = Action("Compute", (_: {}) => Effect.succeed({ value: "new-body" }));
      yield* seedAction("Compute", {}, { value: "old-body" });
      const plan = yield* Effect.gen(function* () {
        const result = yield* Compute({});
        return yield* Function("Host", { env: { RESULT: result.value } });
      }).pipe(makePlan);
      expect(plan.actions.Compute.action).toBe("noop");
      expect(plan.resources.Host).toMatchObject({
        action: "create",
        props: { env: { RESULT: "old-body" } },
      });
    }),
  );

  test(
    "a literal environment converges while an unrelated Action remains noop",
    Effect.gen(function* () {
      const Compute = Action("Compute", (_: {}) => Effect.succeed({ value: "v1" }));
      yield* seedAction("Compute", {}, { value: "v1" });
      yield* seedHost("v1");
      const plan = yield* Effect.gen(function* () {
        yield* Compute({});
        return yield* Function("Host", { name: "host", env: { RESULT: "v1" } });
      }).pipe(makePlan);
      expect(plan.actions.Compute.action).toBe("noop");
      expect(plan.resources.Host.action).toBe("noop");
    }),
  );

  test(
    "a noop Action does not suppress changes to other consumer props",
    Effect.gen(function* () {
      const Compute = Action("Compute", (_: {}) => Effect.succeed({ value: "v1" }));
      yield* seedAction("Compute", {}, { value: "v1" });
      yield* seedHost("v1");
      const plan = yield* Effect.gen(function* () {
        const result = yield* Compute({});
        return yield* Function("Host", { name: "changed", env: { RESULT: result.value } });
      }).pipe(makePlan);
      expect(plan.actions.Compute.action).toBe("noop");
      expect(plan.resources.Host.action).toBe("update");
    }),
  );

  test(
    "an unchanged Action output does not hide a replacement-sensitive prop change",
    Effect.gen(function* () {
      const Compute = Action("Compute", (_: {}) => Effect.succeed({ value: "v1" }));
      yield* seedAction("Compute", {}, { value: "v1" });
      yield* seed({
        Host: {
          instanceId,
          providerVersion: 0,
          logicalId: "Host",
          fqn: "Host",
          namespace: undefined,
          resourceType: "Test.BindingTarget",
          status: "created",
          props: { name: "host", string: "v1", replaceString: "old" },
          attr: { name: "host", string: "v1", env: {}, replaceString: "old" },
          bindings: [],
          downstream: [],
        },
      });
      const plan = yield* Effect.gen(function* () {
        const result = yield* Compute({});
        return yield* BindingTarget("Host", {
          name: "host",
          string: result.value,
          replaceString: "new",
        });
      }).pipe(makePlan);
      expect(plan.actions.Compute.action).toBe("noop");
      expect(plan.resources.Host.action).toBe("replace");
    }),
  );

  for (const stable of [false, true]) {
    test.provider(
      `resource-backed Action inputs ${stable ? "reuse a stable property" : "invalidate a changing property"}`,
      (stack) =>
        Effect.gen(function* () {
          const Compute = Action("Compute", (input: { value: string }) => Effect.succeed(input));
          const program = (value: string) =>
            Effect.gen(function* () {
              const source = yield* TestResource("Source", { string: value });
              const result = yield* Compute({
                value: stable ? source.stableString : source.string,
              });
              return yield* Function("Host", { env: { RESULT: result.value } });
            });
          yield* stack.deploy(program("v1"));
          const plan = yield* stack.plan(program("v2"));
          expect(plan.resources.Source.action).toBe("update");
          expect(plan.actions.Compute.action).toBe(stable ? "noop" : "run");
          expect(plan.resources.Host.action).toBe(stable ? "noop" : "update");
          expect(plan.resources.Source.downstream).toContain("Compute");
          expect(plan.actions.Compute.downstream).toContain("Host");
        }),
    );
  }

  test(
    "partial stable attributes cannot prove that a whole-resource Action input is unchanged",
    Effect.gen(function* () {
      const source = { stableString: "Source", stableArray: ["Source"] };
      yield* seed({
        Source: {
          instanceId,
          providerVersion: 0,
          logicalId: "Source",
          fqn: "Source",
          namespace: undefined,
          resourceType: "Test.TestResource",
          status: "created",
          props: { string: "v1" },
          attr: source,
          bindings: [],
          downstream: ["Compute"],
        },
      });
      yield* seedAction("Compute", { source }, { value: "v1" });
      yield* seedHost("v1");
      const Compute = Action("Compute", (input: { source: { string?: string } }) =>
        Effect.succeed({ value: input.source.string ?? "v1" }),
      );
      const plan = yield* Effect.gen(function* () {
        const source = yield* TestResource("Source", { string: "v2" });
        const result = yield* Compute({ source: Output.of(source) });
        return yield* Function("Host", { name: "host", env: { RESULT: result.value } });
      }).pipe(makePlan);
      expect(plan.resources.Source.action).toBe("update");
      expect(plan.actions.Compute.action).toBe("run");
      expect(plan.resources.Host.action).toBe("update");
    }),
  );

  test(
    "cyclic Action inputs remain unresolved instead of waiting on their own cached plans",
    Effect.gen(function* () {
      const Compute = Action("Compute", (input: { value: string }) => Effect.succeed(input));
      yield* seedAction("First", { value: "v1" }, { value: "v1" });
      yield* seedAction("Second", { value: "v1" }, { value: "v1" });
      const plan = yield* Effect.gen(function* () {
        const input: { value: Input<string> } = { value: "v1" };
        const first = yield* Compute("First", input);
        const second = yield* Compute("Second", { value: first.value });
        input.value = second.value;
        return second;
      }).pipe(makePlan);
      expect(plan.actions.First.action).toBe("run");
      expect(plan.actions.Second.action).toBe("run");
    }),
    { timeout: 1000 },
  );

  test(
    "a resource prop and Action input cycle does not deadlock output resolution",
    Effect.gen(function* () {
      const Compute = Action("Compute", (input: { value: string }) => Effect.succeed(input));
      yield* seedAction("Compute", { value: "v1" }, { value: "v1" });
      yield* seedHost("v1");
      const plan = yield* Effect.gen(function* () {
        const input: { value: Input<string> } = { value: "v1" };
        const result = yield* Compute(input);
        const host = yield* Function("Host", { name: "host", env: { RESULT: result.value } });
        input.value = host.env.RESULT;
        return host;
      }).pipe(makePlan);
      expect(plan.actions.Compute.action).toBe("run");
      expect(plan.resources.Host.action).toBe("update");
    }),
    { timeout: 1000 },
  );

  test(
    "a new Action retains its binding dependency without changing host props",
    Effect.gen(function* () {
      const Compute = Action("Compute", (_: {}) => Effect.succeed({ value: "v1" }));
      const plan = yield* Effect.gen(function* () {
        const result = yield* Compute({});
        const host = yield* BindingTarget("Host", { name: "host" });
        yield* host.bind("Result", { env: { RESULT: result.value } });
        return host;
      }).pipe(makePlan);
      expect(plan.actions.Compute.downstream).toContain("Host");
      expect(plan.resources.Host).toMatchObject({ action: "create", props: { name: "host" } });
    }),
  );
});

test(
  "artifacts are isolated by FQN during plan diff for namespaced resources",
  Effect.gen(function* () {
    yield* seed({
      "Left/Shared": {
        instanceId: "left-instance",
        providerVersion: 0,
        logicalId: "Shared",
        fqn: "Left/Shared",
        namespace: { Id: "Left" },
        resourceType: "Test.ArtifactProbe",
        status: "created",
        props: { value: "left-v1" },
        attr: { value: "left-v1", artifactValue: undefined },
        bindings: [],
        downstream: [],
      },
      "Right/Shared": {
        instanceId: "right-instance",
        providerVersion: 0,
        logicalId: "Shared",
        fqn: "Right/Shared",
        namespace: { Id: "Right" },
        resourceType: "Test.ArtifactProbe",
        status: "created",
        props: { value: "right-v1" },
        attr: { value: "right-v1", artifactValue: undefined },
        bindings: [],
        downstream: [],
      },
    });
    const Site = (id: string, props: { value: string }) =>
      Effect.gen(function* () {
        return yield* ArtifactProbe("Shared", { value: props.value });
      }).pipe(Namespace.push(id));

    const plan = yield* Effect.gen(function* () {
      const left = yield* Site("Left", { value: "left-v2" });
      const right = yield* Site("Right", { value: "right-v2" });
      return { left, right };
    }).pipe(makePlan);

    expect(plan.resources["Left/Shared"]?.action).toEqual("update");
    expect(plan.resources["Right/Shared"]?.action).toEqual("update");
  }),
  { tags: ["unit", "local"] },
);

test(
  "create all resources when plan is empty",
  Effect.gen(function* () {
    expect(
      yield* Effect.gen(function* () {
        const bucket = yield* Bucket("MyBucket", { name: "test-bucket" });
        const queue = yield* Queue("MyQueue", { name: "test-queue" });

        return { queueUrl: queue.queueUrl, bucketArn: bucket.bucketArn };
      }).pipe(makePlan),
    ).toMatchObject({
      resources: {
        MyBucket: {
          action: "create",
          bindings: [],
          props: { name: "test-bucket" },
          state: undefined,
        },
        MyQueue: {
          action: "create",
          bindings: [],
          props: { name: "test-queue" },
          state: undefined,
        },
      },
      deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
    });
  }),
  { tags: ["unit", "local"] },
);

test(
  "reports each diffed resource and action as events",
  Effect.gen(function* () {
    yield* seed({
      A: {
        instanceId,
        providerVersion: 0,
        logicalId: "A",
        fqn: "A",
        namespace: undefined,
        resourceType: "Test.BindingTarget",
        status: "created",
        props: { name: "target" },
        attr: { name: "target", env: {} },
        bindings: [],
        downstream: [],
      },
    });
    const Announce = Action("Announce", (_: { table: string }) => Effect.succeed(1));
    const events: Array<Event> = [];
    yield* Effect.gen(function* () {
      const target = yield* BindingTarget("A", { name: "target" });
      yield* target.bind("TestBinding", { env: { FEATURE_FLAG: "on" } });
      yield* Queue("MyQueue", { name: "test-queue" });
      yield* Announce({ table: "users" });
    }).pipe(
      makePlan,
      onEvent((event) =>
        Effect.sync(() => {
          events.push(event);
        }),
      ),
    );

    // Phase markers land before any node event: state loads, then diffing.
    expect(events.filter((event) => event.type === "plan.phase").map(({ phase }) => phase)).toEqual(
      ["loading-state", "computing-plan"],
    );
    expect(events[0]).toMatchObject({ type: "plan.phase", phase: "loading-state" });
    expect(events[1]).toMatchObject({ type: "plan.phase", phase: "computing-plan" });

    // Each resource diff announces its start before the planned completion.
    expect(
      events
        .filter((event) => event.type === "plan.resource.started")
        .map(({ logicalId }) => logicalId)
        .sort(),
    ).toEqual(["A", "MyQueue"]);

    const nodes = events.filter(
      (event) => event.type === "plan.resource.completed" || event.type === "plan.action.completed",
    );
    const byId = Object.fromEntries(nodes.map((event) => [event.logicalId, event]));
    // resource rows carry their binding rows across the wire
    expect(byId.A).toMatchObject({
      type: "plan.resource.completed",
      action: "update",
      bindings: [{ sid: "TestBinding", action: "create" }],
      total: 2,
    });
    expect(byId.MyQueue).toMatchObject({
      type: "plan.resource.completed",
      action: "create",
      bindings: [],
      total: 2,
    });
    // stack actions get their own events
    expect(byId.Announce).toMatchObject({
      type: "plan.action.completed",
      actionType: "Announce",
      action: "run",
      completed: 1,
      total: 1,
    });
    expect(
      events
        .filter((event) => event.type === "plan.resource.completed")
        .map(({ completed }) => completed)
        .sort(),
    ).toEqual([1, 2]);
  }),
  { tags: ["unit", "local"] },
);

test(
  "destroy plans report deletions as events",
  Effect.gen(function* () {
    yield* seed({
      MyBucket: {
        instanceId,
        providerVersion: 0,
        logicalId: "MyBucket",
        fqn: "MyBucket",
        namespace: undefined,
        resourceType: "Test.Bucket",
        status: "created",
        props: { name: "test-bucket" },
        attr: { name: "test-bucket" },
        bindings: [],
        downstream: [],
      },
    });
    const events: Array<Event> = [];
    const { name, stage } = yield* resolveStackId;
    const plan = yield* Plan.destroy({ name, stage }).pipe(
      onEvent((event) =>
        Effect.sync(() => {
          events.push(event);
        }),
      ),
      Effect.provide(TestLayers()),
    );

    expect(plan.deletions.MyBucket).toMatchObject({ action: "delete" });
    expect(events.filter((event) => event.type === "plan.phase").map(({ phase }) => phase)).toEqual(
      ["loading-state", "computing-plan"],
    );
    const nodes = events.filter((event) => event.type === "plan.resource.completed");
    expect(nodes).toHaveLength(1);
    expect(nodes[0]).toMatchObject({
      type: "plan.resource.completed",
      fqn: "MyBucket",
      logicalId: "MyBucket",
      resourceType: "Test.Bucket",
      action: "delete",
      bindings: [],
      completed: 1,
      total: 1,
    });
  }),
  { tags: ["unit", "local"] },
);

test(
  "update the changed resources and no-op un-changed resources",
  Effect.gen(function* () {
    yield* seed({
      MyBucket: {
        instanceId,
        providerVersion: 0,
        logicalId: "MyBucket",
        fqn: "MyBucket",
        namespace: undefined,
        resourceType: "Test.Bucket",
        status: "created",
        props: { name: "test-bucket" },
        attr: { name: "test-bucket" },
        bindings: [],
        downstream: [],
      },
    });
    expect(
      yield* makePlan(
        Effect.gen(function* () {
          yield* Bucket("MyBucket", { name: "test-bucket" });
          yield* Queue("MyQueue", { name: "test-queue" });
        }),
      ),
    ).toMatchObject({
      resources: {
        MyBucket: { action: "noop", bindings: [], state: { status: "created" } },
        MyQueue: {
          action: "create",
          bindings: [],
          props: { name: "test-queue" },
          state: undefined,
        },
      },
      deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
    });
  }),
  { tags: ["unit", "local"] },
);

test(
  "plan downstream resources when a stable kind shadows an output discriminator",
  Effect.gen(function* () {
    yield* seed({
      Database: {
        instanceId,
        providerVersion: 0,
        logicalId: "Database",
        fqn: "Database",
        namespace: undefined,
        resourceType: "Test.KindStablesResource",
        status: "created",
        props: { value: "v1" },
        attr: { kind: "postgresql", value: "v1", upstreamKind: undefined },
        bindings: [],
        downstream: [],
      },
    });

    const plan = yield* Effect.gen(function* () {
      const database = yield* KindStablesResource("Database", { value: "v2" });
      yield* KindStablesResource("Role", { value: "role", upstream: database });
    }).pipe(makePlan);

    expect(plan.resources.Database!.action).toBe("update");
    expect(plan.resources.Role!.action).toBe("create");
  }),
  { tags: ["unit", "local"] },
);

test(
  "force changes noop resources into updates",
  Effect.gen(function* () {
    yield* seed({
      MyBucket: {
        instanceId,
        providerVersion: 0,
        logicalId: "MyBucket",
        fqn: "MyBucket",
        namespace: undefined,
        resourceType: "Test.Bucket",
        status: "created",
        props: { name: "test-bucket" },
        attr: { name: "test-bucket" },
        bindings: [],
        downstream: [],
      },
    });
    expect(
      yield* makePlan(
        Effect.gen(function* () {
          yield* Bucket("MyBucket", { name: "test-bucket" });
        }),
        { force: true },
      ),
    ).toMatchObject({
      resources: {
        MyBucket: {
          action: "update",
          bindings: [],
          props: { name: "test-bucket" },
          state: { status: "created" },
        },
      },
      deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
    });
  }),
  { tags: ["unit", "local"] },
);

test(
  "no-op resources with undefined props",
  Effect.gen(function* () {
    yield* seed({
      MyQueue: {
        instanceId,
        providerVersion: 0,
        logicalId: "MyQueue",
        fqn: "MyQueue",
        namespace: undefined,
        resourceType: "Test.Queue",
        status: "created",
        props: undefined as any,
        attr: { name: "MyQueue", queueUrl: "https://test.queue.com/MyQueue" },
        bindings: [],
        downstream: [],
      },
    });
    expect(
      yield* makePlan(
        Effect.gen(function* () {
          yield* Queue("MyQueue");
        }),
      ),
    ).toMatchObject({
      resources: { MyQueue: { action: "noop", bindings: [], state: { status: "created" } } },
      deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
    });
  }),
  { tags: ["unit", "local"] },
);

test(
  "no-op resources when object prop key order changes",
  Effect.gen(function* () {
    yield* seed({
      MyFunction: {
        instanceId,
        providerVersion: 0,
        logicalId: "MyFunction",
        fqn: "MyFunction",
        namespace: undefined,
        resourceType: "Test.Function",
        status: "created",
        props: { name: "test-function", env: { A: "1", B: "2" } },
        attr: {
          name: "test-function",
          env: { A: "1", B: "2" },
          functionArn: "arn:test:function:MyFunction",
        },
        bindings: [],
        downstream: [],
      },
    });
    expect(
      yield* makePlan(
        Effect.gen(function* () {
          yield* Function("MyFunction", { name: "test-function", env: { B: "2", A: "1" } });
        }),
      ),
    ).toMatchObject({
      resources: { MyFunction: { action: "noop", bindings: [], state: { status: "created" } } },
      deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
    });
  }),
  { tags: ["unit", "local"] },
);

test(
  "plan retained resources as orphaned",
  Effect.gen(function* () {
    yield* seed({
      MyBucket: {
        instanceId,
        providerVersion: 0,
        logicalId: "MyBucket",
        fqn: "MyBucket",
        namespace: undefined,
        resourceType: "Test.Bucket",
        status: "created",
        props: { name: "test-bucket" },
        attr: { name: "test-bucket" },
        bindings: [],
        downstream: [],
        removalPolicy: "retain",
      },
      MyQueue: {
        instanceId,
        providerVersion: 0,
        logicalId: "MyQueue",
        fqn: "MyQueue",
        namespace: undefined,
        resourceType: "Test.Queue",
        status: "created",
        props: { name: "test-queue" },
        attr: { name: "test-queue" },
        bindings: [],
        downstream: [],
      },
    });
    expect(
      yield* makePlan(
        Effect.gen(function* () {
          yield* Queue("MyQueue", { name: "test-queue" });
        }),
      ),
    ).toMatchObject({
      resources: { MyQueue: { action: "noop", bindings: [], state: { status: "created" } } },
      deletions: {
        MyBucket: {
          action: "orphaned",
          bindings: [],
          state: { status: "created", attr: { name: "test-bucket" } },
          resource: { LogicalId: "MyBucket", Type: "Test.Bucket", Props: { name: "test-bucket" } },
        },
      },
    });
  }),
  { tags: ["unit", "local"] },
);

test(
  "allow deleting a resource after a surviving consumer removes the dependency",
  Effect.gen(function* () {
    yield* seed({
      Secret: {
        instanceId,
        providerVersion: 0,
        logicalId: "Secret",
        fqn: "Secret",
        namespace: undefined,
        resourceType: "Test.TestResource",
        status: "created",
        props: { string: "secret-value" },
        attr: {
          string: "secret-value",
          stringArray: [],
          stableString: "Secret",
          stableArray: ["Secret"],
          replaceString: undefined,
        },
        bindings: [],
        downstream: ["Worker"],
      },
      Worker: {
        instanceId,
        providerVersion: 0,
        logicalId: "Worker",
        fqn: "Worker",
        namespace: undefined,
        resourceType: "Test.Function",
        status: "created",
        props: { name: "worker", env: { SECRET: "secret-value" } },
        attr: {
          name: "worker",
          env: { SECRET: "secret-value" },
          functionArn: "arn:aws:lambda:us-west-2:084828582823:function:Worker",
        },
        bindings: [],
        downstream: [],
      },
    });
    expect(
      yield* makePlan(
        Effect.gen(function* () {
          yield* Function("Worker", { name: "worker" });
        }),
      ),
    ).toMatchObject({
      resources: { Worker: { action: "update", props: { name: "worker" }, bindings: [] } },
      deletions: {
        Secret: { action: "delete", state: { status: "created", downstream: ["Worker"] } },
      },
    });
  }),
  { tags: ["unit", "local"] },
);

test(
  "reject deleting a resource when a surviving consumer still references it",
  Effect.gen(function* () {
    yield* seed({
      Secret: {
        instanceId,
        providerVersion: 0,
        logicalId: "Secret",
        fqn: "Secret",
        namespace: undefined,
        resourceType: "Test.TestResource",
        status: "created",
        props: { string: "secret-value" },
        attr: {
          string: "secret-value",
          stringArray: [],
          stableString: "Secret",
          stableArray: ["Secret"],
          replaceString: undefined,
        },
        bindings: [],
        downstream: ["Worker"],
      },
      Worker: {
        instanceId,
        providerVersion: 0,
        logicalId: "Worker",
        fqn: "Worker",
        namespace: undefined,
        resourceType: "Test.Function",
        status: "created",
        props: { name: "worker", env: { SECRET: "secret-value" } },
        attr: {
          name: "worker",
          env: { SECRET: "secret-value" },
          functionArn: "arn:aws:lambda:us-west-2:084828582823:function:Worker",
        },
        bindings: [],
        downstream: [],
      },
    });
    const malformedStack = {
      name: TEST_STACK,
      stage: TEST_STAGE,
      resources: {},
      bindings: {},
      output: undefined,
    };

    const exit = yield* Effect.exit(
      Effect.gen(function* () {
        const secret = yield* TestResource("Secret", { string: "secret-value" });
        yield* Function("Worker", { name: "worker", env: { SECRET: secret.string } });
        const stack = yield* Stack.Stack;
        delete stack.resources.Secret;
      }).pipe(makePlanWithCustomStack(malformedStack)),
    );

    expect(Exit.isFailure(exit)).toBe(true);
    if (Exit.isFailure(exit)) {
      const reason = exit.cause.reasons.find(Cause.isFailReason);
      expect(reason).toBeDefined();
      expect(reason!.error).toEqual(
        new Plan.DeleteResourceHasDownstreamDependencies({
          message: "Resource Secret has downstream dependencies",
          resourceId: "Secret",
          dependencies: ["Worker"],
        }),
      );
    }
  }),
  { tags: ["unit", "local"] },
);

// #1831: values a Platform's Init captures reach the provider only through
// `props.env`. `CapturedConfigHost`'s diff always returns `noop`, so these
// actions come from the engine's own comparison of the captured values.
describe("Platform Init-captured config", { tags: ["unit", "local"] }, () => {
  const seedHost = (mode: string) =>
    seed({
      Host: {
        instanceId,
        providerVersion: 0,
        logicalId: "Host",
        fqn: "Host",
        namespace: undefined,
        resourceType: "Test.CapturedConfigHost",
        status: "created",
        props: { main: "index.ts", env: { CAPTURED_MODE: packEnvValue(Redacted.make(mode)) } },
        attr: { mode },
        bindings: [],
        downstream: [],
      },
    });

  test(
    "an unchanged captured value keeps the provider's noop",
    Effect.gen(function* () {
      yield* seedHost("a");
      const plan = yield* capturedConfigHost("a").pipe(makePlan);
      expect(plan.resources.Host.action).toBe("noop");
    }),
  );

  test(
    "a changed captured value plans an update over the provider's noop",
    Effect.gen(function* () {
      yield* seedHost("a");
      const plan = yield* capturedConfigHost("b").pipe(makePlan);
      expect(plan.resources.Host.action).toBe("update");
    }),
  );
});

describe("replace resource when replaceString changes", { tags: ["unit", "local"] }, () => {
  const stateResources: Record<string, ResourceState> = {
    A: {
      instanceId,
      providerVersion: 0,
      logicalId: "A",
      fqn: "A",
      namespace: undefined,
      resourceType: "Test.TestResource",
      status: "created",
      props: { replaceString: "A" },
      attr: {},
      downstream: [],
      bindings: [],
    },
  };

  test(
    "noop and replace when replaceString is fully resolved at plan time",
    Effect.gen(function* () {
      yield* seed(stateResources);
      expect(
        yield* Effect.gen(function* () {
          yield* TestResource("A", { replaceString: "A" });
        }).pipe(makePlan),
      ).toMatchObject({
        resources: { A: { action: "noop" } },
        deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
      });

      expect(
        yield* Effect.gen(function* () {
          yield* TestResource("A", { replaceString: "B" });
        }).pipe(makePlan),
      ).toMatchObject({
        resources: { A: { action: "replace", props: { replaceString: "B" } } },
        deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
      });
    }),
  );

  test(
    "force preserves replaces",
    Effect.gen(function* () {
      yield* seed(stateResources);
      expect(
        yield* Effect.gen(function* () {
          yield* TestResource("A", { replaceString: "B" });
        }).pipe((effect) => makePlan(effect, { force: true })),
      ).toMatchObject({
        resources: { A: { action: "replace", props: { replaceString: "B" } } },
        deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
      });
    }),
  );

  test(
    "update when replaceString depends on unresolved output (diff short-circuits)",
    Effect.gen(function* () {
      yield* seed(stateResources);
      let B: TestResource;
      expect(
        yield* Effect.gen(function* () {
          B = yield* TestResource("B", { string: "A" });
          yield* TestResource("A", { replaceString: B.string });
        }).pipe(makePlan),
      ).toMatchObject({
        resources: {
          A: {
            action: "update",
            props: {
              replaceString: expect.objectContaining({
                kind: "PropExpr",
                identifier: "string",
                expr: expect.objectContaining({ kind: "ResourceExpr", src: B! }),
              }),
            },
          },
        },
        deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
      });
    }),
  );
});

test(
  "update resource when a binding is added without prop changes",
  Effect.gen(function* () {
    yield* seed({
      A: {
        instanceId,
        providerVersion: 0,
        logicalId: "A",
        fqn: "A",
        namespace: undefined,
        resourceType: "Test.BindingTarget",
        status: "created",
        props: { name: "target" },
        attr: { name: "target", env: {} },
        bindings: [],
        downstream: [],
      },
    });
    expect(
      yield* Effect.gen(function* () {
        const target = yield* BindingTarget("A", { name: "target" });
        yield* target.bind("TestBinding", { env: { FEATURE_FLAG: "on" } });
      }).pipe(makePlan),
    ).toMatchObject({
      resources: {
        A: {
          action: "update",
          bindings: [
            { action: "create", sid: "TestBinding", data: { env: { FEATURE_FLAG: "on" } } },
          ],
          state: { status: "created" },
        },
      },
      deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
    });
  }),
  { tags: ["unit", "local"] },
);

test(
  "update resource when a binding is removed without prop changes",
  Effect.gen(function* () {
    yield* seed({
      A: {
        instanceId,
        providerVersion: 0,
        logicalId: "A",
        fqn: "A",
        namespace: undefined,
        resourceType: "Test.BindingTarget",
        status: "created",
        props: { name: "target" },
        attr: { name: "target", env: { FEATURE_FLAG: "on" } },
        bindings: [{ sid: "TestBinding", data: { env: { FEATURE_FLAG: "on" } } }],
        downstream: [],
      },
    });
    expect(
      yield* Effect.gen(function* () {
        yield* BindingTarget("A", { name: "target" });
      }).pipe(makePlan),
    ).toMatchObject({
      resources: {
        A: {
          action: "update",
          bindings: [
            { action: "delete", sid: "TestBinding", data: { env: { FEATURE_FLAG: "on" } } },
          ],
          state: { status: "created" },
        },
      },
      deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
    });
  }),
  { tags: ["unit", "local"] },
);

test.provider(
  "binding removals do not keep reappearing after apply",
  (scratch) =>
    Effect.gen(function* () {
      const state = yield* yield* State;
      yield* state.set({
        stack: scratch.name,
        stage: scratch.stage,
        fqn: "A",
        value: {
          instanceId,
          providerVersion: 0,
          logicalId: "A",
          fqn: "A",
          namespace: undefined,
          resourceType: "Test.BindingTarget",
          status: "created",
          props: { name: "target" },
          attr: { name: "target", env: { FEATURE_FLAG: "on" } },
          bindings: [{ sid: "TestBinding", data: { env: { FEATURE_FLAG: "on" } } }],
          downstream: [],
        },
      });

      yield* scratch.deploy(
        Effect.gen(function* () {
          yield* BindingTarget("A", { name: "target" });
        }),
      );

      expect(
        yield* state.get({ stack: scratch.name, stage: scratch.stage, fqn: "A" }),
      ).toMatchObject({ bindings: [] });

      expect(
        yield* Effect.gen(function* () {
          yield* BindingTarget("A", { name: "target" });
        }).pipe(makePlan),
      ).toMatchObject({
        resources: { A: { action: "noop", bindings: [] } },
        deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
      });
    }),
  { tags: ["unit", "local"] },
);

describe("duplicate bindings are collapsed by sid before diff", { tags: ["unit", "local"] }, () => {
  test(
    "dedupeBindings keeps the last occurrence of each sid",
    Effect.sync(() => {
      const deduped = dedupeBindings([
        { sid: "Shared", data: { env: { K: "first" } } },
        { sid: "Other", data: { env: { K: "x" } } },
        { sid: "Shared", data: { env: { K: "last" } } },
      ]);

      // The duplicated sid takes the last value (matching `diffBindings`'
      // `Map`-based collapse) and the result is sid-sorted so binding rows
      // are deterministic regardless of registration order.
      expect(deduped).toEqual([
        { sid: "Other", data: { env: { K: "x" } } },
        { sid: "Shared", data: { env: { K: "last" } } },
      ]);
    }),
  );

  test(
    "diff observes a single binding when the same sid is bound twice",
    Effect.gen(function* () {
      yield* seed({
        A: {
          instanceId,
          providerVersion: 0,
          logicalId: "A",
          fqn: "A",
          namespace: undefined,
          resourceType: "Test.BindingTarget",
          status: "created",
          props: { name: "target" },
          attr: { name: "target", env: {} },
          bindings: [],
          downstream: [],
        },
      });

      // Capture the exact binding list the provider's `diff` receives.
      const observed: ResourceBinding[][] = [];

      const plan = yield* Effect.gen(function* () {
        const target = yield* BindingTarget("A", { name: "target" });
        // The same sid is recorded twice — mirrors a single KV namespace
        // bound to two consumers that both attach it to the same target,
        // which pushes a duplicate into `stack.bindings[fqn]`.
        yield* target.bind("Shared", { env: { FEATURE_FLAG: "on" } });
        yield* target.bind("Shared", { env: { FEATURE_FLAG: "on" } });
      }).pipe(
        makePlan,
        Effect.provideService(TestResourceHooks, {
          diff: (_id, newBindings) =>
            Effect.sync(() => {
              observed.push(newBindings);
            }),
        }),
      );

      // Before the fix, `diff` saw the raw duplicate pair (length 2) while
      // `reconcile` saw a deduped list — an inconsistency that made hashing
      // unstable. Every diff invocation must now see the collapsed list.
      expect(observed.length).toBeGreaterThan(0);
      for (const seen of observed) {
        expect(seen).toHaveLength(1);
        expect(seen[0]).toMatchObject({ sid: "Shared", data: { env: { FEATURE_FLAG: "on" } } });
      }

      // The plan node likewise collapses to a single create binding.
      expect(plan.resources.A).toMatchObject({
        action: "update",
        bindings: [{ action: "create", sid: "Shared", data: { env: { FEATURE_FLAG: "on" } } }],
      });
    }),
  );
});

describe("construct namespaces", { tags: ["unit", "local"] }, () => {
  test(
    "namespaced construct bindings resolve into the plan graph",
    Effect.gen(function* () {
      const Site = (id: string, _props: {}) =>
        Effect.gen(function* () {
          const bucket = yield* BindingTarget("Bucket", { name: "bucket" });
          const distribution = yield* BindingTarget("Distribution", { name: "distribution" });
          yield* bucket.bind("Policy", {
            env: { BUCKET: bucket.string, DISTRIBUTION: distribution.string },
          });
          return { bucket, distribution };
        }).pipe(Namespace.push(id));

      const plan = yield* Effect.gen(function* () {
        yield* Site("MarketingSite", {});
      }).pipe(makePlan);

      expect(plan).toMatchObject({
        resources: {
          "MarketingSite/Bucket": {
            action: "create",
            bindings: [
              {
                action: "create",
                sid: "Policy",
                data: {
                  env: {
                    BUCKET: expect.objectContaining({
                      kind: "PropExpr",
                      identifier: "string",
                      expr: expect.objectContaining({
                        kind: "ResourceExpr",
                        src: plan.resources["MarketingSite/Bucket"]!.resource,
                      }),
                    }),
                    DISTRIBUTION: expect.objectContaining({
                      kind: "PropExpr",
                      identifier: "string",
                      expr: expect.objectContaining({
                        kind: "ResourceExpr",
                        src: plan.resources["MarketingSite/Distribution"]!.resource,
                      }),
                    }),
                  },
                },
              },
            ],
          },
          "MarketingSite/Distribution": { action: "create", bindings: [] },
        },
        deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
      });
    }),
  );

  test(
    "same child logical ids in different constructs do not collide",
    Effect.gen(function* () {
      const Site = (id: string, props: { name: string }) =>
        Effect.gen(function* () {
          return yield* Bucket("Bucket", { name: props.name });
        }).pipe(Namespace.push(id));

      const plan = yield* Effect.gen(function* () {
        yield* Site("MarketingSite", { name: "marketing-bucket" });
        yield* Site("DocsSite", { name: "docs-bucket" });
      }).pipe(makePlan);

      expect(plan).toMatchObject({
        resources: {
          "MarketingSite/Bucket": { action: "create", props: { name: "marketing-bucket" } },
          "DocsSite/Bucket": { action: "create", props: { name: "docs-bucket" } },
        },
        deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
      });
    }),
  );

  test(
    "binding-only cycles inside a construct do not become downstream edges",
    Effect.gen(function* () {
      const Site = (id: string, _props: {}) =>
        Effect.gen(function* () {
          const A = yield* BindingTarget("A", { string: "a-value" });
          const B = yield* BindingTarget("B", { string: "b-value" });

          yield* A.bind("FromB", { env: { PEER: B.string } });
          yield* B.bind("FromA", { env: { PEER: A.string } });

          return { A, B };
        }).pipe(Namespace.push(id));

      const plan = yield* Effect.gen(function* () {
        yield* Site("MarketingSite", {});
      }).pipe(makePlan);

      expect(plan.resources["MarketingSite/A"]?.downstream).toEqual([]);
      expect(plan.resources["MarketingSite/B"]?.downstream).toEqual([]);
      expect(plan.deletions).toEqual({});
    }),
  );
});

const createTestResourceState = (options: {
  logicalId: string;
  status: ResourceStatus;
  props: TestResourceProps;
  attr?: {};
}) =>
  ({
    instanceId,
    providerVersion: 0,
    ...options,
    resourceType: "Test.TestResource",
    attr: options.attr ?? {},
    downstream: [],
    bindings: [],
    fqn: options.logicalId,
    namespace: undefined,
  }) as ResourceState;

const createReplacingState = (options: {
  logicalId: string;
  props: TestResourceProps;
  old: ResourceState;
  attr?: {};
}) =>
  ({
    ...createTestResourceState({
      logicalId: options.logicalId,
      status: "replacing",
      props: options.props,
      attr: options.attr,
    }),
    old: options.old,
    deleteFirst: false,
  }) as Extract<ResourceState, { status: "replacing" }>;

const createReplacedState = (options: {
  logicalId: string;
  props: TestResourceProps;
  old: ResourceState;
  attr?: {};
}) =>
  ({
    ...createTestResourceState({
      logicalId: options.logicalId,
      status: "replaced",
      props: options.props,
      attr: options.attr,
    }),
    old: options.old,
    deleteFirst: false,
  }) as Extract<ResourceState, { status: "replaced" }>;

const testSimple = (
  title: string,
  testCase: {
    state: {
      status: ResourceStatus;
      props: TestResourceProps;
      attr?: {};
      old?: Partial<ResourceState>;
    };
    props: TestResourceProps;
    plan?: any;
    fail?: string;
  },
) =>
  test(
    title,
    Effect.gen(function* () {
      yield* seed({ A: createTestResourceState({ ...testCase.state, logicalId: "A" }) });
      {
        const plan = Effect.gen(function* () {
          yield* TestResource("A", testCase.props);
        }).pipe(makePlan);

        if (testCase.fail) {
          const result = plan.pipe(
            Effect.map(() => false),
            // @ts-expect-error
            Effect.catchTag(testCase.fail, () => Effect.succeed(true)),
            Effect.catch(() => Effect.succeed(false)),
          ) as Effect.Effect<boolean>;
          if (!result) {
            expect.fail(`Expected error '${testCase.fail}`);
          }
        } else {
          expect(yield* plan).toMatchObject({
            resources: { A: testCase.plan },
            deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
          });
        }
      }
    }),
    { tags: ["unit", "local"] },
  );

describe("prior crash in 'creating' state", () => {
  testSimple("create if props unchanged", {
    state: { status: "creating", props: { string: "A" } },
    props: { string: "A" },
    plan: { action: "create", props: { string: "A" } },
  });

  testSimple("create if changed props can be updated", {
    state: { status: "creating", props: { string: "A" } },
    props: { string: "B" },
    plan: { action: "create", props: { string: "B" } },
  });

  testSimple("replace if changed props cannot be updated", {
    state: { status: "creating", props: { replaceString: "A" } },
    props: { replaceString: "B" },
    plan: {
      action: "replace",
      props: { replaceString: "B" },
      state: { status: "creating", props: { replaceString: "A" } },
    },
  });
});

describe("prior crash in 'updating' state", () => {
  testSimple("update if props unchanged", {
    state: { status: "updating", props: { string: "A" } },
    props: { string: "A" },
    plan: {
      action: "update",
      props: { string: "A" },
      state: { status: "updating", props: { string: "A" } },
    },
  });

  testSimple("update if changed props can be updated", {
    state: { status: "updating", props: { string: "A" } },
    props: { string: "B" },
    plan: {
      action: "update",
      props: { string: "B" },
      state: { status: "updating", props: { string: "A" } },
    },
  });

  testSimple("replace if changed props can not be updated", {
    state: { status: "updating", props: { replaceString: "A" } },
    props: { replaceString: "B" },
    plan: {
      action: "replace",
      props: { replaceString: "B" },
      state: { status: "updating", props: { replaceString: "A" } },
    },
  });
});

describe("pending replacement deletion plans", { tags: ["unit", "local"] }, () => {
  for (const status of ["replacing", "replaced"] as const) {
    test(
      `preserves the complete ${status} chain and all generation dependencies`,
      Effect.gen(function* () {
        const oldest: ResourceState = {
          status: "created",
          fqn: "R",
          logicalId: "R",
          namespace: undefined,
          instanceId: "oldest",
          resourceType: "Test.ModalResource",
          providerVersion: 0,
          props: { value: "one" },
          attr: { value: "one", runtime: "live" },
          providerMode: "live",
          downstream: ["OldDependent"],
          bindings: [],
        };
        const middle: ResourceState = {
          ...oldest,
          status: "replacing",
          instanceId: "middle",
          props: { value: "two" },
          attr: undefined,
          providerMode: "local",
          downstream: ["MiddleDependent"],
          deleteFirst: false,
          old: oldest,
        };
        const pending: ResourceState = {
          ...oldest,
          status,
          instanceId: "newest",
          props: { value: "three" },
          attr: { value: "three", runtime: "live" },
          downstream: ["NewDependent"],
          deleteFirst: false,
          old: middle,
        };
        yield* seed({ R: pending });
        const plan = yield* makePlan(Effect.void);
        expect(plan.deletions.R?.action).toBe("delete");
        expect(plan.deletions.R?.mode).toBe("live");
        expect(plan.deletions.R?.state).toEqual(pending);
        expect(plan.deletions.R?.downstream).toEqual([
          "NewDependent",
          "MiddleDependent",
          "OldDependent",
        ]);
        const state = yield* yield* State;
        expect(yield* state.get({ stack: TEST_STACK, stage: TEST_STAGE, fqn: "R" })).toEqual(
          pending,
        );
      }),
    );
  }
});

describe("prior crash in 'replacing' state", () => {
  const priorStates = ["created", "creating", "updated", "updating"] as const;

  const testUnchanged = ({ old }: { old: { status: ResourceStatus } }) =>
    testSimple(
      `"continue 'replace' if props are unchanged and previous state is '${old.status}'"`,
      {
        state: { status: "replacing", props: { string: "A" }, old },
        props: { string: "A" },
        plan: {
          action: "replace",
          props: { string: "A" },
          state: { status: "replacing", props: { string: "A" }, old },
        },
      },
    );

  priorStates.forEach((status) => testUnchanged({ old: { status } }));

  const testMinorChange = ({ old }: { old: { status: ResourceStatus } }) =>
    testSimple(
      `"continue 'replace' if props can be updated and previous state is '${old.status}'"`,
      {
        state: { status: "replacing", props: { string: "A" }, old },
        props: { string: "B" },
        plan: {
          action: "replace",
          props: { string: "B" },
          state: { status: "replacing", props: { string: "A" }, old },
        },
      },
    );

  priorStates.forEach((status) => testMinorChange({ old: { status } }));

  const testReplacement = (title: string, { old, plan }: { old: ResourceState; plan: any }) =>
    testSimple(title, {
      state: { status: "replacing", props: { replaceString: "A" }, old },
      props: { replaceString: "B" },
      plan,
    });

  (["replaced", "replacing"] as const).forEach((status) =>
    testReplacement(
      `continue 'replace' if trying to replace a partially replaced resource in state '${status}'`,
      {
        old:
          status === "replaced"
            ? createReplacedState({
                logicalId: "A_old1",
                props: { replaceString: "A1" },
                old: createTestResourceState({
                  logicalId: "A_old0",
                  status: "created",
                  props: { replaceString: "A0" },
                }),
              })
            : createReplacingState({
                logicalId: "A_old1",
                props: { replaceString: "A1" },
                old: createTestResourceState({
                  logicalId: "A_old0",
                  status: "created",
                  props: { replaceString: "A0" },
                }),
              }),
        plan: {
          action: "replace",
          props: { replaceString: "B" },
          state: {
            status: "replacing",
            props: { replaceString: "A" },
            old: expect.objectContaining({
              status,
              props: { replaceString: "A1" },
              old: expect.objectContaining({ status: "created", props: { replaceString: "A0" } }),
            }),
          },
        },
      },
    ),
  );
});

describe("prior crash in 'replaced' state", () => {
  (["replaced", "replacing"] as const).forEach((status) =>
    testSimple(
      `continue 'replace' if a replaced resource must be replaced again and previous state is '${status}'`,
      {
        state: {
          status: "replaced",
          props: { replaceString: "A1" },
          old:
            status === "replaced"
              ? createReplacedState({
                  logicalId: "A_old0",
                  props: { replaceString: "A0" },
                  old: createTestResourceState({
                    logicalId: "A_old-1",
                    status: "created",
                    props: { replaceString: "A-1" },
                  }),
                })
              : createReplacingState({
                  logicalId: "A_old0",
                  props: { replaceString: "A0" },
                  old: createTestResourceState({
                    logicalId: "A_old-1",
                    status: "created",
                    props: { replaceString: "A-1" },
                  }),
                }),
        },
        props: { replaceString: "B" },
        plan: {
          action: "replace",
          props: { replaceString: "B" },
          state: {
            status: "replaced",
            props: { replaceString: "A1" },
            old: expect.objectContaining({
              status,
              props: { replaceString: "A0" },
              old: expect.objectContaining({ status: "created", props: { replaceString: "A-1" } }),
            }),
          },
        },
      },
    ),
  );
});

describe("prior crash in 'deleting' state", () => {
  testSimple("create the resource if props are unchanged and the previous state is 'deleting'", {
    state: { status: "deleting", props: { string: "A" } },
    props: { string: "A" },
    plan: { action: "create", props: { string: "A" } },
  });
});

test(
  "lazy Output queue.queueUrl to Function.env",
  Effect.gen(function* () {
    let MyQueue: Queue;
    let MyFunction: Function;
    const plan = yield* Effect.gen(function* () {
      MyQueue = yield* Queue("MyQueue");
      MyFunction = yield* Function("MyFunction", {
        name: "test-function",
        env: { QUEUE_URL: MyQueue.queueUrl },
      });
    }).pipe(makePlan);
    expect(plan).toMatchObject({
      resources: {
        MyFunction: {
          action: "create",
          bindings: [],
          resource: MyFunction!,
          props: {
            name: "test-function",
            env: {
              QUEUE_URL: expect.objectContaining({
                kind: "PropExpr",
                identifier: "queueUrl",
                expr: expect.objectContaining({ kind: "ResourceExpr", src: MyQueue! }),
              }),
            },
          },
          state: undefined,
        },
      },
      deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
    });
  }),
  { tags: ["unit", "local"] },
);

test(
  "detect that queueUrl will change and pass through the PropExpr instead of old output",
  Effect.gen(function* () {
    yield* seed({
      MyQueue: {
        instanceId,
        providerVersion: 0,
        logicalId: "MyQueue",
        fqn: "MyQueue",
        namespace: undefined,
        resourceType: "Test.Queue",
        status: "created",
        props: { name: "test-queue-old" },
        attr: { queueUrl: "https://test.queue.com/test-queue-old" },
        downstream: [],
        bindings: [],
      },
    });
    let MyQueue: Queue;
    let MyFunction: Function;
    const plan = yield* Effect.gen(function* () {
      MyQueue = yield* Queue("MyQueue");
      MyFunction = yield* Function("MyFunction", {
        name: "test-function",
        env: { QUEUE_URL: MyQueue.queueUrl },
      });
    }).pipe(makePlan);
    expect(plan).toMatchObject({
      resources: {
        MyFunction: {
          action: "create",
          bindings: [],
          resource: MyFunction!,
          props: {
            name: "test-function",
            env: {
              QUEUE_URL: expect.objectContaining({
                kind: "PropExpr",
                identifier: "queueUrl",
                expr: expect.objectContaining({ kind: "ResourceExpr", src: MyQueue! }),
              }),
            },
          },
          state: undefined,
        },
      },
      deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
    });
  }),
  { tags: ["unit", "local"] },
);

describe("Outputs should resolve to old values", { tags: ["unit", "local"] }, () => {
  const stateResources: Record<string, ResourceState> = {
    A: {
      instanceId,
      providerVersion: 0,
      logicalId: "A",
      fqn: "A",
      namespace: undefined,
      resourceType: "Test.TestResource",
      status: "created",
      props: { string: "test-string", stringArray: ["test-string"] },
      attr: { string: "test-string", stringArray: ["test-string"] },
      downstream: [],
      bindings: [],
    },
  };

  const expected = (props: Input.Resolve<InputProps<TestResourceProps>>) => ({
    resources: {
      A: { action: "noop", bindings: [] },
      B: { action: "create", bindings: [], props: props },
    },
    deletions: expect.toSatisfy((d: any) => Object.keys(d).length === 0, "empty object"),
  });

  const subtest = <const I extends InputProps<TestResourceProps>>(
    description: string,
    input: (resource: TestResource) => I,
    attr: Input.Resolve<I>,
  ) =>
    test(
      description,
      Effect.gen(function* () {
        yield* seed(stateResources);
        expect(
          yield* Effect.gen(function* () {
            const A = yield* TestResource("A", {
              string: "test-string",
              stringArray: ["test-string"],
            });
            yield* TestResource("B", input(A));
          }).pipe(makePlan),
        ).toMatchObject(expected(attr));
      }),
    );

  subtest("string", (A) => ({ string: A.string }), { string: "test-string" });

  subtest(
    "string.apply(string => undefined)",
    (A) => ({ string: A.string.pipe(Output.map(() => undefined)) }),
    { string: undefined },
  );

  subtest(