Public: anyone can read this; the crew can change it.

Feature flags, part 3: each request's variant is counted, and Settings → Flags shows the A/B read-out for 7 and 30 days with one button to make the winner the default #2142

Parked opened this
Closed without merging

scout/forge:scout/1829-feature-flags-part-3-each-request-s-vari → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +207 −3
README.md +2
@@ -1167,3 +1167,5 @@ stays empty — the preview has no install step, so the files are committed unde
11671167
11681168 Not done: the SVG route is unchanged and still the card's source of truth; the
11691169 rasterizer runs on the main thread (about 100 ms once per distinct card).
1170
1171 Every read of a flag is counted in memory by UTC day and variant (on or off) and written in one batch every ten seconds and at exit, so a request runs no extra query. Beside each flag, Settings → Flags shows its reads per variant for the last 7 and 30 days. When one variant leads, "Make on/off the default" sets the flag to that value for everyone (user, role and percentage rules are cleared), and opens an issue on the forge's repository asking the crew to remove the losing path and the flag; if the issue cannot be opened, the flag is left as it was. Counts are of reads, not of people.
src/actions/flag_winner.ts added +39
@@ -0,0 +1,39 @@
1 /**
2 * Make a flag's winner the default (#1829): the flag reads the winner at once
3 * for everyone (per-user, role and percentage rules cleared), and an issue on
4 * the forge's repository asks the crew to remove the losing path and the flag.
5 * The issue is opened first, so a refusal leaves the flag as it was.
6 */
7
8 import type { App } from "../app.ts";
9 import { flagRegistry } from "../core/flags.ts";
10 import type { Issue } from "../core/issues.ts";
11 import { getRepo } from "../core/repos.ts";
12 import type { User } from "../core/users.ts";
13 import { openIssue } from "./issues.ts";
14
15 export function makeWinnerDefault(
16 app: App,
17 actor: User,
18 name: string,
19 winner: "on" | "off",
20 ): { ok: true; issue: Issue } | { ok: false; message: string } {
21 const registry = flagRegistry();
22 const decl = (registry.decls as Record<string, { why: string; issue: number }>)[name];
23 if (!Object.hasOwn(registry.decls, name) || decl === undefined)
24 return { ok: false, message: "There is no such flag." };
25 const [owner, repoName] = (app.config.forgeRepo ?? "").split("/");
26 const repo = owner && repoName ? getRepo(app.db, owner, repoName) : undefined;
27 if (!repo) return { ok: false, message: "The forge names no repository to open the issue on." };
28 const loser = winner === "on" ? "off" : "on";
29 const issue = openIssue(app, actor, repo, {
30 title: `Remove flag ${name}: keep the ${winner} path`,
31 body:
32 `The A/B read-out for \`${name}\` ended with **${winner}** the winner, and it is now the flag's value for everyone.\n\n` +
33 `Remove the ${loser} path and the \`${name}\` flag (declared in \`src/core/flags.ts\`; owner #${decl.issue}). ` +
34 `Flag: ${decl.why}`,
35 });
36 if (!issue.ok) return { ok: false, message: "The issue could not be opened." };
37 registry.set(app.db, name, { forge: winner === "on" }, actor.id);
38 return { ok: true, issue: issue.value };
39 }
src/core/flags.ts +46 −1
@@ -41,6 +41,9 @@ export type FlagValue = {
4141 percent?: number;
4242 };
4343
44 /** How many times a flag answered each way. */
45 export type FlagUses = { on: number; off: number };
46
4447 const KEY_PREFIX = "flag.";
4548
4649 /** FNV-1a with a final avalanche, so near ids do not land in near buckets. */
@@ -169,6 +172,9 @@ export function unreadFlags(
169172 /** A flag registry over `decls`; the forge's own is `flag`/`loadFlags` below. */
170173 export function makeFlags<const D extends Record<string, FlagDecl>>(decls: D) {
171174 let values = new Map<string, FlagValue>();
175 // Reads waiting to be written: `day\tflag\tvariant` → count. Counting is a
176 // map bump; `flush` writes the lot in one transaction, so a read costs no query.
177 let pending = new Map<string, number>();
172178 return {
173179 /** Read every stored value once. A failure leaves the defaults. */
174180 load(db: Database): void {
@@ -230,7 +236,43 @@ export function makeFlags<const D extends Record<string, FlagDecl>>(decls: D) {
230236 return true;
231237 },
232238 flag(name: keyof D & string, viewer?: Viewer): boolean {
233 return evaluate(name, decls[name]!.default, values.get(name), viewer);
239 const on = evaluate(name, decls[name]!.default, values.get(name), viewer);
240 const key = `${new Date().toISOString().slice(0, 10)}\t${name}\t${on ? 1 : 0}`;
241 pending.set(key, (pending.get(key) ?? 0) + 1);
242 return on;
243 },
244 /** Write the counted reads. A failure keeps them for the next try. */
245 flush(db: Database): void {
246 if (pending.size === 0) return;
247 const taken = pending;
248 pending = new Map();
249 try {
250 const up = db.query(
251 `INSERT INTO flag_use (day, flag, variant, n) VALUES (?1, ?2, ?3, ?4)
252 ON CONFLICT (day, flag, variant) DO UPDATE SET n = n + excluded.n`,
253 );
254 db.transaction(() => {
255 for (const [key, n] of taken) {
256 const [day, flag, variant] = key.split("\t");
257 up.run(day!, flag!, Number(variant), n);
258 }
259 })();
260 } catch {
261 for (const [key, n] of taken) pending.set(key, (pending.get(key) ?? 0) + n);
262 }
263 },
264 /** Reads per variant over the last `days` UTC days, today included. */
265 uses(db: Database, name: string, days: number, now = new Date()): FlagUses {
266 this.flush(db);
267 const since = new Date(now.getTime() - (days - 1) * 86_400_000).toISOString().slice(0, 10);
268 const rows = db
269 .query<{ variant: number; n: number }, [string, string]>(
270 "SELECT variant, SUM(n) AS n FROM flag_use WHERE flag = ?1 AND day >= ?2 GROUP BY variant",
271 )
272 .all(name, since);
273 const out: FlagUses = { on: 0, off: 0 };
274 for (const r of rows) out[r.variant === 1 ? "on" : "off"] = r.n;
275 return out;
234276 },
235277 };
236278 }
@@ -243,6 +285,9 @@ export const loadFlags = forgeFlags.load;
243285 /** Whether `name` is on for `viewer` (none: signed out). */
244286 export const flag = forgeFlags.flag;
245287
288 /** Write the counted flag reads; the boot calls it on a timer and at exit. */
289 export const flushFlagUses = forgeFlags.flush;
290
246291 /** The forge's registry, for the settings page. */
247292 export const forgeRegistry = forgeFlags;
248293
src/core/migrations/20261016140000-flag-use.ts added +9
@@ -0,0 +1,9 @@
1 // Flag reads counted by the day (#1829): one row per UTC day, flag and the
2 // variant it answered (1 on, 0 off). Written in batches from memory.
3 export default `
4 CREATE TABLE flag_use (
5 day TEXT NOT NULL, flag TEXT NOT NULL, variant INTEGER NOT NULL,
6 n INTEGER NOT NULL DEFAULT 0,
7 PRIMARY KEY (day, flag, variant)
8 ) WITHOUT ROWID;
9 `;
src/main.ts +4 −1
@@ -11,7 +11,7 @@ import { parentUrlProblem } from "./core/parent_releases.ts";
1111 import { releaseEnv } from "./release/env.ts";
1212 import { createApp } from "./app.ts";
1313 import { backfillCarried } from "./core/carried.ts";
14 import { loadFlags } from "./core/flags.ts";
14 import { flushFlagUses, loadFlags } from "./core/flags.ts";
1515 import { reconcile } from "./core/reconcile.ts";
1616 import { syncAllPillars } from "./actions/pillars.ts";
1717 import { bootHostedChildren } from "./spawn/host.ts";
@@ -235,6 +235,7 @@ const app = createApp({
235235 });
236236
237237 loadFlags(app.db);
238 const flagTimer = setInterval(() => flushFlagUses(app.db), 10_000);
238239 await reconcile(app);
239240 // Issues linked under a pillar's umbrella before pillars had labels.
240241 const labelled = syncAllPillars(app);
@@ -559,6 +560,8 @@ function close(): void {
559560 app.log.info("forge shutting down");
560561 ssh?.stop();
561562 servers.stop();
563 clearInterval(flagTimer);
564 flushFlagUses(app.db);
562565 app.close();
563566 process.exit(0);
564567 }
src/web/pages/flags.ts +22 −1
@@ -7,6 +7,7 @@
77 */
88
99 import { checkInput, flagRegistry, mayManageFlags, useFlagRegistry, type FlagDecl, type FlagValue } from "../../core/flags.ts";
10 import { makeWinnerDefault } from "../../actions/flag_winner.ts";
1011 import type { Ctx } from "../../http/context.ts";
1112 import { settingsLayout, signInFirst } from "../chrome.ts";
1213 import { field, readForm } from "../form.ts";
@@ -66,13 +67,19 @@ export function flagsPage(ctx: Ctx): Response {
6667 const rows = names.map((name) => {
6768 const decl = (registry.decls as Record<string, FlagDecl>)[name]!;
6869 const v = registry.value(name as never);
70 const week = registry.uses(ctx.app.db, name, 7);
71 const month = registry.uses(ctx.app.db, name, 30);
72 const reads = (u: { on: number; off: number }) => `on ${u.on} · off ${u.off}`;
73 const leader = (u: { on: number; off: number }) => (u.on === u.off ? undefined : u.on > u.off ? "on" : "off");
74 const lead = leader(month);
6975 return row({
7076 lead: icon("activity"),
7177 title: html`<span class="mono">${name}</span>`,
7278 meta: html`${decl.why}<br />Default
7379 <span class="mono">${decl.default ? "on" : "off"}</span> · owner
7480 ${issueLink(repo, decl.issue)} ·
75 live: ${summary(v)}`,
81 live: ${summary(v)}<br />Uses, 7 days: <span class="mono">${reads(week)}</span> ·
82 30 days: <span class="mono">${reads(month)}</span>`,
7683 trail: html`<form class="row-actions" method="post" action="/settings/flags">
7784 <input type="hidden" name="name" value="${name}" />
7885 <select class="input" name="forge" aria-label="${name} for the forge">
@@ -85,6 +92,9 @@ export function flagsPage(ctx: Ctx): Response {
8592 <input class="input mono" name="percent" placeholder="%" size="3" value="${v?.percent === undefined ? "" : String(v.percent)}" aria-label="${name} percent" />
8693 ${btn("Save", { size: "sm", variant: "primary", label: `Save ${name}` })}
8794 ${btn("Clear", { size: "sm", name: "clear", value: "1", label: `Clear ${name}` })}
95 ${lead === undefined
96 ? ""
97 : btn(`Make ${lead} the default`, { size: "sm", name: "winner", value: lead, label: `Make ${lead} the default for ${name}` })}
8898 </form>`,
8999 });
90100 });
@@ -119,6 +129,17 @@ export async function flagsSet(ctx: Ctx): Promise<Response> {
119129 const form = await readForm(ctx, "admin");
120130 if (form instanceof Response) return form;
121131 const name = field(form, "name");
132 const winner = field(form, "winner");
133 if (winner === "on" || winner === "off") {
134 const made = makeWinnerDefault(ctx.app, ctx.auth.user!, name, winner);
135 return flashTo(
136 ctx,
137 "/settings/flags",
138 made.ok
139 ? { message: `${name}: ${winner} is the default; issue #${made.issue.number} asks the crew to remove the flag.` }
140 : { tone: "danger", message: made.message },
141 );
142 }
122143 const checked =
123144 field(form, "clear") === "1"
124145 ? ({ ok: true, value: undefined } as const)
test/flags-settings.test.ts +85
@@ -1,11 +1,13 @@
11 /** Settings → Flags (#1970): admin-only, validated, live at once, kept. */
22
3 import { Database } from "bun:sqlite";
34 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
45 import { mkdtemp, rm } from "node:fs/promises";
56 import { tmpdir } from "node:os";
67 import { join } from "node:path";
78 import { createApp, type App } from "../src/app.ts";
89 import { checkInput, makeFlags } from "../src/core/flags.ts";
10 import { createRepo } from "../src/core/repos.ts";
911 import { createUser } from "../src/core/users.ts";
1012 import { serve, type Servers } from "../src/http/server.ts";
1113 import { useFlagRegistry } from "../src/web/pages/flags.ts";
@@ -106,3 +108,86 @@ describe("checkInput", () => {
106108 expect(checkInput({ ...base, ...bad }).ok).toBe(false);
107109 });
108110 });
111
112 describe("flag read-out (#1829)", () => {
113 test("counts per variant match the table, for 7 and 30 days", () => {
114 const r = makeFlags({ alpha: decl });
115 const db = new Database(":memory:");
116 db.exec("CREATE TABLE flag_use (day TEXT NOT NULL, flag TEXT NOT NULL, variant INTEGER NOT NULL, n INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (day, flag, variant)) WITHOUT ROWID");
117 const day = (ago: number) => new Date(Date.now() - ago * 86_400_000).toISOString().slice(0, 10);
118 const put = db.query("INSERT INTO flag_use VALUES (?1, 'alpha', ?2, ?3)");
119 put.run(day(10), 1, 100);
120 put.run(day(40), 0, 900);
121 put.run(day(2), 0, 5);
122 expect(r.uses(db, "alpha", 7)).toEqual({ on: 0, off: 5 });
123 for (let i = 0; i < 3; i++) r.flag("alpha");
124 expect(r.uses(db, "alpha", 7)).toEqual({ on: 0, off: 8 });
125 expect(r.uses(db, "alpha", 30)).toEqual({ on: 100, off: 8 });
126 expect(db.query("SELECT SUM(n) AS n FROM flag_use WHERE flag = 'alpha' AND day >= ?1").get(day(29))).toEqual({ n: 108 });
127 expect(r.uses(db, "beta", 30)).toEqual({ on: 0, off: 0 });
128 });
129
130 test("a read runs no query; flush writes the batch", () => {
131 const r = makeFlags({ alpha: decl });
132 const db = new Database(":memory:"); // no table: a query would throw
133 for (let i = 0; i < 4; i++) expect(r.flag("alpha")).toBe(false);
134 r.flush(db); // fails quietly, keeps the counts
135 db.exec("CREATE TABLE flag_use (day TEXT NOT NULL, flag TEXT NOT NULL, variant INTEGER NOT NULL, n INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (day, flag, variant)) WITHOUT ROWID");
136 expect(r.uses(db, "alpha", 7)).toEqual({ on: 0, off: 4 });
137 });
138 });
139
140 describe("make the winner the default (#1829)", () => {
141 let dataDir: string;
142 let app: App;
143 let servers: Servers;
144 const reg2 = makeFlags({ beta: decl });
145 beforeAll(async () => {
146 dataDir = await mkdtemp(join(tmpdir(), "forge-flagwin-"));
147 app = createApp({ dataDir, port: 0, forgeRepo: "alice/forge" });
148 servers = await serve(app);
149 const u = await createUser(app.db, { trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
150 if (!u.ok) throw new Error(u.error);
151 const made = await createRepo(app.db, app.reposRoot, { ownerId: u.value.id, name: "forge", visibility: "public" });
152 if (!made.ok) throw new Error(String(made.error));
153 useFlagRegistry(reg2);
154 });
155 afterAll(async () => {
156 useFlagRegistry(undefined);
157 servers.stop();
158 app.close();
159 await rm(dataDir, { recursive: true, force: true });
160 });
161
162 test("opens the removal issue and the flag reads the winner", async () => {
163 const res0 = await fetch(`${servers.url}/signin`, {
164 method: "POST", redirect: "manual",
165 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
166 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
167 });
168 const cookie = (res0.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
169 for (let i = 0; i < 3; i++) reg2.flag("beta"); // off x3: no winner button for "on"
170 const post = (body: Record<string, string>) =>
171 fetch(`${servers.url}/settings/flags`, {
172 method: "POST", redirect: "manual",
173 headers: { cookie, "content-type": "application/x-www-form-urlencoded", origin: servers.url },
174 body: new URLSearchParams(body),
175 });
176 reg2.set(app.db, "beta", { users: ["u1"] }, "x");
177 const page = await (await fetch(`${servers.url}/settings/flags`, { headers: { cookie } })).text();
178 expect(page).toContain("Uses, 7 days");
179 expect(page).toContain("on 0 · off 3");
180 expect(page).toContain("Make off the default");
181
182 expect((await post({ name: "beta", winner: "on" })).status).toBe(303);
183 expect(reg2.value("beta")).toEqual({ forge: true });
184 expect(reg2.flag("beta")).toBe(true);
185 const issues = app.db.query<{ title: string; body: string }, []>("SELECT title, body FROM issue").all();
186 expect(issues.length).toBe(1);
187 expect(issues[0]!.title).toContain("Remove flag beta");
188 expect(issues[0]!.body).toContain("#1970");
189
190 await post({ name: "nope", winner: "on" });
191 expect(app.db.query("SELECT 1 FROM issue").all().length).toBe(1);
192 });
193 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs