ab: deleting a document in one collection removes the A/B experiment rows of another collection's document with the same id

Đang mở Phù hợp với người mới
#263 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

Chưa có ai nhận issue này.

Đánh giá

Độ khó
2/5
Thời gian dự kiến
1-3 giờ
Mức phù hợp với người mới
88/100
Loại issue
Lỗi
Độ rõ ràng
Đặc tả rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
postgresql, typescript
Lĩnh vực
backend, database

Hướng nghiên cứu

Bắt đầu trong packages/payload-plugin-ab/src/hooks/buildParentAfterDeleteHook.ts tại lời gọi delete; parentCollectionSlug đã là một đối số. Thay đổi where để kết hợp parentDocId với parentCollection, sau đó thêm tests/hooks/buildParentAfterDeleteHook.test.ts bằng cách dùng mock delete trong bộ nhớ từ issue. Chạy bun run test trong packages/payload-plugin-ab, sau đó build và lint. Xong khi hàng của một collection khác có cùng id vẫn còn, các hàng của collection đã xóa biến mất và các kiểm tra của package đều qua.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

TL;DR

Deleting any non-variant document in an A/B-enabled collection also deletes, without an error or log entry, the ab-experiments rows of an A/B test that runs on a document with the same id in another A/B-enabled collection. With the Postgres adapter's default serial ids every collection counts from 1, so two configured collections are enough. The A/B test drops out of the analytics plugin's A/B overview until the next publish of its document or one of its variants, which creates the row again with a new start date; its variants, traffic split and GA4 data are not touched. The fix is one extra condition in one where clause, plus a unit test. Neither the reproduction nor the proposed test has been run; both were traced through the code.

Implementation details are in the next section.

For the implementing agent

Scope
  • Package: packages/payload-plugin-ab (@focus-reactive/payload-plugin-ab). The same code ships in 2.10.1 and 2.11.0.
  • Source file to change: packages/payload-plugin-ab/src/hooks/buildParentAfterDeleteHook.ts. New test file: packages/payload-plugin-ab/tests/hooks/buildParentAfterDeleteHook.test.ts.
  • Line numbers refer to commit daf914b7. If they have moved, locate the code by the snippet where: { parentDocId: { equals: String(id) } }.
Root cause

packages/payload-plugin-ab/src/hooks/buildParentAfterDeleteHook.ts:68-78:

const experimentsSlug = pluginConfig.experimentsCollectionSlug ?? AB_EXPERIMENTS_SLUG;
await payload
  .delete({
    collection: experimentsSlug as CollectionSlug,
    where: { parentDocId: { equals: String(id) } },
    overrideAccess: true,
    req,
  })
  .catch(() => {
    // non-fatal: nothing to delete if no experiment was ever recorded
  });
  • packages/payload-plugin-ab/src/plugin.ts:57-60 adds this hook to every collection listed in the plugin's collections option, passing collection.slug as the first argument.
  • That argument is parentCollectionSlug (buildParentAfterDeleteHook.ts:9). The hook already uses it for the variant lookup and unlinking (lines 44 and 56), but not for this delete.
  • Every experiment row stores both keys. The only writer is packages/payload-plugin-ab/src/hooks/ensureExperimentRecords.ts:56-67, which sets parentDocId: String(parentId) (line 60) and parentCollection: parentCollectionSlug (line 61).
  • The delete runs for every non-variant document (variants return at lines 19-34), whether or not that document has a test. It removes every row whose parentDocId equals the deleted id, whichever collection the row belongs to.
  • The analytics plugin's A/B overview lists experiments from these rows (packages/payload-plugin-analytics/src/services/queries/getAbOverview.ts:50), so a deleted row removes the A/B test from it.
Change

Replace the where at line 72 and leave the rest of the call, including the .catch, as it is:

// before
where: { parentDocId: { equals: String(id) } },

// after
where: {
  and: [
    { parentDocId: { equals: String(id) } },
    { parentCollection: { equals: parentCollectionSlug } },
  ],
},

Checked at daf914b7:

  • parentCollection is the field name in the experiments collection: name: "parentCollection", type: "text", required: true (packages/payload-plugin-ab/src/collections/buildExperimentsCollection.ts:31-35).
  • The stored value has the same form as the hook's argument. ensureExperimentRecords is called from packages/payload-plugin-ab/src/hooks/buildParentAfterChangeHook.ts:28 and :55 with that factory's parentCollectionSlug, which plugin.ts:55 sets to collection.slug, the same value plugin.ts:59 passes to the delete hook.
  • The and form is how the package combines conditions elsewhere: where: { and: conditions } (packages/payload-plugin-ab/src/hooks/buildParentBeforeChangeHook.ts:41), { and: conditions } (packages/payload-plugin-ab/src/utils/recomputeManifest.ts:44), and: [ ... ] (packages/payload-plugin-ab/src/utils/injectAdminFields.ts:117).
Test to add

How the package is tested at daf914b7:

  • Vitest 2 ("vitest": "^2.1.8", packages/payload-plugin-ab/package.json:122), script "test": "vitest run" (package.json:88).
  • packages/payload-plugin-ab/vitest.config.ts: environment: "node", globals: false (import describe, it, expect, vi from vitest), files tests/**/*.test.{ts,tsx}.
  • Hook tests live in packages/payload-plugin-ab/tests/hooks/ (buildParentAfterChangeHook, buildParentBeforeChangeHook, ensureExperimentRecords) and run without a database: each calls the hook or function directly with a hand-built req, mocking req.payload methods with vi.fn() or, in the afterChange test, the helper modules with vi.mock. There is no test for buildParentAfterDeleteHook yet.
  • Models: the mocked payload in packages/payload-plugin-ab/tests/hooks/ensureExperimentRecords.test.ts:18-46 and the hook call through a cast in packages/payload-plugin-ab/tests/hooks/buildParentAfterChangeHook.test.ts:25-28.

Add packages/payload-plugin-ab/tests/hooks/buildParentAfterDeleteHook.test.ts. Starting point (not run):

import { describe, expect, it, vi } from "vitest";
import { buildParentAfterDeleteHook } from "../../src/hooks/buildParentAfterDeleteHook";
import type { AbTestingPluginConfig, CollectionABConfig } from "../../src/types/config";

type Row = Record<string, string>;
type Where = Record<string, unknown>;

const abConfig: CollectionABConfig = { generatePath: () => null };
const pluginConfig = {
  collections: { pages: abConfig, posts: abConfig },
  storage: {} as never,
} as AbTestingPluginConfig;

// Supports what the hook sends: `and` and `equals`.
function matches(row: Row, where: Where): boolean {
  return Object.entries(where).every(([field, condition]) => {
    if (field === "and") return (condition as Where[]).every((w) => matches(row, w));
    return row[field] === (condition as { equals: unknown }).equals;
  });
}

function makeReq(rows: Row[]) {
  const store = { rows };
  const payload = {
    config: { localization: false },
    find: vi.fn().mockResolvedValue({ docs: [] }),
    delete: vi.fn().mockImplementation(({ where }: { where: Where }) => {
      store.rows = store.rows.filter((row) => !matches(row, where));
      return Promise.resolve({ docs: [] });
    }),
  };
  return { req: { payload } as never, store };
}

const run = (collection: string, id: number, req: never) =>
  (
    buildParentAfterDeleteHook(collection, abConfig, pluginConfig) as unknown as (
      args: Record<string, unknown>
    ) => Promise<unknown>
  )({ doc: { id }, id, req });

describe("buildParentAfterDeleteHook", () => {
  it("keeps another collection's experiment row when the ids are equal", async () => {
    const { req, store } = makeReq([
      { parentCollection: "pages", parentDocId: "1" },
      { parentCollection: "posts", parentDocId: "1" },
    ]);
    await run("posts", 1, req);
    expect(store.rows).toEqual([{ parentCollection: "pages", parentDocId: "1" }]);
  });

  it("removes every row of the deleted parent", async () => {
    const { req, store } = makeReq([
      { parentCollection: "pages", parentDocId: "1", locale: "en" },
      { parentCollection: "pages", parentDocId: "1", locale: "de" },
      { parentCollection: "pages", parentDocId: "2", locale: "en" },
    ]);
    await run("pages", 1, req);
    expect(store.rows).toEqual([{ parentCollection: "pages", parentDocId: "2", locale: "en" }]);
  });
});

Why the mock is this small: generatePath: () => null skips storage.clear (hook lines 36-41), config.localization: false makes getLocales return [undefined] (packages/payload-plugin-ab/src/utils/getLocales.ts:6), and find returning no docs skips the variant unlinking (lines 43-66). The delete mock applies the where to an in-memory list, so the test checks which rows survive, not the shape of the query. With the current code the first case fails (both rows are removed) and the second passes; after the change both pass.

Run: bun install at the repo root (CLAUDE.md:74), then bun run test in packages/payload-plugin-ab. One app pulls a private git repository (apps/content-agent-demo/package.json:36). If the install fails on it, install as CI does with bun install --frozen-lockfile --filter '!./apps/*' (.github/workflows/release.yml:55-62). That install leaves out the apps, so the pre-push hook's repo-wide check-types (lefthook.yml:13-16) fails in apps this change does not touch (release.yml:21-24). Push with LEFTHOOK=0 in that case, as CI does.

Behavioural spec, end to end with the Local API (traced through the code, not run):

  1. Payload 3 with @payloadcms/db-postgres (default serial ids) and an empty database.
  2. Two collections, pages and posts, each with a slug text field and without versions.drafts. Plugin config:
import { abTestingPlugin } from "@focus-reactive/payload-plugin-ab";
import { payloadGlobalAdapter } from "@focus-reactive/payload-plugin-ab/adapters/payload-global";

abTestingPlugin({
  storage: payloadGlobalAdapter(),
  collections: {
    pages: { generatePath: ({ doc }) => (doc.slug ? `/${doc.slug}` : null) },
    posts: { generatePath: ({ doc }) => (doc.slug ? `/blog/${doc.slug}` : null) },
  },
})
  1. Run:
const page = await payload.create({ collection: "pages", data: { slug: "about" } });
await payload.create({
  collection: "pages",
  data: { slug: "about--v1", _abVariantOf: page.id, _abPassPercentage: 50 },
});
const post = await payload.create({ collection: "posts", data: { slug: "hello" } });
// empty database: page.id === post.id === 1

const where = { parentCollection: { equals: "pages" } };
const before = await payload.find({ collection: "ab-experiments", where });
// before.totalDocs === 1 (manifestKey "/about")

await payload.delete({ collection: "posts", id: post.id });

const after = await payload.find({ collection: "ab-experiments", where });
// today: after.totalDocs === 0; expected after the fix: 1

Expected: deleting posts 1 removes only rows with parentCollection = "posts" and parentDocId = "1", and the pages row stays. Today every row with parentDocId = "1" is removed. With debug: true the experiments collection is visible in the admin (buildExperimentsCollection.ts:7), so the same check can be done there.

Acceptance criteria
  • Deleting a non-variant document in collection A removes only experiment rows with parentCollection = A and parentDocId = String(id); rows of collection B with the same parentDocId remain.
  • Deleting a non-variant document still removes all of its own rows (one per locale in a localized config).
  • The new test file fails on the current code and passes with the change.
  • bun run test in packages/payload-plugin-ab passes.
  • bun run build in packages/payload-plugin-ab succeeds. The package has no check-types script (package.json:85-94), and its tsconfig.json includes only src/**/*.
  • bun run lint in packages/payload-plugin-ab reports no problems in the two touched files. Warnings it reports in other files are out of scope; the repository carries legacy lint warnings (lefthook.yml:17-20).
  • No other file is changed.
Out of scope / do not change
  • No schema change and no data migration: parentCollection is required and always written (see Root cause and Change).
  • Rows already lost to this bug are not restored by the fix. ensureExperimentRecords re-creates a row, with a new startedAt (ensureExperimentRecords.ts:63), on the next non-draft save of the parent or of one of its variants (buildParentAfterChangeHook.ts:28 and :55), when the parent's generatePath returns a non-null path and the variant lookup finds at least one variant (ensureExperimentRecords.ts:31-44). That lookup uses draft: false without a _status filter, so in a collection with drafts a variant that has never been published counts too.
  • The rest of the hook stays as it is: the variant branch, the manifest clearing and the variant unlinking already work on the deleting collection only.
  • No change to the experiments collection definition, ensureExperimentRecords, the manifest or variant logic, or packages/payload-plugin-analytics.
Commit and PR

Releases run through multi-semantic-release with conventional commit types (CLAUDE.md:83-104, .releaserc.json). Use a fix commit, which gives a patch release; this package's changelog entries use the ab scope (packages/payload-plugin-ab/CHANGELOG.md:6, :13), for example fix(ab): scope experiment row cleanup on delete to the deleted document's collection. Do not edit CHANGELOG.md or the version field: the release job writes both (.releaserc.json:14-28, CLAUDE.md:122).

Open a PR against main. Do not push to main directly: every push to main runs the Release workflow (.github/workflows/release.yml:3-6), which publishes the changed packages to npm (.releaserc.json:21, CLAUDE.md:89-90), so merging the PR publishes the patch release.

Other places checked

Searched packages/payload-plugin-ab/src and packages/payload-plugin-analytics/src for experimentsCollectionSlug, AB_EXPERIMENTS_SLUG, ab-experiments, parentDocId and parentCollection, and for every call that writes data:

  • payload-plugin-ab: the experiments collection is read or written in two files. ensureExperimentRecords.ts:46-53 finds a row by manifestKey, and :56-67 creates it. buildParentAfterDeleteHook.ts:68-78 is the only delete and the only parentDocId-only filter. plugin.ts:66-67 builds the collection and plugin.ts:71 registers it. The other writes in the package (payload.update at packages/payload-plugin-ab/src/utils/applyVariantPercentage.ts:24, :38 and buildParentAfterDeleteHook.ts:55, payload.db.updateOne at applyVariantPercentage.ts:61, payload.duplicate at packages/payload-plugin-ab/src/endpoints/duplicateVariant.ts:50, payload.updateGlobal at packages/payload-plugin-ab/src/adapters/payloadGlobal/index.ts:17, :36, and the Edge Config request at packages/payload-plugin-ab/src/adapters/vercelEdge/api/updateEdgeConfig.ts:11) target content documents or the manifest, not experiment rows.
  • payload-plugin-analytics: read-only. packages/payload-plugin-analytics/src/services/queries/getAbExperimentRecords.ts:25-31 reads all rows, and :41-48 reads one by manifestKey. Callers pass parentCollection and parentDocId together to getExperimentBucketMeta (packages/payload-plugin-analytics/src/services/queries/getAbOverview.ts:160-166, packages/payload-plugin-analytics/src/services/queries/getAbExperimentStats.ts:75-81), which queries the parentCollection collection by parentDocId (packages/payload-plugin-analytics/src/services/queries/getExperimentBucketMeta.ts:28-30). No writes and no parentDocId-only filter.
Ngôn ngữ chính
TypeScript
Star
34
Fork
5
Merge trung bình
2 ngày 4 giờ
Pull request đã merge (30 ngày)
41

Chuẩn bị môi trường

Dự án này không cung cấp dev container, Dockerfile hay hướng dẫn đóng góp, nên bạn cần tự thiết lập môi trường: hãy bắt đầu từ README và xem hướng dẫn đóng góp lần đầu của chúng tôi để biết các bước chung.

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của focusreactive/payload-plugins

Tất cả issue của focusreactive/payload-plugins

Issue tương tự

Thêm issue về TypeScript

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.