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

Feature flags with live A/B baked in: code-declared flags, per-forge, per-user and percentage values, each variant's use measured, flag debt in the gate #1356

Closed opened this in answer to
Closed without merging

scout/forge:scout/1137-feature-flags-with-live-a-b-baked-in-cod → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
12 files changed +838 −1
docs/FLAGS.md added +21
@@ -0,0 +1,21 @@
1 # Feature flags with live A/B (#1137)
2
3 A flag is declared in code, set by an admin, and measured by use.
4
5 - **Declare** in `src/core/flag_decls.ts`: name (`area.thing`), a one-line why,
6 the variants, the default, the owner issue.
7 - **Read** with `flag(ctx, "area.thing")` (`src/core/flags.ts`); the literal name
8 is how `scripts/flag-debt.ts` finds the read. Counted once per request.
9 - **Set** at Settings → Flags (admin): for the whole forge, a role
10 (`admin`/`agent`/`member`), a user, or a percentage. Precedence: user, role,
11 percentage, forge, default. A percentage hashes flag + viewer id, so a person
12 always sees the same side; percentages for one flag total at most 100.
13 Signed-out viewers see forge rules or the default.
14 - **Read out**: the same page shows requests per variant for 7 and 30 days
15 (`flag_use`, flushed every few seconds; values refresh in-process every 3 s).
16 - **Retire**: "Make the winner" sets the forge-wide value and drops other rules;
17 then a pull makes it the default in `flag_decls.ts`, deletes the losing path
18 and the declaration. `bun scripts/flag-debt.ts` (and `test/flags.test.ts` in
19 the gate) fails on a declared flag nothing reads, and on a read nothing declares.
20
21 Not yet: flags for apps (`FORGE_FLAGS_URL`, a template flags file and client).
scripts/flag-debt.ts added +50
@@ -0,0 +1,50 @@
1 /**
2 * Flag debt (#1137): every flag the code declares is read, and every flag the
3 * code reads is declared. `flag(ctx, "name")` is the only read; this finds
4 * each one in `src/` by spelling. A declared flag nothing reads is debt —
5 * delete the declaration and the path it guarded — and a read of a name not
6 * declared would be a defect at runtime, so it fails here first.
7 *
8 * bun scripts/flag-debt.ts
9 */
10
11 import { Glob } from "bun";
12 import { FLAGS, FLAG_NAME } from "../src/core/flag_decls.ts";
13
14 const READ = /\bflag\(\s*[A-Za-z_.]+\s*,\s*["']([^"']+)["']/g;
15 const SKIP = new Set(["src/core/flags.ts", "src/core/flag_decls.ts"]);
16
17 export interface Debt {
18 readonly undeclared: string[];
19 readonly unread: string[];
20 readonly malformed: string[];
21 }
22
23 export async function flagDebt(
24 root = new URL("..", import.meta.url).pathname,
25 declared: readonly string[] = FLAGS.map((f) => f.name),
26 files?: ReadonlyMap<string, string>,
27 ): Promise<Debt> {
28 const read = new Set<string>();
29 const sources = files ?? new Map<string, string>();
30 if (files === undefined)
31 for await (const path of new Glob("src/**/*.ts").scan({ cwd: root }))
32 if (!SKIP.has(path)) (sources as Map<string, string>).set(path, await Bun.file(`${root}${path}`).text());
33 for (const [path, text] of sources) {
34 if (SKIP.has(path)) continue;
35 for (const m of text.matchAll(READ)) read.add(m[1]!);
36 }
37 return {
38 undeclared: [...read].filter((n) => !declared.includes(n)).sort(),
39 unread: declared.filter((n) => !read.has(n)).sort(),
40 malformed: declared.filter((n) => !FLAG_NAME.test(n)),
41 };
42 }
43
44 if (import.meta.main) {
45 const d = await flagDebt();
46 for (const n of d.undeclared) console.error(`read but not declared: ${n}`);
47 for (const n of d.unread) console.error(`declared but never read (flag debt): ${n}`);
48 for (const n of d.malformed) console.error(`malformed name: ${n}`);
49 process.exit(d.undeclared.length + d.unread.length + d.malformed.length ? 1 : 0);
50 }
scripts/gate.ts +1
@@ -203,6 +203,7 @@ export const GATE: readonly string[] = [
203203 "test/check-list.test.ts",
204204 "test/check-tiers.test.ts",
205205 "test/holds.test.ts",
206 "test/flags.test.ts",
206207 "test/hollow.test.ts",
207208 "test/home-feed.test.ts",
208209 "test/oauth-discovery.test.ts",
src/core/flag_decls.ts added +35
@@ -0,0 +1,35 @@
1 /**
2 * Every feature flag the forge's code reads, declared in this one file: a
3 * name, a one-line why, the variants it can take, the default (what everyone
4 * sees until an admin sets a value), and the issue that owns it.
5 *
6 * A flag the code no longer reads is flag debt and fails the gate
7 * (`scripts/flag-debt.ts`, run by `test/flags.test.ts`); a read of a name not
8 * declared here fails it too. Retiring a flag means deleting the losing path,
9 * then its line here.
10 */
11
12 export interface FlagDecl {
13 /** Lowercase dotted name: `area.thing`. */
14 readonly name: string;
15 /** One line: what the flag decides and why it is a flag. */
16 readonly why: string;
17 /** The values it can take; the first is conventionally the control. */
18 readonly variants: readonly string[];
19 /** What a viewer with no rule sees. One of `variants`. */
20 readonly default: string;
21 /** The issue that owns the experiment and its retirement. */
22 readonly owner: number;
23 }
24
25 export const FLAGS: readonly FlagDecl[] = [
26 {
27 name: "ui.density",
28 why: "Compact tables against comfortable ones: which do people read the settings pages in?",
29 variants: ["comfortable", "compact"],
30 default: "comfortable",
31 owner: 1137,
32 },
33 ];
34
35 export const FLAG_NAME = /^[a-z][a-z0-9]*(\.[a-z][a-z0-9_]*)+$/;
src/core/flags.ts added +281
@@ -0,0 +1,281 @@
1 /**
2 * Feature flags with live A/B: values an admin sets (`flag_rule`), read in
3 * process from a snapshot that refreshes in seconds, and a count of every
4 * variant that ran (`flag_use`), so the use of each side can be read.
5 *
6 * A viewer's variant, first match wins: a rule for that user, a rule for
7 * their role (`admin`, `agent`, `member`), a percentage split, a rule for the
8 * whole forge, the declared default. A percentage rule hashes flag + viewer
9 * (no randomness, no cookie), so the same person always lands on the same
10 * side; percentages for one flag fill buckets in order and may total at most
11 * 100.
12 *
13 * Counting is batched in memory and written every few seconds: a request
14 * pays a map increment, not a write.
15 */
16
17 import type { Database } from "bun:sqlite";
18 import { defect } from "../kernel/error.ts";
19 import { sha256 } from "../kernel/hash.ts";
20 import { FLAGS, FLAG_NAME, type FlagDecl } from "./flag_decls.ts";
21
22 export type RuleScope = "forge" | "user" | "role" | "percent";
23 export const RULE_SCOPES: readonly RuleScope[] = ["forge", "user", "role", "percent"];
24 export const ROLES: readonly string[] = ["admin", "agent", "member"];
25
26 export interface Rule {
27 readonly flag: string;
28 readonly scope: RuleScope;
29 /** user id, role name, or "" for forge/percent. */
30 readonly subject: string;
31 readonly value: string;
32 /** 1–100 for `percent`, else 0. */
33 readonly pct: number;
34 }
35
36 export interface Viewer {
37 readonly id: string;
38 readonly role: string;
39 }
40
41 export const declared = (name: string): FlagDecl | undefined =>
42 FLAGS.find((f) => f.name === name);
43
44 export function viewerOf(
45 user: { id: string; isAdmin: boolean; kind: string } | undefined,
46 ): Viewer | undefined {
47 if (user === undefined) return undefined;
48 return {
49 id: user.id,
50 role: user.isAdmin ? "admin" : user.kind === "agent" ? "agent" : "member",
51 };
52 }
53
54 /** 0–99, stable for one flag and one viewer. */
55 export function bucket(flag: string, viewerId: string): number {
56 const h = sha256(`${flag}\0${viewerId}`);
57 return Number.parseInt(h.slice(0, 8), 16) % 100;
58 }
59
60 /** Pure: which variant `viewer` sees under `rules`. No viewer sees only forge rules. */
61 export function resolve(
62 decl: FlagDecl,
63 rules: readonly Rule[],
64 viewer: Viewer | undefined,
65 ): string {
66 if (viewer !== undefined) {
67 const user = rules.find((r) => r.scope === "user" && r.subject === viewer.id);
68 if (user) return user.value;
69 const role = rules.find((r) => r.scope === "role" && r.subject === viewer.role);
70 if (role) return role.value;
71 const b = bucket(decl.name, viewer.id);
72 let from = 0;
73 for (const r of rules) {
74 if (r.scope !== "percent") continue;
75 if (b >= from && b < from + r.pct) return r.value;
76 from += r.pct;
77 }
78 }
79 return rules.find((r) => r.scope === "forge")?.value ?? decl.default;
80 }
81
82 // ---- the snapshot ------------------------------------------------------
83
84 const REFRESH_MS = 3_000;
85 const FLUSH_MS = 5_000;
86
87 interface Cache {
88 at: number;
89 rules: Map<string, Rule[]>;
90 }
91 const caches = new WeakMap<Database, Cache>();
92
93 function snapshot(db: Database, now = Date.now()): Map<string, Rule[]> {
94 const hit = caches.get(db);
95 if (hit && now - hit.at < REFRESH_MS) return hit.rules;
96 const rules = new Map<string, Rule[]>();
97 const rows = db
98 .query<
99 { flag: string; scope: RuleScope; subject: string; value: string; pct: number },
100 []
101 >("SELECT flag, scope, subject, value, pct FROM flag_rule ORDER BY rowid")
102 .all();
103 for (const r of rows) {
104 const list = rules.get(r.flag) ?? [];
105 list.push(r);
106 rules.set(r.flag, list);
107 }
108 caches.set(db, { at: now, rules });
109 return rules;
110 }
111
112 const forgetSnapshot = (db: Database): void => void caches.delete(db);
113
114 export function rulesOf(db: Database, flag: string): readonly Rule[] {
115 return snapshot(db).get(flag) ?? [];
116 }
117
118 // ---- reading -----------------------------------------------------------
119
120 interface Reader {
121 readonly app: { readonly db: Database };
122 readonly auth: {
123 readonly user: { id: string; isAdmin: boolean; kind: string } | undefined;
124 };
125 readonly request?: Request;
126 }
127
128 const pending = new WeakMap<Database, Map<string, number>>();
129 const timers = new WeakMap<Database, ReturnType<typeof setTimeout>>();
130 const seen = new WeakMap<Request, Set<string>>();
131
132 const day = (at: number): string => new Date(at).toISOString().slice(0, 10);
133
134 /**
135 * The variant this request runs under, counted once per request per flag.
136 * An undeclared name is a defect — and the gate finds it before it ships.
137 */
138 export function flag(ctx: Reader, name: string): string {
139 const decl = declared(name);
140 if (decl === undefined) defect("flag.undeclared", `flag "${name}" is not declared in core/flag_decls.ts`);
141 const db = ctx.app.db;
142 const variant = resolve(decl, rulesOf(db, name), viewerOf(ctx.auth.user));
143 const req = ctx.request;
144 if (req !== undefined) {
145 const s = seen.get(req) ?? new Set<string>();
146 seen.set(req, s);
147 if (s.has(name)) return variant;
148 s.add(name);
149 }
150 countUse(db, name, variant);
151 return variant;
152 }
153
154 export function countUse(db: Database, name: string, variant: string, now = Date.now()): void {
155 const map = pending.get(db) ?? new Map<string, number>();
156 pending.set(db, map);
157 const key = `${name}\0${variant}\0${day(now)}`;
158 map.set(key, (map.get(key) ?? 0) + 1);
159 if (!timers.has(db)) {
160 const t = setTimeout(() => flushUse(db), FLUSH_MS);
161 (t as { unref?: () => void }).unref?.();
162 timers.set(db, t);
163 }
164 }
165
166 export function flushUse(db: Database): void {
167 const t = timers.get(db);
168 if (t) clearTimeout(t);
169 timers.delete(db);
170 const map = pending.get(db);
171 if (!map || map.size === 0) return;
172 pending.delete(db);
173 try {
174 const up = db.query(
175 `INSERT INTO flag_use (flag, variant, day, n) VALUES (?1, ?2, ?3, ?4)
176 ON CONFLICT (flag, variant, day) DO UPDATE SET n = n + excluded.n`,
177 );
178 db.transaction(() => {
179 for (const [key, n] of map) {
180 const [f, v, d] = key.split("\0");
181 up.run(f!, v!, d!, n);
182 }
183 })();
184 } catch {
185 // The database closed under a pending batch (shutdown): a lost count,
186 // never a failed request.
187 }
188 }
189
190 // ---- writing -----------------------------------------------------------
191
192 export type RuleInput = {
193 flag: string;
194 scope: string;
195 subject: string;
196 value: string;
197 pct: number;
198 };
199
200 /** Validate and store a rule; one per (flag, scope, subject), the latest wins. */
201 export function setRule(db: Database, input: RuleInput): string | undefined {
202 const decl = declared(input.flag);
203 if (decl === undefined) return "That flag is not declared in the code.";
204 if (!decl.variants.includes(input.value)) return "That is not one of the flag's variants.";
205 const scope = input.scope as RuleScope;
206 if (!RULE_SCOPES.includes(scope)) return "Unknown scope.";
207 let subject = input.subject.trim();
208 let pct = 0;
209 if (scope === "user") {
210 if (!/^[A-Za-z0-9_-]{1,64}$/.test(subject)) return "A user rule needs a user id.";
211 const exists = db.query("SELECT 1 FROM user WHERE id = ?1 OR username = ?1").get(subject);
212 if (!exists) return "No such user.";
213 subject = (db.query<{ id: string }, [string]>("SELECT id FROM user WHERE id = ?1 OR username = ?1").get(subject))!.id;
214 } else if (scope === "role") {
215 if (!ROLES.includes(subject)) return "Role must be admin, agent or member.";
216 } else {
217 subject = "";
218 }
219 if (scope === "percent") {
220 if (!Number.isInteger(input.pct) || input.pct < 1 || input.pct > 100)
221 return "A percentage is a whole number from 1 to 100.";
222 pct = input.pct;
223 const others = rulesOf(db, input.flag)
224 .filter((r) => r.scope === "percent" && r.value !== input.value)
225 .reduce((a, r) => a + r.pct, 0);
226 if (others + pct > 100) return "Percentages for one flag may total at most 100.";
227 }
228 db.query(
229 `INSERT INTO flag_rule (flag, scope, subject, value, pct) VALUES (?1, ?2, ?3, ?4, ?5)
230 ON CONFLICT (flag, scope, subject, value) DO UPDATE SET pct = excluded.pct`,
231 ).run(input.flag, scope, scope === "percent" ? input.value : subject, input.value, pct);
232 forgetSnapshot(db);
233 return undefined;
234 }
235
236 export function clearRule(db: Database, flag: string, scope: string, subject: string): void {
237 db.query("DELETE FROM flag_rule WHERE flag = ?1 AND scope = ?2 AND subject = ?3").run(flag, scope, subject);
238 forgetSnapshot(db);
239 }
240
241 /** The winner becomes everyone's value: every other rule goes, one forge rule stays. */
242 export function crownWinner(db: Database, flagName: string, winner: string): string | undefined {
243 const decl = declared(flagName);
244 if (decl === undefined) return "That flag is not declared in the code.";
245 if (!decl.variants.includes(winner)) return "That is not one of the flag's variants.";
246 db.transaction(() => {
247 db.query("DELETE FROM flag_rule WHERE flag = ?1").run(flagName);
248 db.query(
249 "INSERT INTO flag_rule (flag, scope, subject, value, pct) VALUES (?1, 'forge', '', ?2, 0)",
250 ).run(flagName, winner);
251 })();
252 forgetSnapshot(db);
253 return undefined;
254 }
255
256 // ---- the read-out ------------------------------------------------------
257
258 export interface Readout {
259 readonly variant: string;
260 readonly d7: number;
261 readonly d30: number;
262 }
263
264 export function readout(db: Database, name: string, now = Date.now()): Readout[] {
265 flushUse(db);
266 const decl = declared(name);
267 const since = (days: number): string => day(now - (days - 1) * 86_400_000);
268 const sum = (variant: string, days: number): number =>
269 db
270 .query<{ n: number | null }, [string, string, string]>(
271 "SELECT SUM(n) AS n FROM flag_use WHERE flag = ?1 AND variant = ?2 AND day >= ?3",
272 )
273 .get(name, variant, since(days))?.n ?? 0;
274 return (decl?.variants ?? []).map((variant) => ({
275 variant,
276 d7: sum(variant, 7),
277 d30: sum(variant, 30),
278 }));
279 }
280
281 export { FLAG_NAME };
src/core/schema.ts +20
@@ -1578,6 +1578,26 @@ export const migrations: readonly string[] = [
15781578 expires_at TEXT NOT NULL
15791579 );
15801580 `,
1581 // 74 — feature flags with live A/B (#1137): the values an admin sets, and
1582 // a count of each variant that ran, per day. Config and measurement, not
1583 // truth: losing the tables returns every flag to its declared default.
1584 `
1585 CREATE TABLE flag_rule (
1586 flag TEXT NOT NULL,
1587 scope TEXT NOT NULL CHECK (scope IN ('forge','user','role','percent')),
1588 subject TEXT NOT NULL DEFAULT '',
1589 value TEXT NOT NULL,
1590 pct INTEGER NOT NULL DEFAULT 0,
1591 PRIMARY KEY (flag, scope, subject, value)
1592 );
1593 CREATE TABLE flag_use (
1594 flag TEXT NOT NULL,
1595 variant TEXT NOT NULL,
1596 day TEXT NOT NULL,
1597 n INTEGER NOT NULL DEFAULT 0,
1598 PRIMARY KEY (flag, variant, day)
1599 );
1600 `,
15811601 ];
15821602
15831603 /**
src/http/server.ts +10
@@ -96,6 +96,12 @@ import {
9696 backupsPage,
9797 backupsTest,
9898 } from "../web/pages/backups.ts";
99 import {
100 flagsClear,
101 flagsPage,
102 flagsSet,
103 flagsWinner,
104 } from "../web/pages/flags.ts";
99105 import {
100106 cloudAdd,
101107 cloudAudit,
@@ -652,6 +658,10 @@ export function buildRouter(): Router<Handler> {
652658 router.add("POST", "/settings/cloud/remove", cloudRemove);
653659 router.add("GET", "/settings/capacity", capacityPage);
654660 router.add("POST", "/settings/capacity", capacitySet);
661 router.add("GET", "/settings/flags", flagsPage);
662 router.add("POST", "/settings/flags/set", flagsSet);
663 router.add("POST", "/settings/flags/clear", flagsClear);
664 router.add("POST", "/settings/flags/winner", flagsWinner);
655665 router.add("GET", "/settings/backups", backupsPage);
656666 router.add("POST", "/settings/backups/now", backupsNow);
657667 router.add("POST", "/settings/backups/destination", backupsDestination);
src/web/layout.ts +7 −1
@@ -14,6 +14,7 @@ import type { User } from "../core/users.ts";
1414 import type { Ctx } from "../http/context.ts";
1515 import { edgeLoginUrl, edgeLogoutUrl } from "../http/edge.ts";
1616 import { json } from "../http/respond.ts";
17 import { flag } from "../core/flags.ts";
1718 import { sha256 } from "../kernel/hash.ts";
1819 import { secret } from "../kernel/id.ts";
1920 import { runningLine } from "../kernel/version.ts";
@@ -526,6 +527,7 @@ export function page(options: PageOptions, status = 200): Response {
526527 const nonce = secret();
527528 const { ctx } = options;
528529 const theme = ctx.theme ?? options.theme;
530 const density = flag(ctx, "ui.density");
529531 const flash = readFlash(ctx.request);
530532 const links = pageLinks(ctx);
531533 const scriptJs = options.scriptJs
@@ -551,7 +553,11 @@ export function page(options: PageOptions, status = 200): Response {
551553 ${paletteIndex(ctx, options.palette ?? [])}`;
552554
553555 const doc = html`<!doctype html>
554 <html lang="en" ${theme ? html`data-theme="${theme}"` : null}>
556 <html
557 lang="en"
558 ${theme ? html`data-theme="${theme}"` : null}
559 data-density="${density}"
560 >
555561 <head>
556562 <meta charset="utf-8" />
557563 <meta
src/web/pages/flags.ts added +212
@@ -0,0 +1,212 @@
1 /**
2 * Settings → Flags, for a forge admin: every flag the code declares, its
3 * default and live values, and beside each the use of every variant over the
4 * last 7 and 30 days — the A/B read-out. One form adds a value (the whole
5 * forge, a user, a role, or a percentage of viewers), one button per variant
6 * makes it everyone's and ends the experiment.
7 *
8 * The default lives in code, so crowning a winner cannot edit it: it sets the
9 * forge-wide value, drops every other rule, and says what the retiring pull
10 * must delete.
11 */
12
13 import {
14 FLAGS,
15 type FlagDecl,
16 } from "../../core/flag_decls.ts";
17 import {
18 clearRule,
19 crownWinner,
20 readout,
21 ROLES,
22 rulesOf,
23 setRule,
24 type Rule,
25 } from "../../core/flags.ts";
26 import type { Ctx } from "../../http/context.ts";
27 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
28 import { field, readForm } from "../form.ts";
29 import { html, type Html } from "../html.ts";
30 import { flashTo, page } from "../layout.ts";
31 import { btn, card, icon } from "../ui.ts";
32 import { accountSections } from "./origins.ts";
33
34 function requireAdmin(ctx: Ctx): Response | undefined {
35 if (!ctx.auth.user) return signInFirst(ctx);
36 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
37 return undefined;
38 }
39
40 const describe = (r: Rule): string =>
41 r.scope === "percent"
42 ? `${r.pct}% of viewers`
43 : r.scope === "forge"
44 ? "everyone"
45 : `${r.scope} ${r.subject}`;
46
47 function flagCard(ctx: Ctx, f: FlagDecl): Html {
48 const rules = rulesOf(ctx.app.db, f.name);
49 const out = readout(ctx.app.db, f.name);
50 const hidden = (extra: Html | null = null): Html =>
51 html`<input type="hidden" name="flag" value="${f.name}" />${extra}`;
52 return card(
53 html`<p>${f.why}</p>
54 <p class="muted small">
55 Default <code>${f.default}</code> · owner
56 <span class="mono">#${String(f.owner)}</span>
57 </p>
58 <table class="table" data-flag="${f.name}">
59 <thead>
60 <tr>
61 <th scope="col">Variant</th>
62 <th scope="col" class="num">7 days</th>
63 <th scope="col" class="num">30 days</th>
64 <th scope="col"></th>
65 </tr>
66 </thead>
67 <tbody>
68 ${out.map(
69 (o) =>
70 html`<tr data-variant="${o.variant}">
71 <th scope="row">${o.variant}</th>
72 <td class="num">${String(o.d7)}</td>
73 <td class="num">${String(o.d30)}</td>
74 <td>
75 <form method="post" action="/settings/flags/winner">
76 ${hidden(
77 html`<input type="hidden" name="winner" value="${o.variant}" />`,
78 )}
79 ${btn("Make the winner", {
80 size: "sm",
81 label: `Make ${o.variant} the winner of ${f.name}`,
82 })}
83 </form>
84 </td>
85 </tr>`,
86 )}
87 </tbody>
88 </table>
89 <p class="muted small">
90 Requests that ran under each variant, counted once per request.
91 </p>
92 ${rules.length === 0
93 ? html`<p class="muted">No values set: everyone sees the default.</p>`
94 : html`<ul>
95 ${rules.map(
96 (r) =>
97 html`<li>
98 <code>${r.value}</code> for ${describe(r)}
99 <form method="post" action="/settings/flags/clear" class="inline">
100 ${hidden(
101 html`<input type="hidden" name="scope" value="${r.scope}" /><input
102 type="hidden"
103 name="subject"
104 value="${r.scope === "percent" ? r.value : r.subject}"
105 />`,
106 )}
107 ${btn("Remove", { size: "sm", label: `Remove ${describe(r)}` })}
108 </form>
109 </li>`,
110 )}
111 </ul>`}
112 <form method="post" action="/settings/flags/set" class="row-actions">
113 ${hidden()}
114 <select class="input" name="value" aria-label="Value">
115 ${f.variants.map((v) => html`<option value="${v}">${v}</option>`)}
116 </select>
117 <select class="input" name="scope" aria-label="For">
118 <option value="forge">the whole forge</option>
119 <option value="percent">a percentage of viewers</option>
120 <option value="role">a role</option>
121 <option value="user">a user</option>
122 </select>
123 <input
124 class="input"
125 name="subject"
126 placeholder="username, or ${ROLES.join(" / ")}"
127 aria-label="User or role"
128 maxlength="64"
129 />
130 <input
131 class="input"
132 name="pct"
133 type="number"
134 min="1"
135 max="100"
136 placeholder="%"
137 aria-label="Percent"
138 />
139 ${btn("Set", { variant: "primary", label: `Set a value for ${f.name}` })}
140 </form>`,
141 { head: html`${icon("activity")} <b class="mono">${f.name}</b>` },
142 );
143 }
144
145 export function flagsPage(ctx: Ctx): Response {
146 const denied = requireAdmin(ctx);
147 if (denied) return denied;
148 return page({
149 ctx,
150 title: "Flags",
151 body: html`<div class="page-head"><h1>Flags</h1></div>
152 ${settingsLayout(
153 accountSections("flags", { admin: true }),
154 html`${FLAGS.length === 0
155 ? html`<p class="muted">The code declares no flags.</p>`
156 : FLAGS.map((f) => flagCard(ctx, f))}
157 <p class="muted small">
158 A person always sees the same side: a percentage hashes the flag and
159 the viewer. Order of precedence: user, role, percentage, whole forge,
160 default.
161 </p>`,
162 "Account settings",
163 )}`,
164 });
165 }
166
167 async function admin(ctx: Ctx): Promise<Response | Awaited<ReturnType<typeof readForm>>> {
168 const denied = requireAdmin(ctx);
169 if (denied) return denied;
170 return readForm(ctx, "admin");
171 }
172
173 const back = (ctx: Ctx, message: string, bad = false): Response =>
174 flashTo(ctx, "/settings/flags", bad ? { tone: "danger", message } : { message });
175
176 export async function flagsSet(ctx: Ctx): Promise<Response> {
177 const form = await admin(ctx);
178 if (form instanceof Response) return form;
179 const flag = field(form, "flag");
180 const scope = field(form, "scope");
181 const pct = Number(field(form, "pct"));
182 const error = setRule(ctx.app.db, {
183 flag,
184 scope,
185 subject: field(form, "subject"),
186 value: field(form, "value"),
187 pct: scope === "percent" ? pct : 0,
188 });
189 return error ? back(ctx, error, true) : back(ctx, `${flag} updated.`);
190 }
191
192 export async function flagsClear(ctx: Ctx): Promise<Response> {
193 const form = await admin(ctx);
194 if (form instanceof Response) return form;
195 const flag = field(form, "flag");
196 clearRule(ctx.app.db, flag, field(form, "scope"), field(form, "subject"));
197 return back(ctx, `${flag}: value removed.`);
198 }
199
200 export async function flagsWinner(ctx: Ctx): Promise<Response> {
201 const form = await admin(ctx);
202 if (form instanceof Response) return form;
203 const flag = field(form, "flag");
204 const winner = field(form, "winner");
205 const error = crownWinner(ctx.app.db, flag, winner);
206 return error
207 ? back(ctx, error, true)
208 : back(
209 ctx,
210 `${winner} is now everyone's ${flag}. To retire it, open a pull that makes "${winner}" the default in core/flag_decls.ts, deletes the losing path and removes the flag's declaration.`,
211 );
212 }
src/web/pages/origins.ts +7
@@ -80,6 +80,7 @@ export type AccountSection =
8080 | "backups"
8181 | "secrets"
8282 | "capacity"
83 | "flags"
8384 | "cloud";
8485
8586 /**
@@ -131,6 +132,12 @@ export function accountSections(
131132 icon: "activity" as const,
132133 current: current === "capacity",
133134 },
135 {
136 label: "Flags",
137 href: "/settings/flags",
138 icon: "activity" as const,
139 current: current === "flags",
140 },
134141 {
135142 label: "Backups",
136143 href: "/settings/backups",
src/web/style/components.ts +3
@@ -730,4 +730,7 @@ a.row:hover .row-title { color: var(--accent); }
730730 input, textarea, select, .input, .input[data-size="sm"], .topbar-search input,
731731 .palette .palette-input { font-size: 16px; }
732732 }
733
734 /* ui.density (#1137): the compact side of the experiment. */
735 html[data-density="compact"] .table th, html[data-density="compact"] .table td { padding-block: 4px; }
733736 `;
test/flags.test.ts added +191
@@ -0,0 +1,191 @@
1 /**
2 * Feature flags with live A/B (#1137): the code's declarations are the set
3 * (no debt, no undeclared read), a percentage splits viewers evenly and
4 * stably, and the read-out is the use table.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { flagDebt } from "../scripts/flag-debt.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { FLAGS, type FlagDecl } from "../src/core/flag_decls.ts";
14 import {
15 bucket,
16 clearRule,
17 countUse,
18 crownWinner,
19 flag,
20 flushUse,
21 readout,
22 resolve,
23 setRule,
24 type Rule,
25 } from "../src/core/flags.ts";
26 import { createUser } from "../src/core/users.ts";
27 import { serve, type Servers } from "../src/http/server.ts";
28
29 const decl: FlagDecl = {
30 name: "t.split",
31 why: "test",
32 variants: ["a", "b"],
33 default: "a",
34 owner: 1,
35 };
36 const pct = (value: string, n: number): Rule => ({
37 flag: "t.split",
38 scope: "percent",
39 subject: value,
40 value,
41 pct: n,
42 });
43
44 describe("flag debt", () => {
45 test("the repository declares what it reads and reads what it declares", async () => {
46 expect(await flagDebt()).toEqual({ undeclared: [], unread: [], malformed: [] });
47 });
48 test("an undeclared read and an unread declaration both fail", async () => {
49 const src = new Map([["src/x.ts", `const v = flag(ctx, "nope.nothing");`]]);
50 const d = await flagDebt("", ["old.thing"], src);
51 expect(d.undeclared).toEqual(["nope.nothing"]);
52 expect(d.unread).toEqual(["old.thing"]);
53 });
54 test("reading an undeclared flag at runtime is a defect", () => {
55 const ctx = { app: { db: null as never }, auth: { user: undefined } };
56 expect(() => flag(ctx, "nope.nothing")).toThrow();
57 });
58 });
59
60 describe("percentage", () => {
61 const viewers = Array.from({ length: 1000 }, (_, i) => ({ id: `u${i}`, role: "member" }));
62 test("splits a thousand viewers within tolerance and is stable per viewer", () => {
63 const rules = [pct("b", 30)];
64 const first = viewers.map((v) => resolve(decl, rules, v));
65 const b = first.filter((x) => x === "b").length;
66 expect(b).toBeGreaterThan(300 - 50);
67 expect(b).toBeLessThan(300 + 50);
68 expect(viewers.map((v) => resolve(decl, rules, v))).toEqual(first);
69 expect(bucket("t.split", "u1")).toBe(bucket("t.split", "u1"));
70 });
71 test("user beats role beats percent beats forge beats default", () => {
72 const v = { id: "u1", role: "admin" };
73 const forge: Rule = { flag: "t.split", scope: "forge", subject: "", value: "b", pct: 0 };
74 expect(resolve(decl, [], v)).toBe("a");
75 expect(resolve(decl, [forge], v)).toBe("b");
76 expect(resolve(decl, [forge, pct("a", 100)], v)).toBe("a");
77 const role: Rule = { flag: "t.split", scope: "role", subject: "admin", value: "b", pct: 0 };
78 expect(resolve(decl, [pct("a", 100), role], v)).toBe("b");
79 const user: Rule = { flag: "t.split", scope: "user", subject: "u1", value: "a", pct: 0 };
80 expect(resolve(decl, [role, user], v)).toBe("a");
81 expect(resolve(decl, [forge], undefined)).toBe("b");
82 });
83 });
84
85 describe("the forge", () => {
86 let dir: string;
87 let app: App;
88 let servers: Servers;
89 const name = FLAGS[0]!.name;
90
91 beforeAll(async () => {
92 dir = await mkdtemp(join(tmpdir(), "flags-"));
93 app = createApp({ dataDir: dir, port: 0 });
94 servers = await serve(app);
95 for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) {
96 const made = await createUser(app.db, {
97 trusted: true,
98 username,
99 email: `${username}@forge.local`,
100 password: "correct horse battery",
101 adminIfFirst,
102 });
103 if (!made.ok) throw new Error(made.error);
104 }
105 });
106 afterAll(async () => {
107 servers.stop();
108 app.close();
109 await rm(dir, { recursive: true, force: true });
110 });
111
112 const login = async (username: string): Promise<string> => {
113 const res = await fetch(`${servers.url}/signin`, {
114 method: "POST",
115 redirect: "manual",
116 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
117 body: new URLSearchParams({ username, password: "correct horse battery" }),
118 });
119 return (res.headers.get("set-cookie") ?? "").split(";")[0]!;
120 };
121
122 test("rules are validated at the boundary", () => {
123 const base = { flag: name, scope: "forge", subject: "", value: "compact", pct: 0 };
124 expect(setRule(app.db, { ...base, flag: "no.such" })).toBeString();
125 expect(setRule(app.db, { ...base, value: "huge" })).toBeString();
126 expect(setRule(app.db, { ...base, scope: "galaxy" })).toBeString();
127 expect(setRule(app.db, { ...base, scope: "percent", pct: 101 })).toBeString();
128 expect(setRule(app.db, { ...base, scope: "role", subject: "king" })).toBeString();
129 expect(setRule(app.db, { ...base, scope: "user", subject: "nobody" })).toBeString();
130 });
131
132 test("the read-out counts match the use table, once per request", async () => {
133 const admin = await login("alice");
134 clearRule(app.db, name, "forge", "");
135 expect(setRule(app.db, { flag: name, scope: "role", subject: "admin", value: "compact", pct: 0 })).toBeUndefined();
136 const before = readout(app.db, name);
137 for (let i = 0; i < 3; i++) {
138 const res = await fetch(`${servers.url}/settings/flags`, { headers: { cookie: admin } });
139 expect(res.status).toBe(200);
140 expect(await res.text()).toContain('data-density="compact"');
141 }
142 const anon = await fetch(`${servers.url}/signin`);
143 expect(await anon.text()).toContain('data-density="comfortable"');
144 const after = readout(app.db, name);
145 const n = (r: typeof after, v: string) => r.find((x) => x.variant === v)!;
146 expect(n(after, "compact").d7 - n(before, "compact").d7).toBe(3);
147 expect(n(after, "comfortable").d7 - n(before, "comfortable").d7).toBe(1);
148 // the table itself says the same
149 flushUse(app.db);
150 const row = app.db
151 .query<{ n: number }, [string]>("SELECT SUM(n) AS n FROM flag_use WHERE flag = ?1 AND variant = 'compact'")
152 .get(name)!;
153 expect(row.n).toBe(n(after, "compact").d30);
154 });
155
156 test("old days fall out of the 7-day window but stay in the 30", () => {
157 const now = Date.parse("2026-10-13T12:00:00Z");
158 countUse(app.db, "t.old", "a", now - 10 * 86_400_000);
159 app.db.query("INSERT OR IGNORE INTO flag_use (flag, variant, day, n) VALUES ('ui.density','compact','2020-01-01',9)").run();
160 flushUse(app.db);
161 const r = app.db
162 .query<{ n: number }, []>("SELECT SUM(n) AS n FROM flag_use WHERE flag='t.old'")
163 .get()!;
164 expect(r.n).toBe(1);
165 });
166
167 test("the page is for admins; every mutation is same-origin; a winner replaces all rules", async () => {
168 const admin = await login("alice");
169 const bob = await login("bob");
170 expect((await fetch(`${servers.url}/settings/flags`, { headers: { cookie: bob } })).status).toBe(404);
171 expect((await fetch(`${servers.url}/settings/flags`, { redirect: "manual" })).status).not.toBe(200);
172 const post = (path: string, body: Record<string, string>, cookie = admin, origin = servers.url) =>
173 fetch(`${servers.url}${path}`, {
174 method: "POST",
175 redirect: "manual",
176 headers: { cookie, origin, "content-type": "application/x-www-form-urlencoded" },
177 body: new URLSearchParams(body),
178 });
179 const cross = await post("/settings/flags/winner", { flag: name, winner: "compact" }, admin, "https://evil.example");
180 expect(cross.status).toBeGreaterThanOrEqual(400);
181 const forbidden = await post("/settings/flags/winner", { flag: name, winner: "compact" }, bob);
182 expect(forbidden.status).not.toBe(303);
183 const set = await post("/settings/flags/set", { flag: name, value: "compact", scope: "percent", pct: "40", subject: "" });
184 expect(set.status).toBe(303);
185 const won = await post("/settings/flags/winner", { flag: name, winner: "comfortable" });
186 expect(won.status).toBe(303);
187 const rules = app.db.query("SELECT scope, value FROM flag_rule WHERE flag = ?1").all(name);
188 expect(rules).toEqual([{ scope: "forge", value: "comfortable" }]);
189 expect(crownWinner(app.db, name, "bogus")).toBeString();
190 });
191 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs