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

Experiments on a phone: money first, what bills, the right order #16606

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

sold/experiments-2 → main 0 commits 3 threads · 3 unresolved

  • Merged. sold/experiments-2 was merged into main as 8659798.

Review

Sign in to review this change.
5 files changed +92 −31
docs/features/experiments.md +2 −1
@@ -21,6 +21,7 @@ All three read and write through `src/cloud/experiments.ts`, and only a forge ad
2121 - **Has cost** is each machine's monthly cost now, over its days on the experiment.
2222 - A machine is on one experiment at a time. Attaching it to another closes its time on the first, which keeps what it spent there; attaching it back opens a new stretch.
2323 - Recording a result marks the experiment done and stops its cost counting. Its machines keep costing until they are retired; the row says so.
24 - A pinned forge that costs money and is on no experiment shows as **idle spend**, with Attach and Retire. A retired forge's kept volume counts too.
24 - A pinned forge that costs money and is on no experiment shows as **idle spend**, below the experiments and the New experiment form: its name and monthly cost first, then what bills (`bills`: its machine, or the disk a retired forge kept). A running one offers Attach (or, with no experiment yet, a link to the form) and Retire its machine; a retired one offers Delete its kept disk, through the same confirm that asks for its name.
25 - New experiment's Runs on offers exactly the machines that cost money: the idle ones and those on an experiment now.
2526
2627 Each begin, attach and result is an event (`pinned.experiment_begun`, `pinned.experiment_attached`, `pinned.experiment_result`) naming who did it. Retiring a machine stays on the pinned forge itself.
src/cloud/experiments.ts +3
@@ -39,6 +39,8 @@ export interface Machine {
3939 readonly since: string;
4040 /** When it moved to another experiment; empty while it is still on this one. */
4141 readonly until: string;
42 /** What still bills: its machine, or, once retired, only the data disk it kept. */
43 readonly bills: "machine" | "disk";
4244 }
4345
4446 export interface Experiment {
@@ -97,6 +99,7 @@ export function experiments(db: Database, now = new Date()): Experiments {
9799 monthlyCents: rowCents(p, prices),
98100 since,
99101 until,
102 bills: p.state === "retired" ? "disk" : "machine",
100103 });
101104 const items = db
102105 .query<Row, []>("SELECT id, question, result, started_at, ended_at FROM experiment ORDER BY started_at DESC, id")
src/tui/screens/experiments.ts +2 −2
@@ -90,9 +90,9 @@ export function experimentsScreen(f: Session, ctx: Ctx): Screen {
9090 meta: e.startedAt.slice(0, 10),
9191 })),
9292 ...x.idle.map((m) => ({
93 title: `idle: ${m.name}`,
93 title: `idle: ${m.name} · ${month(m.monthlyCents)}`,
9494 tone: "danger" as const,
95 secondary: `${m.account} · ${m.state} · ${month(m.monthlyCents)} · on no experiment`,
95 secondary: `${m.bills === "disk" ? "retired, disk kept" : m.state} · ${m.account} · on no experiment`,
9696 meta: "",
9797 })),
9898 ];
src/web/pages/pinned.ts +53 −22
@@ -29,12 +29,24 @@ export interface PinnedFacts {
2929 const fact = (label: string, value: Html): Html => html`<div class="status-row"><dt>${label}</dt><dd>${value}</dd></div>`;
3030 const none = (text: string): Html => html`<span class="muted">${text}</span>`;
3131
32 /**
33 * Retire, or delete what a retired forge kept (`act`), through the confirm page, which posts to
34 * `/pinned/<name>/<act>`; a claimed forge's form says the owner means it (`despite_claim`). The
35 * forge's own block and its idle spend row both call this, so the two never drift.
36 */
37 const retireForm = (name: string, act: "retire" | "retire-data", label: string, claimed: boolean): Html => html`<form method="get" action="/-/confirm">
38 <input type="hidden" name="to" value="/pinned/${name}/${act}" />
39 ${claimed ? html`<input type="hidden" name="despite_claim" value="1" />` : null}
40 ${btn(label, { variant: "ghost", label: `${label}: ${name}` })}
41 </form>`;
42
3243 /**
3344 * Update asks for the version, Roll back, Check and New claim link for nothing (a forge deployed
3445 * before forges had names is asked for its hostname); each goes through the confirm page, which
3546 * posts to `/pinned/<name>/<act>`.
3647 */
3748 function actions(p: PinnedView): Html {
49 const retire = (act: "retire" | "retire-data", label: string, claimed: boolean): Html => retireForm(p.name, act, label, claimed);
3850 const to = (act: string): string => `/pinned/${p.name}/${act}`;
3951 const check = html`<form method="get" action="/-/confirm">
4052 <input type="hidden" name="to" value="${to("check")}" />
@@ -44,12 +56,6 @@ function actions(p: PinnedView): Html {
4456 <input type="hidden" name="to" value="${to("file")}" />
4557 ${btn("File in project", { variant: "ghost", label: `File ${p.name} in its cloud project` })}
4658 </form>`;
47 // Retire asks the confirm page; a claimed forge's form says the owner means it (`despite_claim`).
48 const retire = (act: string, label: string, claimed: boolean): Html => html`<form method="get" action="/-/confirm">
49 <input type="hidden" name="to" value="${to(act)}" />
50 ${claimed ? html`<input type="hidden" name="despite_claim" value="1" />` : null}
51 ${btn(label, { variant: "ghost", label: `${label}: ${p.name}` })}
52 </form>`;
5359 if (p.state === "retired")
5460 return html`<div class="form-actions">${p.volume === "" ? null : retire("retire-data", "Delete its kept data", p.claimedAt !== "")}</div>`;
5561 if (p.claimedAt !== "")
@@ -78,7 +84,26 @@ function actions(p: PinnedView): Html {
7884
7985 const month = (cents: number): string => `${dollars(cents)} a month`;
8086 const machineLine = (m: Machine): Html =>
81 html`<a class="mono" href="#forge-${m.name}">${m.name}</a> on ${m.account}, ${m.until === "" ? m.state : "moved on"}, ${month(m.monthlyCents)}`;
87 html`<a class="mono" href="#forge-${m.name}">${m.name}</a> on ${m.account}, ${m.until !== "" ? "moved on" : m.bills === "disk" ? "retired, disk kept" : m.state}, ${month(m.monthlyCents)}`;
88
89 /**
90 * One idle machine: its name and what it costs lead (a row's title is one line, so the money is
91 * never cut off), then what bills, in facts that wrap. A retired one bills for its kept disk, and
outdated

Principle 7 and one-way-to-do-it: this repeats the retire form from actions() (same confirm, same despite_claim hidden input, same btn). Extract that helper to module level and call it here so the two cannot drift.

92 * its action deletes that disk through the forge's own confirm, which asks for the name; a running
93 * one's retires it there, with the same form its own block uses.
94 */
95 function idleRow(m: Machine, running: Experiment[], claimed: boolean): Html {
96 const attach = attachForm(m.name, running) ?? html`<a href="#begin-experiment">Begin an experiment with it</a>`;
97 const end = m.bills === "disk" ? retireForm(m.name, "retire-data", "Delete its kept disk", claimed) : retireForm(m.name, "retire", "Retire its machine", claimed);
outdated

'Retire its machine' is an <a> to #forge-name, not a retire. A person on a phone who taps it lands in a long list and must find the button again. Use the confirm form here (a button that mutates, as DESIGN.md asks), so the row can be finished where it stands, as the kept-disk row can.

98 return row({
99 title: `${m.name} · ${month(m.monthlyCents)}`,
100 data: { bills: m.bills },
101 facts: [
102 { label: "Bills for", value: m.bills === "disk" ? "its kept disk; the machine is retired" : `its machine, ${m.state}` },
103 ],
outdated

Principle 1 and 7: Account duplicates the name's row context and 'Bills for' already carries the cost story. Keep the facts to what the person decides on, or drop Account here since the experiment rows show it in their own line.

104 after: html`<div class="row-fields">${attach} ${end}</div>`,
105 });
106 }
82107
83108 /** A select of the experiments still running, to move machine `name` onto one. */
84109 function attachForm(name: string, running: Experiment[]): Html | null {
@@ -116,24 +141,30 @@ function experimentRow(e: Experiment): Html {
116141 }
117142
118143 /**
119 * Experiments first: what the cloud spend buys, and the machines that buy nothing. The region
144 * Experiments first: what the cloud spend buys, then the machines that buy nothing. The region
120145 * `#experiments` is a live region: the page's shared client (`liveRegionsJs`) swaps it in when
121 * any `pinned.*` event reaches it on /events, so a change from any door shows in place.
146 * any `pinned.*` event reaches it on /events, so a change from any door shows in place. Runs on
147 * offers exactly the machines that cost money: the idle ones and those on an experiment now.
122148 */
123 function experimentsSection(x: Experiments, forges: readonly Pick<PinnedView, "name" | "state">[]): Html {
149 function experimentsSection(x: Experiments, forges: readonly Pick<PinnedView, "name" | "claimedAt">[]): Html {
124150 const running = x.items.filter((e) => e.state === "running");
125 const busy = new Set(x.items.flatMap((e) => e.machines.filter((m) => m.until === "").map((m) => m.name)));
126 const free = forges.filter((p) => p.state !== "retired" && !busy.has(p.name));
127 return html`<section id="experiments" data-experiments data-live="pinned.*">
128 <h2>Experiments</h2>
129 ${x.idle.length === 0 ? null : html`<h3>Idle spend</h3><div data-idle>${rowList(x.idle.map((m) => row({ title: machineLine(m), after: html`${m.state === "retired" ? null : attachForm(m.name, running)} <a href="#forge-${m.name}">Retire</a>` })))}</div>`}
130 ${x.items.length === 0 ? html`<p role="status">No experiment yet.</p>` : rowList(x.items.map(experimentRow))}
131 <form method="post" action="/pinned/experiment/begin" class="stack">
132 ${field({ name: "question", label: "New experiment", required: true, placeholder: "What question does this spend answer?", maxlength: 300 })}
133 ${free.length === 0 ? null : html`<fieldset><legend>Runs on</legend>${free.map((p) => html`<label><input type="checkbox" name="names" value="${p.name}" /> <span class="mono">${p.name}</span></label> `)}</fieldset>`}
134 ${btn("Begin experiment", { variant: "secondary" })}
135 </form>
136 </section>`;
151 const claimed = new Set(forges.filter((p) => p.claimedAt !== "").map((p) => p.name));
152 const spending = [...new Set([...x.idle, ...x.items.flatMap((e) => e.machines.filter((m) => m.until === "" && m.monthlyCents > 0))].map((m) => m.name))];
153 return html`<div id="experiments" data-live="pinned.*">
154 <section class="settings-block" data-experiments>
155 <h2>Experiments</h2>
156 ${x.items.length === 0 ? html`<p role="status">No experiment yet.</p>` : rowList(x.items.map(experimentRow))}
157 <form method="post" action="/pinned/experiment/begin" class="stack" id="begin-experiment">
158 ${field({ name: "question", label: "New experiment", required: true, placeholder: "What question does this spend answer?", maxlength: 300 })}
159 ${spending.length === 0 ? null : html`<fieldset><legend>Runs on</legend>${spending.map((n) => html`<label class="check"><input type="checkbox" name="names" value="${n}" /> <span class="mono">${n}</span></label> `)}</fieldset>`}
160 ${btn("Begin experiment", { variant: "secondary" })}
161 </form>
162 </section>
163 ${x.idle.length === 0 ? null : html`<section class="settings-block" data-idle>
164 <h2>Idle spend</h2>
165 ${rowList(x.idle.map((m) => idleRow(m, running, claimed.has(m.name))))}
166 </section>`}
167 </div>`;
137168 }
138169
139170 function forge(p: PinnedView, f: PinnedFacts): Html {
test/experiments.test.ts +32 −6
@@ -76,6 +76,14 @@ describe("experiments", () => {
7676 );
7777 setRemote(app.db, name, { remote: `d-${name}`, volume: `v-${name}`, state: "running" });
7878 }
79 // test1 was retired and kept its disk, which still bills; canary1 failed and holds nothing.
80 for (const name of ["test1", "canary1"])
81 insertPinned(app.db, {
82 name, target: "digitalocean", account: "main", app: "trevato/forge", source: "https://forge.example.org/trevato/forge",
83 version: "a".repeat(40), config: {}, host: `${name}.forge.test`, claimHash: "", claimExpires: "", datacenter: "nyc3", size: "s-1vcpu-2gb",
84 }, admin.id);
85 setRemote(app.db, "test1", { remote: "", volume: "v-test1", state: "retired" });
86 setRemote(app.db, "canary1", { state: "failed" });
7987 app.bus.subscribe((e) => {
8088 if ((EXPERIMENT_KINDS as readonly string[]).includes(e.kind)) seen.push(e);
8189 }, "local");
@@ -86,12 +94,25 @@ describe("experiments", () => {
8694 await rm(dataDir, { recursive: true, force: true });
8795 });
8896
89 test("two running machines on no experiment are both idle spend", () => {
97 test("what costs money on no experiment is idle spend, each saying what it bills for", () => {
9098 const x = experiments(app.db);
9199 expect(x.items).toEqual([]);
92 expect(x.idle.map((m) => m.name)).toEqual(["friend1", "spare"]);
100 expect(x.idle.map((m) => [m.name, m.bills])).toEqual([["friend1", "machine"], ["spare", "machine"], ["test1", "disk"]]);
93101 expect(x.idle[0]!.monthlyCents).toBeGreaterThan(0);
94 expect(x.monthlyCents).toBe(x.idle[0]!.monthlyCents * 2);
102 expect(x.idle[2]!.monthlyCents).toBeGreaterThan(0);
103 expect(x.monthlyCents).toBe(x.idle.reduce((s, m) => s + m.monthlyCents, 0));
104 // With no experiment, an idle row points at the form; the kept disk's action is the confirm that deletes it.
105 const page = render();
106 const idle = page.slice(page.indexOf("data-idle"));
107 expect(idle).toContain('href="#begin-experiment"');
108 expect(idle).toContain('value="/pinned/test1/retire-data"');
109 expect(idle).toContain("Delete its kept disk");
110 expect(idle).toContain(`test1 · ${dollars(x.idle[2]!.monthlyCents)} a month`);
111 expect(page.indexOf("No experiment yet.")).toBeLessThan(page.indexOf("data-idle"));
112 // Runs on offers what has spend: the disk too, never a failed forge with nothing at the provider.
113 const offered = [...page.matchAll(/name="names" value="([^"]+)"/g)].map((m) => m[1]);
114 expect(offered).toEqual(["friend1", "spare", "test1"]);
115 expect(page).toContain('<label class="check"><input type="checkbox" name="names"');
95116 });
96117
97118 test("the page shows an experiment as one row with its machine and monthly cost, the other machine as idle spend", () => {
@@ -102,7 +123,7 @@ describe("experiments", () => {
102123 expect(e).toMatchObject({ question: "Will a friend claim and use a forge?", state: "running", result: "" });
103124 expect(e.machines.map((m) => [m.name, m.account, m.until])).toEqual([["friend1", "digitalocean/main", ""]]);
104125 expect(e.monthlyCents).toBeGreaterThan(0);
105 expect(x.idle.map((m) => m.name)).toEqual(["spare"]);
126 expect(x.idle.map((m) => m.name)).toEqual(["spare", "test1"]);
106127
107128 const page = render();
108129 expect(page).toContain("the question each one&#39;s spend answers");
@@ -114,7 +135,11 @@ describe("experiments", () => {
114135 const idle = page.slice(page.indexOf("data-idle"), page.indexOf("</ul>", page.indexOf("data-idle")));
115136 expect(idle).toContain("spare");
116137 expect(idle).not.toContain(">friend1<");
117 expect(idle).toContain("Retire");
138 // Retire is the forge block's own confirm form, a button where the row stands, not a jump to the block.
139 expect(idle).toContain('value="/pinned/spare/retire"');
140 expect(idle).toContain("Retire its machine");
141 expect(idle).not.toContain('href="#forge-spare">Retire');
142 expect(idle).not.toContain("<dt>Account</dt>");
118143 expect(page).toContain('action="/pinned/experiment/result"');
119144 });
120145
@@ -169,7 +194,8 @@ describe("experiments", () => {
169194 const begun = await call({ action: "begin", question: "Is a 1 GB machine enough?" });
170195 const id = begun.value.experiment.id as string;
171196 expect((await call({ action: "attach", id, names: ["spare"] })).ok).toBe(true);
172 expect(experiments(app.db).idle).toEqual([]);
197 // What Talk reads: the kept disk is still idle spend, and says it bills for a disk.
198 expect((await call({ action: "list" })).value.idle.map((m: { name: string; bills: string }) => [m.name, m.bills])).toEqual([["test1", "disk"]]);
173199 expect((await call({ action: "record_result", id: "1 GB", result: "Yes." })).ok).toBe(false);
174200 expect((await call({ action: "record_result", id, result: "Yes, under light use." })).value.experiment.state).toBe("done");
175201 expect(["list", "show", "begin", "attach", "record_result"].filter((action) => tool.heldNotWhen?.({ action }) !== true)).toEqual([]);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs