| 1 | import { readFileSync } from "node:fs"; |
| 2 | import { describe, expect, it } from "vitest"; |
| 3 | import { buildFunnelReport, funnelSql, parseArgs } from "../scripts/report-funnel.mjs"; |
| 4 | import { contributionCohorts, exportPublicHistory } from "../scripts/report-contribution-cohorts.mjs"; |
| 5 | import { FUNNEL_COUNTER_FIELDS } from "../src/schema"; |
| 6 | import worker from "../src/index"; |
| 7 | import { harness, postJson } from "./support"; |
| 8 | |
| 9 | const NOW = new Date("2026-11-10T00:00:00Z"); |
| 10 | const ID = "3f2a9c1e-0000-4000-8000-000000000001"; |
| 11 | const SECOND = "3f2a9c1e-0000-4000-8000-000000000002"; |
| 12 | function counts(values: Record<string, number> = {}) { return { ...Object.fromEntries(FUNNEL_COUNTER_FIELDS.map((field) => [field, 0])), ...values }; } |
| 13 | function native(event: string, at: string, id = ID) { return { install_id: id, event, surface: "tui", install_kind: "install", session_source: "interactive", received_at: at, schema_version: 4, turns_ok: 1, weight: 1 }; } |
| 14 | function receipt() { |
| 15 | return { format: "codewhale-funnel-receipt-v1", source: "synthetic", coverage: { from: "2026-10-01T00:00:00Z", to: "2026-11-01T00:00:00Z", complete: true, accepted_only: true }, website_rows: [{ day: "2026-10-04", counters: counts({ install_intent: 3, install_confirmed: 2, quickstart_confirmed: 1 }), weight: 2 }], native_rows: [native("install_or_upgrade", "2026-10-02T00:00:00Z"), native("model_usage", "2026-10-03T00:00:00Z"), native("install_or_upgrade", "2026-10-30T00:00:00Z", SECOND)] }; |
| 16 | } |
| 17 | |
| 18 | describe("existing-pipeline owner funnel report", () => { |
| 19 | it("separates weighted self-reports from native technical outcomes and seven-day eligibility", () => { |
| 20 | const report = buildFunnelReport(receipt(), { now: NOW }); |
| 21 | expect(report.synthetic).toBe(true); |
| 22 | expect(report.website.totals).toMatchObject({ install_intent: 6, install_confirmed: 4, quickstart_confirmed: 2 }); |
| 23 | expect(report.native.observed_initialized_ids).toBe(2); |
| 24 | expect(report.native.incomplete_followup_ids).toBe(1); |
| 25 | expect(report.native.seven_day_initialization_cohort).toMatchObject({ denominator: 1, numerator: 1, fraction: 1 }); |
| 26 | expect(JSON.stringify(report)).not.toContain(ID); |
| 27 | expect(report.caveats.join(" ")).toContain("late cancellation"); |
| 28 | }); |
| 29 | |
| 30 | it("handles repeated accepted native rows without turning them into new installs", () => { |
| 31 | const input = receipt(); input.native_rows.push(input.native_rows[0], input.native_rows[1]); |
| 32 | const report = buildFunnelReport(input, { now: NOW }); |
| 33 | expect(report.native.observed_initialized_ids).toBe(2); |
| 34 | expect(report.native.seven_day_initialization_cohort.numerator).toBe(1); |
| 35 | }); |
| 36 | |
| 37 | it("does not let older model observations hide completion after a reset state", () => { |
| 38 | const input = receipt(); input.native_rows.unshift(native("model_usage", "2026-10-01T12:00:00Z")); |
| 39 | expect(buildFunnelReport(input, { now: NOW }).native.seven_day_initialization_cohort.numerator).toBe(1); |
| 40 | }); |
| 41 | |
| 42 | it("excludes CI-contaminated native identities and reports missing coverage as unavailable", () => { |
| 43 | const input = receipt(); input.native_rows.push({ ...native("session_start", "2026-10-04T00:00:00Z"), session_source: "ci" }); |
| 44 | const report = buildFunnelReport(input, { now: NOW }); |
| 45 | expect(report.native.excluded_ci_ids).toBe(1); |
| 46 | expect(report.native.observed_completed_ids).toBe(0); |
| 47 | expect(report.native.seven_day_initialization_cohort.fraction).toBeNull(); |
| 48 | input.coverage.complete = false; |
| 49 | expect(buildFunnelReport(input, { now: NOW }).native.seven_day_initialization_cohort.unavailable_reason).toContain("incomplete"); |
| 50 | }); |
| 51 | |
| 52 | it("excludes fleet worker, agent and scripted starts like CI, and accepts v6 model usage", () => { |
| 53 | for (const source of ["fleet_worker", "agent", "scripted"]) { |
| 54 | const input = receipt(); |
| 55 | input.native_rows.push({ ...native("session_start", "2026-10-04T00:00:00Z"), session_source: source }); |
| 56 | input.native_rows.push({ ...native("model_usage", "2026-10-04T00:00:00Z"), schema_version: 6 }); |
| 57 | const report = buildFunnelReport(input, { now: NOW }); |
| 58 | expect(report.native.excluded_ci_ids, source).toBe(1); |
| 59 | expect(report.native.observed_completed_ids, source).toBe(0); |
| 60 | } |
| 61 | const input = receipt(); input.native_rows.push({ ...native("model_usage", "2026-10-04T00:00:00Z"), schema_version: 5 }); |
| 62 | expect(() => buildFunnelReport(input, { now: NOW })).toThrow(/version/); |
| 63 | }); |
| 64 | |
| 65 | it("does not compute a cohort fraction from sampled native records", () => { |
| 66 | const input = receipt(); input.native_rows[0].weight = 4; |
| 67 | expect(buildFunnelReport(input, { now: NOW }).native.seven_day_initialization_cohort).toMatchObject({ fraction: null, sampled: true }); |
| 68 | }); |
| 69 | |
| 70 | it("rejects unsupported sources, unaccepted buffers, unknown counters and truncated receipts", () => { |
| 71 | const input = receipt(); input.coverage.accepted_only = false; |
| 72 | expect(() => buildFunnelReport(input, { now: NOW })).toThrow(/accepted-only/); |
| 73 | expect(() => buildFunnelReport({ ...receipt(), source: "local-buffer" }, { now: NOW })).toThrow(/source/); |
| 74 | const unknown = receipt(); unknown.website_rows[0].counters = counts({ raw_query: 1 }); |
| 75 | expect(() => buildFunnelReport(unknown, { now: NOW })).toThrow(/counter field/); |
| 76 | expect(() => buildFunnelReport({ ...receipt(), native_rows: Array(10001).fill(native("model_usage", "2026-10-02T00:00:00Z")) }, { now: NOW })).toThrow(/truncated/); |
| 77 | }); |
| 78 | |
| 79 | it("refuses future or oversized windows and avoids printing query plans as observed data", () => { |
| 80 | expect(() => buildFunnelReport({ ...receipt(), coverage: { ...receipt().coverage, to: "2026-12-01T00:00:00Z" } }, { now: NOW })).toThrow(/future/); |
| 81 | expect(() => buildFunnelReport({ ...receipt(), coverage: { ...receipt().coverage, from: "2025-01-01T00:00:00Z" } }, { now: NOW })).toThrow(/90/); |
| 82 | const sql = funnelSql("2026-10-01T00:00:00Z", "2026-11-01T00:00:00Z"); |
| 83 | expect(sql.website).not.toContain("index1"); |
| 84 | expect(sql.website).toContain("blob19 = '5'"); |
| 85 | expect(sql.native).toContain("LIMIT 10001"); |
| 86 | expect(() => funnelSql("'; SELECT private", "2026-11-01T00:00:00Z")).toThrow(/from/); |
| 87 | expect(parseArgs(["--sql"]).sql).toBe(true); |
| 88 | }); |
| 89 | |
| 90 | it("reports the accepted local pipeline fixture, while rejection creates no receipt rows", async () => { |
| 91 | const batch = JSON.parse(readFileSync(new URL("./golden/browser-v5.json", import.meta.url), "utf8")); |
| 92 | const { env, written } = harness(); |
| 93 | expect((await worker.fetch(postJson(batch), env)).status).toBe(204); |
| 94 | const point = written.find((row) => row.blobs[0] === "funnel_usage")!; |
| 95 | const input = receipt(); input.website_rows = [{ day: "2026-10-04", counters: JSON.parse(point.blobs[17]), weight: 1 }]; |
| 96 | expect(buildFunnelReport(input, { now: NOW }).website.totals.install_intent).toBe(1); |
| 97 | const rejected = harness(); batch.events[1].counters.private_query = 1; |
| 98 | expect((await worker.fetch(postJson(batch), rejected.env)).status).toBe(400); |
| 99 | expect(rejected.written).toHaveLength(0); |
| 100 | }); |
| 101 | }); |
| 102 | |
| 103 | function publicSnapshot() { |
| 104 | const user = (login: string) => ({ id: login.toLowerCase() === "alice" ? 1 : 2, login, type: "User" }); |
| 105 | return { format: "codewhale-public-contributions-v1", repository: "codewhale-hq/CodeWhale", source: "synthetic", coverage: { issues_complete: true, pulls_complete: true }, issues: [ |
| 106 | { number: 1, created_at: "2026-10-01T00:00:00Z", user: user("Alice") }, |
| 107 | { number: 2, created_at: "2026-10-04T00:00:00Z", user: user("alice") }, |
| 108 | { number: 3, created_at: "2026-10-05T00:00:00Z", user: user("Bob"), pull_request: {} }, |
| 109 | { number: 4, created_at: "2026-10-05T00:00:00Z", user: { login: "a-bot", type: "Bot" } }, |
| 110 | ], pulls: [ |
| 111 | { number: 3, merged_at: "2026-10-08T00:00:00Z", user: user("Bob") }, |
| 112 | { number: 5, merged_at: "2026-10-06T00:00:00Z", user: user("Bob") }, |
| 113 | { number: 6, merged_at: null, user: user("Alice") }, |
| 114 | ] }; |
| 115 | } |
| 116 | |
| 117 | describe("separate public repository contribution cohorts", () => { |
| 118 | it("finds first issues and first merges separately, excluding bots and PRs from issues", () => { |
| 119 | const result = contributionCohorts(publicSnapshot(), { from: "2026-10-01T00:00:00Z", to: "2026-11-01T00:00:00Z" }); |
| 120 | expect(result.totals).toEqual({ first_public_issue_authors: 1, first_merged_pr_authors: 1 }); |
| 121 | expect(result.days.find((row) => row.first_merged_pr_authors)?.day).toBe("2026-10-06"); |
| 122 | expect(result.input_counts).toEqual({ public_issues: 2, merged_prs: 2, excluded_bot_or_deleted_records: 1 }); |
| 123 | expect(JSON.stringify(result)).not.toMatch(/Alice|alice|Bob/); |
| 124 | }); |
| 125 | |
| 126 | it("does not count a returning contributor's later issue as their first in a reporting window", () => { |
| 127 | const result = contributionCohorts(publicSnapshot(), { from: "2026-10-03T00:00:00Z", to: "2026-10-07T00:00:00Z" }); |
| 128 | expect(result.totals).toEqual({ first_public_issue_authors: 0, first_merged_pr_authors: 1 }); |
| 129 | }); |
| 130 | |
| 131 | it("refuses incomplete history instead of trusting FIRST_TIME_CONTRIBUTOR display metadata", () => { |
| 132 | const snapshot = publicSnapshot(); snapshot.coverage.pulls_complete = false; |
| 133 | expect(() => contributionCohorts(snapshot)).toThrow(/incomplete/); |
| 134 | }); |
| 135 | |
| 136 | it("verifies public visibility before reading history and fails at the pagination cap", async () => { |
| 137 | const privateCalls: string[] = []; |
| 138 | await expect(exportPublicHistory({ get: async (url) => { privateCalls.push(url); return { private: true }; } })).rejects.toThrow(/public/); |
| 139 | expect(privateCalls).toHaveLength(1); |
| 140 | await expect(exportPublicHistory({ maxPages: 1, get: async (url) => url.includes("?") ? Array(100).fill({}) : { private: false } })).rejects.toThrow(/incomplete/); |
| 141 | }); |
| 142 | |
| 143 | it("completes short paginated histories without writing handles or contacting a telemetry sink", async () => { |
| 144 | const snapshot = publicSnapshot(); const calls: string[] = []; |
| 145 | const exported = await exportPublicHistory({ get: async (url) => { calls.push(url); return url.includes("/issues?") ? snapshot.issues : url.includes("/pulls?") ? snapshot.pulls : { private: false }; } }); |
| 146 | expect(calls).toHaveLength(3); |
| 147 | expect(contributionCohorts(exported).synthetic).toBe(false); |
| 148 | }); |
| 149 | }); |
| 150 |