Imported as a linear vendor commit so forge rebases do not replay the upstream root tree. git-subtree-dir: third_party/pi git-subtree-split: 71023aec1546d6d677a65669c5665c0927ce0dd0
18 KiB
18 KiB
Changelog
[1.3.0] - 2026-10-15
Breaking Changes
- Terminology follows the concepts: a reference (what
getreturns) isRef<C>(wasHandle<C>), its statusRefStatus(wasHandleStatus); what a factory returns isImplementationOf<C>(wasBehaviorOf<C>); a resource's options are aResourceDeclaration(wasResourceSpec); epochs are code versions:Ctx.codeVersion,RootOptions.codeVersion,Host.codeVersion/previousCodeVersion, and thecodeVersionfields of frames and reload reports (all wereepoch). Docs and messages say object (was record) and reference (was handle and hold); theholdandreleaseframe types keep their names - A remote object's variant is named
variant(waskind): factories return{ variant: "editor", … }, references exposeref.variantandshape.variant, and theshapeframe carriesvariant.variantis reserved as a member name;kindno longer is - Links have a protocol version (
PROTOCOL_VERSION, now 2), announced inhello. Peers of different versions do not talk: the side that notices closes the link with reasonprotocol-version <n>, and both sides report it throughLinkOptions.onProtocolMismatch. Peers without a version (older Chord) are refused serve(…, { lifetime })replaceseager:"referenced"(the default) creates an object at the firstgetof its address and disposes it after the last reference is released (pluslinger);"host"creates the type's one object when its facet loads and keeps it until the host closes or a reload removes its facet.lifetime: "host"is refused atservefor remote types, for inputs that do not accept{}and together withlinger; everygetof such a type reaches its one object, created for the host principal, and another input isinvalid/input.eager: { input }and the extra objects host-principalgets with other inputs created are gone. Only"host"objects may register (reasoninvalid/not_host_lifetime, wasnot_eager).LoadOptions.awaitHostObjectsreplacesawaitEager- Declarations are calls by name:
self.state(name, schema, initial, { version?, migrate? })returns the cell,self.resource(name, { version, deps?, exclusive?, open, close? })the resource (revis nowversion),self.on(name, source, [select,] handler)declares a listener;self.derive(sources, fn)andself.task(fn)take no name.cell(),derivation(),resource(),listener(),self.resources,self.listen,self.tasksand the declaration maps are gone, and so are the typesCellDecl,ResourceDecl,DerivationDecl,ListenerDecl. A repeated name of one kind in a run isinvalid/duplicate - State versions belong to cells:
ServeOptions.stateis gone; a cell'sversion(default 1) andmigrate(old, from)replace it. A raised version migrates only that cell; a lowered one refuses the reload - A derivation is new at every reload (computed at the commit) instead of kept with its function replaced. A listener whose state source a reload replaced subscribes again and gets the current value again: listeners on state must reconcile. Listeners on state subscribe when they activate, so they get the value current then
method(args?, result?): without arguments a method is calledref.name(ctx?)and implemented(ctx) => …; without a result it is void (callers getundefined). Descriptions record both by leavingargs/resultout (fingerprints of such methods change),callframes omitargsandresultframesvaluefor them. Coverage requires both sides to agree on arguments; a void consumer accepts a result- Remote contracts declare where their objects live, and callers no longer name a host:
remote(name, { …, host: hostNamed("server") })orhost: hostFamily("session:", "session")(the hostsession:+ the input's required string fieldsession, checked by TypeScript).hostis required on remote contracts;GetOptions.atis removed. Agetnormalizes the input, resolves the host, and acquires locally or over the link to it.serverefuses a type whose placement does not include the host (also at a reload), a host refuses a hold whose input its own contract places elsewhere (invalid/placement), and a relay refuses a hold whose target disagrees with its contract token. The placement is part of the description and fingerprint; coverage requires equal placements, andacceptsadapters do not bridge placements. Remote references are addressed by type, normalized input and principal, without a host name.PROTOCOL_VERSIONis 3 (remote tokens carryhost; a hold's input is normalized). New exports:hostNamed,hostFamily,Placement,PlacementFor,HostNamed,HostFamily FacetApihas asignal(below): code that builds aFacetApiby hand, for example to wrapserve, must pass it on- Principals are typed and supplied by the app:
createHost<P>,Host<P>,defineFacet<P>,FacetApi<P>,Serve<P>,Factory<C, P>,Self<P>,Ctx<P>,GetOptions<P>,RootOptions<P>,Route<P>,AcceptOptions<P>andPrincipalMatch<P>take the app's principal type (defaultunknown), so factories, methods, listeners and tasks narrow on it without casts. Chord invents no principals any more:createHost({ self })(required) is the principal of the host's own code, replacing the built-inhostPrincipal({ host: true }, removed);connect(link, { principal })(required) is what the parent's own requests act as, replacing{ host: <parent name> };Route.principalis required, replacing the default{ host: <host name> }.HostOptions.upstreamis{ link, principal, ...LinkOptions }(was a link, withupstreamOptions). The host's own principal is recognized byprincipalKey, not object identity. ThePrincipaltype is gone;ConnectOptionsandPrincipalPatternare new serve(type, factory, { lifetime: "host" })compiles only for a local type whose input has no required fields, and withoutlinger;servestill refuses the rest at runtime.ServeOptionsis a union ofReferencedServeOptionsandHostServeOptions, andservetakesServeOptionsFor<C>- An awaited reference has its state, local or remote.
ctx.getandhost.getare async: they resolve once the reference is live and every state member of its variant has its first snapshot, and reject with the activation error,aborted(the ctx aborted or its call settled;host.get'ssignal) orunavailable/ready_timeoutafterHostOptions.readyTimeout(default 60000 ms), releasing only that reference.host.holdis the synchronous form (possiblyloading) for UI runtimes;ref.readystays.self.getstays synchronous: an object goes live only once its references are ready and hydrated, and the state it exposes or derives from (also forwarded from a remote reference held another way) has its values; activation and reload prepare wait at mostreadyTimeout(a reference cycle across hosts fails with a hint instead of hanging) - State members are typed
T(wasT | undefined) andStateSource<T>isReadable<T>. Reading state before the first hydration throwsnot_ready, outside the current variantnot_in_variant, after the reference ended its end error. A remote reference is a union discriminated byvariant: another variant's members are reachable only after narrowing.MembersOfis gone. A listener added before a member is readable gets its snapshot then (noundefinedsnapshot first) - A remote reference stays subscribed to its variant's state while held, with or without listeners (it no longer forgets its value when the last listener leaves).
GetOptions.state: falsemakes a method-only reference: no state unless another reference to the object wants it, ready once live Shape.codeVersionand theshapeframe'scodeVersionare gonePROTOCOL_VERSIONis 4: aholdimplies the state of its variant (state: falseopts out untilsub;unsubstops it); the provider answers with units, ashapelisting the members the consumer lacks (state) followed by their snapshots;stateframes are addressed by hold and member (hold,m) withas: "snap" | "reset" | "ops" | "error"andvalue(absent:undefined);sub/unsubtake a hold;resyncasks for a member again;againmarks a re-hold after a link loss;origin(replacingclient) names the client connection a hold comes from
Added
@earendil-works/chord/output:OutputBuffer, which keeps a head or tail window of a stream at a cost proportional to each chunk,Progress, which paces commits of a changing value by their size, plusboundOutput,sanitizeOutput,characterEnd,utf8ByteLength, and theOutputLimits,BoundedOutput,OutputSlice, andOutputSkiptypes. Moved from@earendil-works/pi-durable, which now uses them from here.- Remote references to one object share one binding per host and key (type, normalized input identity, principal key, contract fingerprint): one hold, one stream per state member, calls over the same hold; every reference keeps its own status, observers and
release.HostOptions.linger({ types: { [typeName]: ms }, cap }, cap default 4) keeps a binding held and hydrated after its last reference is released, so a reference taken again meanwhile costs nothing on the link - Holds from clients carry an opaque
origin: the id the accepting host gave the client connection, forwarded by relays and honored only from the parent link, so a host can tell client connections apart; a disconnect releases that client's holds at once - Flow control by units: the first unit of a new reference passes the window, so a
getnever waits behind other references' state; units for reloads and re-holds wait, built lazily from the current values; waiting ops are capped per link (LinkOptions.pendingCap, default four windows), beyond which the oldest streams become resets (a relay asks downstream withresync) StateOptions,EventOf,ValueOfandLifetimetypesself.state(name, schema, { init }, options?): a cell whose first value comes from its source.init(ctx)(may be async) runs once the object's resources are open and its references live, before the object goes live, so no method, listener, task or subscriber sees another value; a throw or an invalid value fails the activation. A reload keeps the cell without runninginit; a cell a reload adds runs it while the reload prepares (a failure refuses the reload). Until then the cell'svaluethrowsnot_ready.StateInittype- Links are flow controlled end to end: peers acknowledge what they processed (
ackframes, announced withacksinhello), and while a window of frames is unacknowledged (windowinLinkOptions, default 256 KiB), state frames wait at the sender, coalesced per subscription, instead of queuing in front of call results. A stalled peer costs a bounded slot per subscription; a slot that outgrows it becomes a reset. Calls, results and control frames are never held back, so under load a result can arrive before state changes made before it maxCallsinAcceptOptionslimits the calls a peer may have in progress on a link; further ones are answered at once withunavailable(reasontoo_many_calls) and the link stays openFacetApi.signalaborts once that run of the facet is no longer installed: a committed reload replaced or removed it, the reload that loaded it aborted, or the host closed. While a reload prepares, the installed and the candidate run are both liveHostOptions.taskStopDeadline(default 5000 ms) bounds how long a reload waits for aborted tasks before it starts their replacements- Links deflate call arguments, results and state snapshots whose JSON exceeds
PACK_THRESHOLD(64K characters): over IPC as a base64 field, over WebSockets as a binary message. Relaying hosts forward the deflated bytes unread; the host that uses the payload inflates it.webSocketLink(socket, { compress, acceptPacked })(WebSocketLinkOptions) controls sending and accepting packed frames (servers should refuse them from untrusted clients), andinflateMessageturns a packed WebSocket message back into a text frame
Changed
Link.sendreturns the encoded frame's size as sent (deflated payloads count as sent) when the transport knows it (memory and WebSocket links); flow control counts these sizes, so links that return nothing (IPC, custom links) are not windowed- A reload starts an object's new tasks only after its aborted ones finished (at most
taskStopDeadline, then anyway, reported); before, the old and the new run of a task worked side by side - When a reload forces the retirement of the previous code version, it first aborts the roots still running on it (their
ctx.signal, reasonsuperseded) and gives them up to 1 s to stop before it closes what only that code used; a call with such a ctx issuperseded. Before, resources were closed under running roots, which were never told
Fixed
nodeLoaderregisters every facet's directory before importing any, so a facet that imports a file of a facet listed after it gets the same module copy as that facet; before, the load order could produce duplicates.- A link that is already closed when a host accepts or routes to it is no longer kept as a connection: before, a route that returned a dead link (a child process that exited before its link was wrapped) made every later call to that host name fail with
unavailableuntil restart, and leaked the connection's ping timer. - Fixed
processLock()failing withlisten EINVALon macOS and the BSDs when the temporary directory is too deep for a socket path (sun_path holds 104 bytes); the lock socket then lives in a private per-user directory,/tmp/chord2-<uid> - A child host whose hello arrived while a cluster reload ran was marked in step without taking part, so it stayed on the old code version and every call to it failed
supersededuntil it reconnected. It is now synced or reconciled when the reload ends; a child already behind is fenced at once, so its roots' calls up are admitted meanwhile. A reconciliation that is running when a reload starts likewise syncs its child only after that reload, against the committed code version - A child host retired its previous code version as soon as a cluster reload's
preparearrived, before its parent did, so the parent's old roots gotsupersededon it. The coordinator now retires before it sendsprepare, a child waits for its parent'sretire(at mostretireDeadline), and a child coming in step (or about to be reconciled) is told which code versions the parent retired before - Disposed objects stayed reachable from the host until an object with the same address was created again (every distinct guest, session or input leaked one object, its references and the code they bind)
- References kept every code version's services, and with them the factory code of every reload, reachable for as long as they lived (held references, objects of lifetime
"host"); old code generations could never be collected - Call, task and root contexts were linked to long-lived signals with
AbortSignal.any; Node keeps such dependants reachable while they have abort listeners, so a listener onctx.signalkept its closure (and its code generation) alive for the object's lifetime. Contexts now detach when they close - IPC links and the host manager's control channel wrote to a peer process that had exited without a callback, so the
EPIPENode reports for a write in the gap between the exit anddisconnect(anacksent just after a worker shut down) became an unhandlederrorevent that crashed the process. The link now ends on a failed write (reasonipc send failed: EPIPE), and control messages to a gone peer are dropped - A relayed call ran under the origin's cancel signal only, so a forced retirement of the relaying host could not cancel it before closing the old code's resources; it now follows its root's signal
- A resource kept across a reload closed with the
closeof the factory run that first opened it, and kept that run's code reachable; it now adopts the newest declaration at commit forkDriverpassed its ownCHORD2_LOCKto forked children, so a child host that forked its own children made those without a lock of their own fail withlocked- A call through a remote reference accepted a ctx from another host, or an object not made by Chord, and carried its root over the link; it now rejects it with
invalid/foreign_ctxlike a local reference (#10959)
[1.2.0] - 2026-10-12
Breaking Changes
- Replaced the facet and service runtime with a typed host runtime: contracts (
local,remote,method,opaque) are runtime values described with TypeBox schemas, objects are served by hosts (createHost,defineFacet,defineRegistry) and reached through handles, and hosts exchange JSON frames over memory, Node IPC, or WebSocket links (memoryLinkPair,ipcLink,webSocketLink,acceptWebSockets), with hot reload of plugins. Seedocs/tutorial.mdanddocs/guide.md - Removed
defineService,createFacetHost,createRemoteServiceBinding,createStaticFacetLoader,combineFacetLoaders, the remote-service endpoint, provider, error, and wire helpers, and their types. The olddefineFacet,Facet, andFacetLoaderare replaced by the new runtime's names of the same spelling - Removed the
./bundlerexport and the facet bundle loaders of./node;./nodenow exports the child host manager (createHostManager,forkDriver,childControl,processLock) and the facet module loadernodeLoader - Removed
@earendil-works/pi-client,@earendil-works/pi-protocol, and@earendil-works/pi-server, which served only the old runtime; they are no longer released
Changed
replicatedState,copyJson,isJsonValue,Context,JsonValue,JsonRepresentation,Draft, and the replicated state types keep their names on the root export;./contextand./deltaare unchanged, and./contextalso exports theContextandContextKeytypes- Depends on
typeboxinstead ofesbuild
Fixed
- Fixed appending to an array costing a walk over the whole array: the delta tracker now plans inserts and removals that keep the remaining elements in order from the changed ranges alone, and
applyImmutablebuilds an appended array in one copy instead of two. 32,000 one-item appends, one commit each, take 1.4 s instead of 11.3 s