Skip to content

Commit d3cab00

Browse files
committed
Guesses over writables: signals and stores (07 decision 21)
guess x := v is legal on any source: a := signal or store, and a source with a question that is also written plainly. The writable is the truth; an optimistic layer derives from it (createOptimistic(() => truth()), createOptimisticStore(() => truth, seed)). Plain writes go to the truth, guesses to the layer. GUESS_NO_QUESTION is retired. Scenarios S-guess-writable-1..3. The server runtime creates the layer for its owner slot only and renders the truth: Solid's server throws NotReadyError for a projection over a pending store (solidjs/solid#5097, repro in ref/oracle/repros). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0117BoWLtkg281f1NkGEDjCt
1 parent dc74228 commit d3cab00

26 files changed

Lines changed: 300 additions & 141 deletions

‎compiler/src/check.rs‎

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2513,15 +2513,6 @@ impl<'a> Checker<'a> {
25132513
if !ctx.in_action {
25142514
self.err("GUESS_OUTSIDE_HOLD", "AC-3", "a guess outside an action: it needs a hold to live in — an apply block is never an action (its return is the cleanup, EF-5): declare one, `action save(v) { guess … }`, and call it from the block".into());
25152515
}
2516-
if let Some(t) = tsym {
2517-
if self.syms[t].kind == SymKind::Source && !self.syms[t].question {
2518-
self.err(
2519-
"GUESS_NO_QUESTION",
2520-
"AC-3",
2521-
format!("{} is declared with := — a guess needs a question to confirm it (source {} = …, ST-5c)", target.name, target.name),
2522-
);
2523-
}
2524-
}
25252516
}
25262517
for p in &target.path {
25272518
if let PathSeg::Expr(x) = p {

‎compiler/src/emit.rs‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ struct Usage {
9898
optimistic: HashSet<String>,
9999
paths: HashSet<String>,
100100
prev_of: HashSet<String>,
101-
/// plain writes (not guesses): a question source that is guessed by path and written plainly is not lowered yet
101+
/// plain writes (not guesses): a question source that is guessed by path and written plainly lowers to a layer over a writable truth
102102
plain: HashSet<String>,
103103
}
104104
fn usage(programs: &[&Program], extra: &[Vec<Stmt>]) -> Usage {
@@ -1020,16 +1020,17 @@ impl<'p> Gen<'p> {
10201020
match d {
10211021
Decl::Source { name, init, question: false, .. } => {
10221022
let x = self.expr(init, env, &reactive())?;
1023-
let mut out = vec![S::Const(pair(), rtc("source", vec![str(name.clone()), rtc("untrack", vec![thunk(x)])])), self.reg(name, b, true)];
1023+
let mut args = vec![str(name.clone()), rtc("untrack", vec![thunk(x)])];
1024+
if self.u.optimistic.contains(name) {
1025+
args.push(E::Bool(true)); // AC-3: a guess over a writable — an optimistic layer derived from it
1026+
}
1027+
let mut out = vec![S::Const(pair(), rtc("source", args)), self.reg(name, b, true)];
10241028
prev(&mut out);
10251029
Ok(out)
10261030
}
10271031
Decl::Source { name, init, key, .. } => {
1028-
if self.u.optimistic.contains(name) && self.u.paths.contains(name) && self.u.plain.contains(name) {
1029-
return fail(format!("a plain write to {name}, a source with a question that is also guessed by path, is not lowered yet (06 AC-3): guess the server's answer after the `await` instead (`guess {name} := rs => …`, until the re-ask lands), or guess {name} whole (`guess {name} := rs => …`) rather than by path"));
1030-
}
10311032
let lv = self.loading_value(init, env)?;
1032-
let mode = obj(vec![("optimistic", E::Bool(self.u.optimistic.contains(name))), ("structured", E::Bool(self.u.paths.contains(name))), ("record", E::Bool(matches!(init.k, ExprKind::Rec(_))))]);
1033+
let mode = obj(vec![("optimistic", E::Bool(self.u.optimistic.contains(name))), ("structured", E::Bool(self.u.paths.contains(name))), ("record", E::Bool(matches!(init.k, ExprKind::Rec(_)))), ("plain", E::Bool(self.u.plain.contains(name)))]);
10331034
let x = self.expr(init, env, &Ctx { tail: true, self_: Some(name.clone()), ..Ctx::default() })?;
10341035
let mut args = vec![str(name.clone()), arrow(&["__prev"], x), lv, mode];
10351036
if let Some(k) = key {

‎guide/async.md‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ by what the screen should do:
113113

114114
| You want | Write |
115115
| --- | --- |
116-
| Show a value now, and take it back if the action fails | `guess x := v` (x is an equation, `x = …`, or a source with a question, `source x = …`) |
116+
| Show a value now, and take it back if the action fails | `guess x := v` (x is a source or an equation) |
117117
| `pending? x` true while the action runs | `affects x` |
118118
| Land a UI write now and keep it (close a menu, clear a message) | `onFlush(() => { x := v })` (EF-8) |
119119
| Record the server's answer | `x := answer` after the `await` |
@@ -175,8 +175,7 @@ export action rename(id: number, title: string, i: number) { // i: the row's
175175
- **After the `await`, take only what is the server's.** A plain write into an answer after the server answered
176176
takes its answer and the answer's own value at the write (`x := rs => …`, rows found by id), never a row the handler
177177
saw or one read from another source: by then it may have changed, or be held with this write. Pass actions plain
178-
values (ids, titles, indexes), not rows. The compiler flags the rest (`STALE_CAPTURE`, AC-1g). A plain write to a
179-
store that is also guessed by path is not supported yet: re-ask it instead.
178+
values (ids, titles, indexes), not rows. The compiler flags the rest (`STALE_CAPTURE`, AC-1g).
180179
- **A failure is the client's, not a guess.** A guess reverts when its action ends; a failure must outlast it, so it
181180
is a plain source, and a successful retry removes it.
182181
- **Generate ids on the client** in the handler, before calling the action, so a declined add can be shown again

‎guide/diagnostics.md‎

Lines changed: 0 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -493,28 +493,6 @@ export default component App() {
493493
}
494494
```
495495

496-
### GUESS_NO_QUESTION
497-
498-
A guess is confirmed or replaced by the answer to a question, so `guess` writes an equation or a source declared
499-
with `=` (a source with a question, ST-5c). A source seeded with `:=` has no question; write it plainly, or with
500-
`onFlush` if it is a reset that should land now (EF-8).
501-
502-
```rx before
503-
export default component App() {
504-
source shown := "Ann"
505-
action fix() { guess shown := "Zed"; await fetch("x") catch (e) => null }
506-
<button onClick={() => { fix() }}>{shown}</button>
507-
}
508-
```
509-
510-
```rx after
511-
export default component App() {
512-
source shown = await fetch("name") catch (e) => "Ann"
513-
action fix() { guess shown := "Zed"; await fetch("x") catch (e) => null }
514-
<button onClick={() => { fix() }}>{shown}</button>
515-
}
516-
```
517-
518496
### GUESS_ON_DEFERRED
519497

520498
A `deferred` equation is a lagging copy of another value (V-16), so nothing would confirm a guess on it. Guess the

‎guide/language.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ does (`export action select(id) { selected := id }`, or an action passed as a pr
2525

2626
```rx
2727
source count: number := 0 // state; written only with `:=` in imperative code
28-
source user = await fetchUser(id) // state with a question: re-asked when `id` changes, can take a guess
28+
source user = await fetchUser(id) // state with a question: re-asked when `id` changes
2929
double = count * 2 // an equation: always equal to its right side, never written
3030
label = `${user.name} (${count})`
3131
rows key id = items // a keyed collection (rows keep identity by `id`)

‎guide/reference.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,8 @@ Expr ::= TypeScript's, without assignment, `this`, `function`, `new` on rea
5858
- A failure inside the body must be caught there: `try { … } catch (e) { … }` (R-f-6, AC-7). The catch runs inside the
5959
same change: its writes land with the body's end. A rejected body commits its plain writes and reverts its guesses
6060
(AC-1, DV-2).
61-
- `guess x := e`: a guess on an equation (`x = …`) or a source with a question (`source x = …`), shown now, kept until the action's change
62-
commits or `x`'s own answer differs (AC-3, H-11). Guesses on one source hold together.
61+
- `guess x := e`: a guess on a source or an equation, shown now, kept until the action's change commits or `x`'s own
62+
answer differs (AC-3, H-11); on a `:=` source the truth is its plain writes, which land with that change. Guesses on one source hold together.
6363
- `refresh x`: asks `x` again, quietly (no `pending?`; the old value stays up until the new one lands). Inside an
6464
action, the answer lands with the action's commit (AC-4).
6565
- `affects x`: `pending? x` is true until this change commits (AC-5).

‎ref/compile/emit.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -335,10 +335,9 @@ class Gen {
335335
const pad = " ".repeat(ind * 2);
336336
const prev = b.prev ? `\n${pad}const ${b.prev} = __rt.pre(${b.js});` : "";
337337
if (d.k === "source") {
338-
if (!d.question) return `${pad}const [${b.js}, ${b.w}] = __rt.source(${J(d.name)}, __rt.untrack(() => ${this.expr(d.init, env, { imp: false })}));\n${pad}__rt.reg(${J(d.name)}, { get: ${b.js}, w: ${b.w} });${prev}`;
338+
if (!d.question) return `${pad}const [${b.js}, ${b.w}] = __rt.source(${J(d.name)}, __rt.untrack(() => ${this.expr(d.init, env, { imp: false })})${this.u.optimistic.has(d.name) ? ", true" : ""});\n${pad}__rt.reg(${J(d.name)}, { get: ${b.js}, w: ${b.w} });${prev}`;
339339
const lv = this.loadingValue(d.init, env);
340-
if (this.u.optimistic.has(d.name) && this.u.paths.has(d.name) && this.u.plain.has(d.name)) throw new CompileError(`a plain write to ${d.name}, a source with a question that is also guessed by path, is not lowered yet (06 AC-3): guess the server's answer after the \`await\` instead (\`guess ${d.name} := rs => …\`, until the re-ask lands), or guess ${d.name} whole (\`guess ${d.name} := rs => …\`) rather than by path`);
341-
const mode = `{ optimistic: ${this.u.optimistic.has(d.name)}, structured: ${this.u.paths.has(d.name)}, record: ${d.init.k === "rec"} }`;
340+
const mode = `{ optimistic: ${this.u.optimistic.has(d.name)}, structured: ${this.u.paths.has(d.name)}, record: ${d.init.k === "rec"}, plain: ${this.u.plain.has(d.name)} }`;
342341
return `${pad}const [${b.js}, ${b.w}] = __rt.question(${J(d.name)}, (__prev) => ${this.expr(d.init, env, { imp: false, tail: true, self: d.name })}, ${lv}, ${mode}${d.key ? `, ${J(d.key)}` : ""});\n${pad}__rt.reg(${J(d.name)}, { get: ${b.js}, w: ${b.w} });${prev}`;
343342
}
344343
if (d.k !== "eq") throw new CompileError("unreachable");

‎ref/compile/rt-server.ts‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -133,14 +133,16 @@ export function createApp(opts: { api?: Record<string, (...a: any[]) => unknown>
133133
lookup(name: string): Entry { const l = registry.get(name); if (!l?.length) { if (jsErrors.has(name)) return { value: jsErrors.get(name) }; throw new Error(`unbound ${name}`); } return l[l.length - 1]; }, // a server function's request has its module's error classes, not the page's registry
134134

135135
// ---- declarations: the same primitives, from the server build. Writes do not happen on the server (SV-2). ----
136-
source(name: string, init: unknown): [Acc, Writer] {
136+
source(name: string, init: unknown, guessed = false): [Acc, Writer] { // guessed: the client's optimistic layer over the writable (AC-3), so the owner trees (and hydration keys) match
137137
void name;
138-
if (typeof init === "object" && init !== null) { const [store] = createStore(init as any); const [get] = createSignal<unknown>(store); return ro(get as Acc); }
139-
const [get] = createSignal(init); return ro(get as Acc);
138+
if (typeof init === "object" && init !== null) { const [store] = createStore(init as any); const [get] = createSignal<unknown>(store); if (guessed) { const [view] = (createOptimisticStore as any)(() => get(), Array.isArray(init) ? [] : {}); return ro(() => view); } return ro(get as Acc); }
139+
const [get] = createSignal(init); if (guessed) { const [view] = createOptimistic(() => (get as Acc)()); return ro(view as Acc); } return ro(get as Acc);
140140
},
141-
question(name: string, compute: (prev: unknown) => unknown, o: { loadingValue?: unknown } | undefined, mode: { optimistic: boolean; structured: boolean; derived?: boolean; record?: boolean }, key?: string): [Acc, Writer] {
141+
question(name: string, compute: (prev: unknown) => unknown, o: { loadingValue?: unknown } | undefined, mode: { optimistic: boolean; structured: boolean; derived?: boolean; record?: boolean; plain?: boolean }, key?: string): [Acc, Writer] {
142142
const fn = named(name, compute);
143-
if (mode.optimistic && mode.structured) { const [store] = (createOptimisticStore as any)((draft: any) => { const r = fn(draft); if (r instanceof Flight || r instanceof Promise) return (async () => landDraft(draft, r instanceof Flight ? await r.first : await r, key))(); return landDraft(draft, r, key); }, key && !mode.record ? [] : {}, key ? { key } : undefined); return ro(() => store); }
143+
const derive = (draft: any) => { const r = fn(draft); if (r instanceof Flight || r instanceof Promise) return (async () => landDraft(draft, r instanceof Flight ? await r.first : await r, key))(); return landDraft(draft, r, key); };
144+
if (mode.optimistic && mode.structured && mode.plain && !mode.derived) { const [truth] = (createStore as any)(derive, key && !mode.record ? [] : {}, key ? { key } : undefined); (createOptimisticStore as any)(() => (key && !mode.record ? [] : {}), key && !mode.record ? [] : {}, key ? { key } : undefined); return ro(() => truth); } // the client's layer, created for its owner slot only: the server shows the truth (it has no guesses), since Solid's server runs a projection's fn at once and one over a pending store throws NotReadyError out of the component (solidjs/solid#5097)
145+
if (mode.optimistic && mode.structured) { const [store] = (createOptimisticStore as any)(derive, key && !mode.record ? [] : {}, key ? { key } : undefined); return ro(() => store); }
144146
if (mode.optimistic && mode.derived) { const [get] = createOptimistic(fn as any, o as any); return ro(get as Acc); } // AC-3 over an equation: the client's createOptimistic(fn), so the owner trees (and hydration keys) match
145147
if (mode.optimistic) { const [truth] = createSignal(fn as any, o as any); const [get] = createOptimistic(() => (truth as Acc)()); return ro(get as Acc); }
146148
if (mode.structured) {

0 commit comments

Comments
 (0)