- Go 78.6%
- Shell 21.4%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
|
|
||
| apps | ||
| go | ||
| rows | ||
| .gitignore | ||
| LICENSE | ||
| README.md | ||
Entity Component Runtime
Entity Component Runtime (ECR) is an entity store and runtime for one owner process. Your code never changes state
directly: each system records its writes in a buffer, and a flush turns the buffers into deeds, commits them to an
SQLite file and then applies the committed ones to an in-memory engine, Jacquard, which answers reads. Each entity has
an eid (its id, which names its system and kind). After a restart Open loads every entity of the All kinds (the kinds
the engine holds whole) from the store and brings the engine to the store's seq (the number of the last committed
transaction); an entity of a Touched kind is loaded when the host reads it from the store (see "Reading after a restart"
below). It is for a Go service, the host, that owns its entities in one process; the contract it implements is the KAN
home's specs/ecd_runtime/ecd_runtime.specs.md.
Earlier records and journals call it Ecd Runtime, and before that Ecd Loom; the name changed on 26 Nov 2026.
Install
go get github.com/fiberfx/ecd-runtime/go/ecr@v0.11.0
Go 1.27.4 or later. A host imports one package, github.com/fiberfx/ecd-runtime/go/ecr, and requires one module:
require github.com/fiberfx/ecd-runtime/go/ecr v0.11.0
The facade brings in the main module, the SQLite store and the id package at the versions it was released with.
Quick start
This program defines a catalog with one kind and one component, opens a new store, writes one entity through a system's buffer, flushes, and reads the value back from the engine.
A few words it uses: a Minter mints eids for one lease (the system and writer number that one process mints for);
the 0 in Register(0, "signup") is the system's stage (stages flush in ascending order, and the systems of one stage
in registration order); a kind's Budget is the bytes its entities may hold in the engine.
package main
import (
"context"
"fmt"
"log"
"os"
"path/filepath"
"github.com/fiberfx/ecd-runtime/go/ecr"
)
// The names of the examples: system app, its kind usr (a user) and component handle, 8 bytes. Deeds are of kind ded.
var (
appSys = ecr.MustCode("app")
user = ecr.Kind{System: appSys, Kind: ecr.MustCode("usr")}
appDeed = ecr.MustCode("ded")
)
const handle ecr.CID = 1
// appCatalog declares kind usr, whose entities the engine keeps resident once written, and component handle.
func appCatalog() *ecr.Catalog {
return &ecr.Catalog{
Components: []ecr.ComponentDef{{CID: handle, Name: "handle", Form: ecr.Component, Size: 8}},
Kinds: []ecr.KindDef{{Kind: user, Residency: ecr.Touched, Budget: 1 << 20}},
}
}
// appMinter stands in for the host's Minter: it mints the eids of system app, writer 1, at one fixed time. A real
// host holds one *eid.Minter of its lease, from github.com/fiberfx/ecd-id/go, and passes it in.
type appMinter struct{ count uint32 }
func (m *appMinter) Mint(kind ecr.Code) (ecr.ID, error) {
m.count++
return ecr.FromParts(appSys, kind, 1795271400000, 1, m.count)
}
func main() {
dir, err := os.MkdirTemp("", "ecr-quickstart") // a real host keeps its store at a fixed path
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
ctx := context.Background() // bounds the open and each flush up to its commit
s, err := ecr.CreateStore(ctx, filepath.Join(dir, "app.db"), appCatalog()) // a later start opens it with OpenStore
if err != nil {
log.Fatal(err)
}
h, err := ecr.Open(ctx, ecr.Options{
Store: s,
Catalog: appCatalog(),
Minter: &appMinter{},
DeedKind: appDeed,
})
if err != nil {
log.Fatal(err)
}
defer h.Close()
// A system records its writes in its own buffer.
signup, err := h.Register(0, "signup")
if err != nil {
log.Fatal(err)
}
u := signup.Spawn(user) // a placeholder for the new entity
signup.Set(u, handle, []byte("ada-lace"))
// Flush commits the buffers to the store, then applies what committed to the engine.
res, err := h.Flush(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println("seq", res.Seq, "committed", res.Outcomes[0] == ecr.Committed)
// The flush answers the eid that it minted for the spawn of u. Read its value back from the engine.
id, err := res.Spawned(u)
if err != nil {
log.Fatal(err)
}
v, err := h.Engine().Get(id, handle, nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s %s\n", ecr.KindOf(id).Kind, v)
}
It prints:
seq 1 committed true
usr ada-lace
What a real host does differently:
- The Minter.
appMintermints eids at one fixed time and is not safe across restarts. A real host holds one*eid.Minterfor its lease, fromgithub.com/fiberfx/ecd-id/go(eid.NewMinter(lease, eid.SystemClock{}, eid.ProcessPid{})), and passes it in asOptions.Minter. ecr does not build a Minter and reads no environment. - The store. The store lives at a fixed path.
ecr.CreateStoremakes the file for the catalog, which the store records, and refuses a path at which anything exists, so call it only on the first start andecr.OpenStoreon every later one (see "Starting on a new or an existing store" below for a start function that decides).Opentakes the opened store inOptions.Storeand refuses a catalog whose components differ from the store's record withErrCatalog; theHostowns the store onceOpenreturns, andh.Close()closes it. A store thatOpenrefused stays open: close it. - The goroutine. A
Hostis used on the owner goroutine only. CallFlush(ctx)at your sync points, with no system running. A ctx done before the commit refuses the flush with an error that matchesctx.Err()and keeps every record for the nextFlush; an owner loop that must not be interrupted passescontext.WithoutCancel(ctx). - The reads of the store.
h.Store().View(ctx, f)callsfwith an*ecr.Viewof one read transaction at one seq,v.Seq(); itsRows,Scan,LogandBody, and the generated reads, answer the values at that seq, whatever commits whilefruns.
Every Go block before ## Reference is code from go/ecr/example_test.go, so go test ./...
in go/ecr (row FC-01) runs it and checks its output. The quick start is Example with main renamed; the blocks
below, up to Reference, are the bodies of the Examples they name, one tab less, or a function of that file, but the
blocks that say they are excerpts. The test file passes its package's bg, context.Background(), where a block
writes ctx.
Common tasks
Starting on a new or an existing store
ecr.CreateStore makes the store for the host's catalog and refuses a path at which anything exists, so a host calls
it only when nothing is at the path, and ecr.OpenStore otherwise. Both return the store opened and owned, which the
host passes to Open as Options.Store; Open opens and makes no file. The store records the components of the
catalog it was created with, and Open compares the catalog of Options with that record: a component added,
dropped, resized, renamed, of another form or another pointers flag is refused with ErrCatalog, whose error names
each; a change of the kinds alone, their residency or budgets, or of the queries is admitted. OpenStore never
migrates: a store of user version 2, written before rung 28, is refused with ErrSchema; rebuild it into a new file
(rung 30's Rebuild), and OpenReader still reads it. A store written by go/sqlite v0.4.0 to v0.5.1 has user
version 1, which OpenStore refuses too; bring it to user version 2 with Migrate of go/ecr v0.10.1 first, once;
Migrate is one-way, so copy the file first if you may need to go back.
// start opens the store at path, then the Host over it. The first run makes the file for the catalog; every later run
// opens it as it is, and Open compares the catalog with the store's record.
func start(ctx context.Context, path string, m ecr.Minter) (*ecr.Host, error) {
cat := appCatalog()
open := ecr.OpenStore
if _, err := os.Stat(path); errors.Is(err, fs.ErrNotExist) {
open = func(ctx context.Context, path string) (*ecr.Store, error) { return ecr.CreateStore(ctx, path, cat) }
}
s, err := open(ctx, path)
if err != nil {
return nil, err
}
h, err := ecr.Open(ctx, ecr.Options{Store: s, Catalog: cat, Minter: m, DeedKind: appDeed})
if err != nil {
return nil, errors.Join(err, s.Close()) // a store that Open refused stays open: close it
}
return h, nil
}
This block is an excerpt, which example_test.go does not run; start of apps/chatlog decides the same way, and
its tests run it. An Open whose ctx is done fails with an error that matches ctx.Err(), closes the engine it built
and leaves the store open, so the next Open of the same store succeeds; the caller closes a store it gives up on.
Reading after a restart
Open of an existing store loads every All kind whole, each kind from one read transaction of the store, and brings
the engine to the store's seq. So after a restart a read or a declared query of an All kind answers from the engine,
as the store holds it. Touched kinds start empty, so the first read of their entity answers ErrMiss: read the
entities through with h.Load(ctx, ids...), which groups the eids by kind, reads each kind's rows in one view of the
store at the engine's seq and hydrates them into the engine, after which Get answers from the engine. An eid that the
store does not hold, or holds destroyed, stays a miss. h.Evict(ids...) drops resident Touched entities, which has no
store meaning: the next Get of one answers ErrMiss until Load reads it again.
Load and Evict refuse an eid of an All kind with an error that matches ErrAllKind, and one of a kind that the
catalog does not declare with ErrKind, before any change. Open hydrates every All kind whole, and h.Engine() is an
EngineReader, with no Hydrate, so a host cannot replace an All kind with the rows of some of its entities; it reads
a kind that Open left Cold in a view.
Two cases leave an All kind out of the engine:
- Over budget. An All kind whose stored rows exceed its
Budgetstays Cold:Openreturns the host, andh.Cold()[kind]holds the refusal, which matchesErrBudget. The engine answersErrColdfor that kind, so read it from the store with a view'sRowsorScan. ABudgetof 0 is no limit. - A failed hydration. If the engine panics while it loads a kind, it becomes Stale and
Openfails with an error that matchesErrStale, after closing the engine; the store stays open. CallOpenagain with the store: it builds a new engine.
The rules are in Reference, under "Starting a host".
Attaching trace and span ids
Buffer.SetSpan(trace, span) sets the W3C ids that the buffer's next deed carries, and the store keeps them with the
deed. The zero values mean no trace and no span. The flush that empties the buffer resets them, but a buffer that
records nothing keeps them until its next deed, so a host that traces only some units of work calls SetSpan with the
zero values for the others. ecr.ParseTraceparent(header) returns both ids from a W3C traceparent header,
00-<trace id>-<span id>-<flags>, and refuses a version 00 header with another field count, version ff or an id
that ParseTraceID or ParseSpanID refuses; a higher version reads its first four fields and accepts anything after
a dash that follows the flags, as W3C Trace Context's versioning asks. From Example_span:
dir, err := os.MkdirTemp("", "ecr-span")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
ctx := context.Background()
s, err := ecr.CreateStore(ctx, filepath.Join(dir, "app.db"), appCatalog())
if err != nil {
log.Fatal(err)
}
h, err := ecr.Open(ctx, ecr.Options{Store: s, Catalog: appCatalog(), Minter: &appMinter{}, DeedKind: appDeed})
if err != nil {
log.Fatal(err)
}
defer h.Close()
signup, err := h.Register(0, "signup")
if err != nil {
log.Fatal(err)
}
// The W3C ids of the request that caused the write, as in its traceparent header.
trace, err := ecr.ParseTraceID("4bf92f3577b34da6a3ce929d0e0e4736")
if err != nil {
log.Fatal(err)
}
span, err := ecr.ParseSpanID("00f067aa0ba902b7")
if err != nil {
log.Fatal(err)
}
signup.SetSpan(trace, span) // the next deed of this buffer carries these ids
signup.Set(signup.Spawn(user), handle, []byte("ada-lace"))
if _, err := h.Flush(ctx); err != nil {
log.Fatal(err)
}
// The flush reset the ids, so this deed carries none.
signup.Set(signup.Spawn(user), handle, []byte("bob-byte"))
if _, err := h.Flush(ctx); err != nil {
log.Fatal(err)
}
// The store keeps each deed's ids with it; the zero values mean none. ms is the commit time in Unix milliseconds.
err = h.Store().View(ctx, func(v *ecr.View) error {
return v.Log(0, func(seq uint64, ms int64, d ecr.Deed) error {
fmt.Println(seq, d.TraceID, d.SpanID)
return nil
})
})
if err != nil {
log.Fatal(err)
}
It prints:
1 4bf92f3577b34da6a3ce929d0e0e4736 00f067aa0ba902b7
2 00000000000000000000000000000000 0000000000000000
Testing a host
Package ecrtest gives a host's tests the reference engine, the model: pass ecrtest.NewModel as Options.Engine. A
host never runs the model in production; Open builds Jacquard when Options.Engine is nil, and hydrates the All kinds
into the model as into Jacquard. In a test use t.TempDir() for the directory, or pass mem.New(cat) of
github.com/fiberfx/ecd-runtime/go/store/mem, a store in memory of class D0 that records the catalog cat, as
Options.Store when the test needs no file. From Example_model, which prints the engine is at seq 1:
dir, err := os.MkdirTemp("", "ecr-model") // in a test, t.TempDir()
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
ctx := context.Background()
s, err := ecr.CreateStore(ctx, filepath.Join(dir, "app.db"), appCatalog())
if err != nil {
log.Fatal(err)
}
h, err := ecr.Open(ctx, ecr.Options{Store: s, Catalog: appCatalog(), Minter: &appMinter{}, DeedKind: appDeed,
Engine: ecrtest.NewModel})
if err != nil {
log.Fatal(err)
}
defer h.Close()
signup, err := h.Register(0, "signup")
if err != nil {
log.Fatal(err)
}
signup.Set(signup.Spawn(user), handle, []byte("ada-lace"))
if _, err := h.Flush(ctx); err != nil {
log.Fatal(err)
}
fmt.Println("the engine is at seq", h.Engine().At())
Checking errors
Every sentinel of ecr holds the error of the package that defines it, so errors.Is matches either name.
| Error or outcome | When |
|---|---|
ErrConfig |
Open with no Store, Catalog or Minter, a DeedKind that is not a kind, or an Engine func that returns no engine; Register with an empty or repeated name. Nothing is built, and the store stays open, the caller's to close. |
ErrExist |
CreateStore at a path where anything exists, or where no file is but a -wal or -shm file, which CreateStore never removes. |
ErrHeld |
OpenStore or CreateStore of a store that another owner holds, through an OpenStore or a CreateStore in this process or another; the error names the store, and nothing is opened. The kernel drops the lock on Close, on exit and on a kill, so a standby retries OpenStore. A lock file that cannot be opened for writing is another error, which names it and its cause. |
ErrCatalog |
Open with a catalog whose components differ from those the store was created with: one added, dropped, resized, renamed, of another form or another pointers flag. The error is a *CatalogError, whose Diffs holds each difference and whose text names each component, as component 3 "score" resized 8 to 16. No engine is built, and the store stays open, the caller's to close. A change of the kinds alone, their residency or budgets, or of the queries is admitted. |
ErrSchema |
OpenStore of a file that is not an owner store of the current schema, user version 3: a store of user version 2 is rebuilt into a new file, and OpenReader still reads it (a v0.5.x store needs Migrate of go/ecr v0.10.1 first). OpenReader of a file of neither user version 3 nor 2. |
ErrRef |
Flush of a record that names no entity of its buffer, or of a SetRef whose target is not an entity of its buffer (the zero Ref, a placeholder of another buffer or an earlier flush, an entity that the buffer destroys) or whose component is not eid-typed; the error names the record and the component. Every collected buffer's records are dropped. Also Result.Spawned of a Ref that is not the placeholder of a spawn that the flush committed. |
ErrKind |
Flush of an op on an entity whose kind the catalog does not declare, or a spawn eid of another kind than the spawn's. Nothing is committed, and every collected buffer's records are dropped. |
ErrOp |
Flush of an op the catalog does not allow: an unknown op code, an undeclared CID, a value of the wrong length (a component's value is exactly its Size, a tag's is empty), or ops out of order (an op before the spawn, after the destroy, or a spawn and destroy of one eid in one flush). Nothing is committed, and every collected buffer's records are dropped. The engine's Hydrate answers it for such a stored row. |
ErrMiss |
Engine.Get of an entity of a Touched kind that is not resident, as after a restart. Read it from the store (see "Reading after a restart"). |
ErrCold |
Engine.Get of an entity, or a query, of an All kind that is not hydrated: one that Open left Cold because its rows exceed its Budget or it holds an entity alive with no component value. Read the store. Also h.Cold()[kind] after Open for the second case, naming the entity. |
ErrBudget |
h.Cold()[kind] after Open: the stored rows of that All kind exceed its Budget, so it stays Cold. Open itself returns no error for it. |
ErrStale |
Open when the engine panicked while it loaded an All kind; the engine is closed and the store stays open, and a new Open of it builds a new engine. Also every read, and the error of Flush, once the engine failed in Apply. |
ErrNested |
A View or a Hydrate of the store, or a View of a Reader, from the callback of a View of it, or from another goroutine while such a view runs: the reader is one connection, which the running view holds, so the call answers at once where it would wait forever. Reads one after another in one view are the normal case, and a Body inside a Scan's callback of the same view reads the same transaction. A Commit from a callback succeeds. |
ErrView |
A read of a View after the callback that received it returned. |
ErrBusy |
A View, Commit, Hydrate or open that SQLite answered busy under another connection's lock. It names an error of the store, never one of a callback. |
ErrClosed |
A call of a Store or a Reader after its Close. |
context.Canceled, context.DeadlineExceeded |
Open, CreateStore, OpenStore, OpenReader, View or Flush whose ctx is done. A Flush refused so before its commit keeps every record, Pending names them, and the next Flush commits them; after the commit the flush finishes whatever ctx says. |
ErrSeq |
Store.CommitAt at a seq other than the store's seq plus one; nothing is committed. |
ErrPending |
Host.Close while a buffer holds a record that no Flush has taken, a flush refused by a done ctx among them. The error names each system that Pending() lists with its number of records, and nothing is closed: Flush, or Buffer.Discard each such buffer, then Close again. |
ErrAllKind |
Host.Load or Host.Evict of an eid of an All kind, which Open holds whole; nothing changes. An eid of a kind that the catalog does not declare answers ErrKind. |
ErrOwner |
In a build with the tag ecrdebug (go test -tags ecrdebug, go build -tags ecrdebug), Flush or Register from a goroutine other than the owner, the goroutine of the first Flush; the refused Flush leaves every buffer as it was. Without the tag no check runs. |
Refused, Conflict |
Not errors: Flush returns nil and Result.Outcomes names each deed's outcome. Refused: the store's state does not allow the deed. Conflict: the deed's eid is already committed (a retry). Only Committed deeds reach the engine. |
| An error of the store's transaction | Flush returns an error that wraps rt: commit: and the zero Result; every collected buffer's records are dropped and nothing reaches the engine. The outcome Unknown is answered only by a Committer that reports per deed; on the SQLite store a failed transaction is this error instead. |
From Example_errors:
dir, err := os.MkdirTemp("", "ecr-errors")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "app.db")
ctx := context.Background()
s, err := ecr.CreateStore(ctx, path, appCatalog())
if err != nil {
log.Fatal(err)
}
o := ecr.Options{Store: s, Catalog: appCatalog(), Minter: &appMinter{}, DeedKind: appDeed}
// Options that miss a required field are refused, and the store stays open for the caller.
bad := o
bad.Minter = nil
_, err = ecr.Open(ctx, bad)
fmt.Println("no Minter:", errors.Is(err, ecr.ErrConfig))
h, err := ecr.Open(ctx, o)
if err != nil {
log.Fatal(err)
}
defer h.Close()
// CreateStore refuses a path at which anything exists.
_, err = ecr.CreateStore(ctx, path, appCatalog())
fmt.Println("exists:", errors.Is(err, ecr.ErrExist))
// OpenStore refuses a file that is not an owner store of the current schema.
empty := filepath.Join(dir, "empty.db")
if err := os.WriteFile(empty, nil, 0o600); err != nil {
log.Fatal(err)
}
_, err = ecr.OpenStore(ctx, empty)
fmt.Println("not a store:", errors.Is(err, ecr.ErrSchema))
// A deed that the store does not allow is not an error: its Outcome says so, and nothing is committed.
rename, err := h.Register(0, "rename")
if err != nil {
log.Fatal(err)
}
nobody, err := ecr.FromParts(appSys, user.Kind, 1795271400000, 2, 1) // an eid of no entity
if err != nil {
log.Fatal(err)
}
rename.Set(ecr.Of(nobody), handle, []byte("nobody.."))
res, err := h.Flush(ctx)
fmt.Println("refused:", err == nil && res.Outcomes[0] == ecr.Refused, "seq", res.Seq)
// A record that names no entity refuses the whole flush.
rename.Set(ecr.Of(ecr.ID{}), handle, []byte("nobody.."))
_, err = h.Flush(ctx)
fmt.Println("no entity:", errors.Is(err, ecr.ErrRef))
It prints:
no Minter: true
exists: true
not a store: true
refused: true seq 0
no entity: true
Generating typed handles and queries
A host that does not want to write codes, sizes and byte offsets by hand declares its system in a catalog file and
generates a Go package from it: the kinds, a value type with a codec for each component, a handle for each component
and tag, and the Catalog() that Open takes. In a Go file of the host, write the go:generate line and run
go generate:
//go:generate go run github.com/fiberfx/ecd-runtime/go/cmd/gen -import ecr -in X.catalog.json -out X_gen.go
-import ecr writes the package against package ecr alone, as a host imports it. The repository's own example is
go/ecr/internal/llm. A catalog may mark a component "query": true and may declare queries over kinds and
components. The generator refuses a query that an engine would refuse or that would not compile, with its path and
reason, and writes the same bytes on every run:
{"cid": 2, "name": "turn", "form": "component", "query": true, "doc": "one turn of a conversation", "fields": [
{"name": "seq", "type": "u32"}, {"name": "tokens", "type": "u16"}
]},
"queries": [
{"name": "billed", "kinds": ["cnv", "arc"], "all": ["turn", "usage"], "none": ["pinned"], "doc": "turns with their usage, not pinned"}
]
The marked handle gets Turn.All(e), and each declared query a variable (Billed) with All(e) and a row type
(BilledRow) whose fields are copies of the components of all that hold a value. All runs the query before it
returns, so an error of the engine, ErrCold and ErrQuery among them, comes before any step. It returns an
iter.Seq2 of each entity and its value or row, in the order of the engine's answer:
seq, err := llm.Billed.All(h.Engine())
if err != nil {
log.Fatal(err)
}
for id, v := range seq {
fmt.Println(id, v.Turn.Seq, v.Usage.Cost)
}
A loop body must not write to the host: if the engine moves while the loop runs, or a read fails, the next step panics
with an *IterError that names the query and the seq at which the engine answered. Run the query again after a flush.
Through ecr.Open, every All kind is hydrated, so All over an All kind answers from the host's engine. It answers
ErrCold only for a kind that Open left Cold (h.Cold()). All also runs on an engine that a test hydrates, such as
ecrtest.NewModel (see "Testing a host").
A host loops over the entities of a kind from the owner store with Scan(v, k, after, f) of a marked handle, inside a
view. It reads the store and no engine, so it works while the kind is Cold. It calls f with each entity of the kind
that holds the component and a copy of its value, in eid order, at the view's seq; after resumes a scan after an eid
of the kind, and the zero ecr.ID{} starts at the first. A stored value that does not decode (ErrValue), an error of
the store and an error of f stop the scan and are returned; an error of f comes back unchanged. A commit that lands
while the view is open changes nothing it answers, so a host that builds an index from a scan knows the seq that the
index holds, v.Seq(), the one source of the seq. A View from f answers ErrNested at once:
err := h.Store().View(ctx, func(v *ecr.View) error {
err := llm.Turn.Scan(v, llm.KindCnv, ecr.ID{}, func(id ecr.ID, t llm.TurnValue) error {
index[id] = t.Seq
return nil
})
at = v.Seq() // the seq that index holds
return err
})
if err != nil {
log.Fatal(err)
}
The view is an *ecr.View, the ecd.View over the store's read transaction, which a test builds over its own
ecd.Snapshot with ecd.RunView. These blocks are excerpts: example_test.go does not run them; TestScanHost of
go/ecr/internal/llm runs a scan on a host.
A kind may list its components in the catalog file, each required unless it carries "optional": true:
{"code": "cnv", "residency": "all", "budget": 0, "components": [{"name": "turn"}, {"name": "usage"}, {"name": "parent", "optional": true}]}
The generator then writes CnvEntity, with a field per listed component and a HasParent field per optional one;
SpawnCnv(b, v), which records the spawn and a set of each required component and of each optional one whose Has
field is true; and GetCnv(e, id), which reads the whole entity: false and nil when a required component is absent, an
absent optional one as its zero value with its Has field false, and an error that matches ErrKind for an eid of
another kind. Get<K> reads the engine, which serves an All kind such as cnv after Open; for a kind that Open
left Cold it answers ErrCold, as All does, and a view's Scan reads that kind from the store. A kind with no required
component answers false and nil when it holds none of them.
The generator also writes ReadCnv(v, ids) and ReadCnvOne(v, id), which read whole entities from the store, not the
engine, through an *ecr.View. They serve a kind that the engine holds Cold, a Touched kind after a restart, and a
reader of the store. ReadCnv answers, at the view's seq, a map of each entity that is alive and whole, each optional
component as its Has field; an entity that is not alive, or that lacks a required component, is absent from the map.
An eid of another kind answers ErrKind before any read, and a stored value that does not decode answers ErrValue,
naming the entity and the component. ReadCnvOne answers the entity and true, or false. No generated read returns a
seq: v.Seq() is the one source. The reads of a detached catalog take the system: ReadMsg(v, sys, ids). A body is no
member of a kind; its handle's Get(v, id) reads it in a view, of the host's store (h.Store()) or of a Reader.
TestStoreRead and TestScanSeqHost of go/ecr/internal/llm run these reads on a host:
err := h.Store().View(ctx, func(v *ecr.View) error {
cnvs, err := llm.ReadCnv(v, ids)
if err != nil {
return err
}
for id, c := range cnvs {
fmt.Println(id, c.Turn.Seq, c.HasParent, "at seq", v.Seq())
}
return nil
})
if err != nil {
log.Fatal(err)
}
With -registry DIR, which holds systems.tsv and
kinds.tsv of the ecd-id registry, the generator refuses a catalog whose system is not a live system of the registry or
whose kinds are not live entity kinds of that system, and a detached catalog, with exit 1 and nothing written. The
module github.com/fiberfx/ecd-id/go ships no registry file, so DIR is the registry/ folder of a checkout of
github.com/fiberfx/ecd-id.
Body components
A component value has a fixed size of at most 4096 bytes. A text or a JSON document of any length is a body: a value of
any length up to its cap, which the owner store holds whole and no engine holds. Declare it with the form "body" and,
optionally, a cap in bytes from 1 to 1,048,576; a body that names no cap takes 1 MiB:
{"cid": 2, "name": "lesson_text", "form": "body", "doc": "the text of a lesson"},
{"cid": 3, "name": "figures", "form": "body", "cap": 131072, "doc": "the figures of a lesson, as JSON"}
The generator writes the cap (CapFigures) and a handle whose Set takes a []byte and whose SetString takes a
string, of any length up to the cap. A longer value is refused with an error that matches ErrValue and names the
body, the length and the cap, and nothing is recorded. Get(v, id) reads the value from the store in a view; Has
reads the engine:
b, err := h.Register(0, "lessons")
if err != nil {
log.Fatal(err)
}
r := b.Spawn(lesson.KindEch)
if err := lesson.LessonText.SetString(b, r, text); err != nil {
log.Fatal(err)
}
res, err := h.Flush(ctx)
if err != nil {
log.Fatal(err)
}
id, _ := res.Spawned(r)
var val []byte
var ok bool
err = h.Store().View(ctx, func(v *ecr.View) error {
val, ok, err = lesson.LessonText.Get(v, id) // the whole value, from the store
return err
})
A view's Body(id, c, dst) reads the stored value of any component by entity and CID at the view's seq, as Get
does; the bodies of one entity read in one view are those of one seq.
- A deed that sets bodies and components commits whole, as any deed does. The Runtime refuses a flush whose buffer holds
a body over its cap, set with
Buffer.Setpast the handle, with an error that matchesErrOp, and nothing commits. - An engine keeps a body's presence as it keeps a tag's, never its value:
Hasanswers from the engine,Engine.Getof a body appends no byte, and a body adds nothing toKindStats.Bytes.Openhydrates no body value. - An entity of an All kind that holds only bodies loads, and its kind stays Warm. An entity that holds nothing at all, no component and no body, still leaves its kind Cold.
- A body is no query term and no member of a kind's
components; the generator refuses either, and a"query": trueon a body, with its path and reason. - Each
Setcarries the whole value, so a rewrite adds the whole value to the store's deed log again. A range read, an append and compression are not offered.
The repository's example is go/ecr/internal/lesson, whose kind ech mixes entities with a title and entities with
bodies only. Rows BD-01 to BD-06, in rows/groups/96-bd46.sh, measure bodies.
Modules and versions
| Module | Directory | What it is | Require it when |
|---|---|---|---|
github.com/fiberfx/ecd-runtime/go/ecr |
go/ecr/ |
The facade: ids, seam types, Runtime, store and engine behind one import, plus ecrtest. |
You write a host. This is the one module you need. |
github.com/fiberfx/ecd-runtime/go |
go/ |
The seam package ecd, the runtime rt and the engine Jacquard. No SQLite driver. |
You build a Runtime over your own Committer, or an engine, without the store. |
github.com/fiberfx/ecd-runtime/go/sqlite |
go/sqlite/ |
The owner store in one SQLite file (pure-Go driver modernc.org/sqlite). |
You wire rt and the store yourself. |
github.com/fiberfx/ecd-runtime/go/litestream |
go/litestream/ |
A standard-library client of the control socket of a Litestream v0.5.18 sidecar (GET /info, GET /list, POST /sync with wait); no requirement. |
You run Litestream beside an owner store and confirm that a seq is covered off the host (roadmap M2). |
The current release is v0.11.0 of all four (tags go/v0.11.0, go/sqlite/v0.11.0, go/ecr/v0.11.0, go/litestream/v0.11.0). If you do not use
ecr, upgrade go and go/sqlite together: go/sqlite v0.11.0 requires go v0.11.0.
Migrating to go/v0.11.0
Rung 26 puts every read of a store behind one seam: a store hands a callback a View of one read transaction at one
seq, and every call that opens, reads or commits takes a context. One line per change, old call to new call:
ecr.Open(o)→ecr.Open(ctx, o);ecr.OpenReader(path)→ecr.OpenReader(ctx, path).h.Flush()→h.Flush(ctx); an owner loop that must not be interrupted passescontext.WithoutCancel(ctx).ecr.Migrate(path)andsqlite.Migrate(path)→ deleted: bring a store of user version 1 to 2 withMigrateof v0.10.1 once, before the host runs v0.11.0;OpenStorerefuses it withErrSchema.sqlite.Create(p)thensqlite.Open(p)→sqlite.Create(ctx, p), which returns the store opened and owned;sqlite.Open(p)→sqlite.Open(ctx, p);sqlite.OpenReader(p)→sqlite.OpenReader(ctx, p).s.Log(after, func(seq, d))ands.LogTime(after, func(seq, ms, d))→s.View(ctx, func(v *ecr.View) error { return v.Log(after, func(seq uint64, ms int64, d ecr.Deed) error { ... }) });msis 0 when the store does not know the time.s.Rows(k, ids, func(at, src))→v.Rows(k, ids, func(src))inside a view, withv.Seq()for the seq.s.Scan(k, c, after, func(at, src))→v.Scan(k, c, after, func(src)), with one view around the loop.s.Body(id, c, dst)→v.Body(id, c, dst), which answers([]byte, bool, error)and no seq; the bodies of one entity read in one view are those of one seq.ecr.StoreReader,ecr.Scannerandecr.BodyReader, andecd.StoreReader,ecd.Scannerandecd.BodyReader→*ecr.View(*ecd.View).rt.Outcome,rt.Committed,rt.Conflict,rt.Refusedandrt.Unknown→ecd.Outcomeand its constants, whichecr.Outcome,ecr.Committedand the others alias.Committer.Commit(deeds, out)→Commit(ctx, deeds, out);s.CommitAt(q, deeds, out)→s.CommitAt(ctx, q, deeds, out);s.Hydrate(e, cat)→s.Hydrate(ctx, e, cat).sqlite.ErrExist,sqlite.ErrHeld,sqlite.ErrNestedandsqlite.ErrSeq→store.ErrExist,store.ErrHeld,store.ErrNestedandstore.ErrSeq(ecr.ErrExistand the others now hold those);sqlite.ErrSchemastays.- A store error's
Code() int, read witherrors.As→errors.Is(err, ecr.ErrBusy)for SQLite's busy result. - Generated code: regenerate it with
go/cmd/genat go/v0.11.0,-import ecrkept.ReadK(s, ids)→ReadK(v, ids), which answers the map and no seq;ReadKOne(s, id)→ReadKOne(v, id); a handle'sScan(s, k, after, f)andScanAt(s, k, after, f)→Scan(v, k, after, f); a body'sGet(s, id)→Get(v, id).v.Seq()is the one source of the seq. inspect.Read(r, cat, id, body)on a*sqlite.Reader→inspect.Read(ctx, r, cat, id, body)on anystore.Viewer.
Rung 29 makes the host take any store: Open takes an opened, owned store in Options.Store and opens no file, and
Host keeps its fields unexported behind methods (Path and Create are gone, with no form kept beside Store):
Options{Path: p, Create: true}→s, err := ecr.CreateStore(ctx, p)thenOptions{Store: s}.Options{Path: p}→s, err := ecr.OpenStore(ctx, p)thenOptions{Store: s}; a store in memory isOptions{Store: mem.New()}, fromgithub.com/fiberfx/ecd-runtime/go/store/mem.h.Store.View→h.Store().View;h.Engine→h.Engine();h.Cold→h.Cold(), a map the caller must not change.- A store refused by
Openstays open: close it. AHostfromOpenowns its store, andh.Close()closes it.
Rung 28 gives every store the record of the catalog it was created with, and Open compares the host's catalog with
it:
ecr.CreateStore(ctx, p)→ecr.CreateStore(ctx, p, cat);sqlite.Create(ctx, p)→sqlite.Create(ctx, p, cat);mem.New()→mem.New(cat). No store is made without its catalog.Openrefuses a catalog whose components differ from the store's record (ErrCatalognames each), an added one included; a change of the kinds alone, their residency or budgets, or of the queries is admitted.- A store of user_version 2 is refused by
Open: rebuild it into a new file (rung 30's Rebuild);OpenReaderstill reads it. Keep the version 2 file until the rebuild has finished, and never write it.
Rung 30 gives every store the forward path, a rebuild from a deed log:
s.CommitAt(ctx, q, deeds, out)→s.CommitAt(ctx, q, ms, deeds, out): the commit time in Unix milliseconds, 0 for now; a replay keeps every known time.- A store's own rebuild (the learning system's
store/rebuild.go) →ecr.Rebuild(ctx, path, cat, src, from, drops), whosesrcis anecr.DeedSource(a view'sLog, or a shipped target adapted to it with ms 0); a missing seq answersErrSeq. - A store of user_version 2:
r, _ := ecr.OpenReader(ctx, old);r.View(ctx, func(v *ecr.View) error { _, err := ecr.Rebuild(ctx, new, cat, v.Log, ecr.Identity{}, nil); return err }); then swap the files. A version 3 source passes its identity (r.Identity()), so the rebuilt store keeps its store id with a new lineage. store.Rebuild(ctx, src, dst, drops)replays into any store that hasCommitAt, an in-memory one included.
Rung 31 narrows the host's engine to its read side and gives the host its read-through:
h.Engine()returns anecr.EngineReader(At,State,Get,Query,Stats), not anecr.Engine: a function that takes the host's engine takesecr.EngineReader, asfunc whole(en ecr.Engine, id eid.ID)→func whole(en ecr.EngineReader, id eid.ID); its callers passh.Engine().- A read-through of Touched entities,
h.Store().Viewwithv.Rows(k, ids, func(src) error { return h.Engine().Hydrate(k, v.Seq(), src) })(or v0.10.1'sh.Store.Rows(k, ids, func(at, src) error { return h.Engine.Hydrate(k, at, src) })), →h.Load(ctx, ids...). - An eviction, a map of eids by kind and
h.Engine.Evict(k, ids)for each →h.Evict(ids...). buf.Span(trace, span)→buf.SetSpan(trace, span).h.Pending()answered an error → it answers[]ecr.Held{{System, Records}}in flush order, nil when none;h.Close()still answers an error that matchesErrPendingand names each system.h.Engine().Name()→ gone from the host's engine; the name of the engine is theEnginefunc's choice.- An All kind that holds an entity with no component value is Warm, no longer Cold with
ErrCold(S4): the entity hydrates as a presence row and aGetof it answersErrAbsent;Host.Cold()holds onlyErrBudgetrefusals.
Reference
The sections below are the detailed rules of each package, as before this README was reorganised.
Entity Component Runtime is the entity store and runtime of an owner process. Callers change state only through deeds,
which are committed through the Committer interface of package rt, and engines answer reads from memory. The owner
store is the nested module go/sqlite, an SQLite file that a host passes in through rt.Config.Committer. Jacquard is
the archetype engine.
The contract is the KAN home's specs/ecd_runtime/ecd_runtime.specs.md. This repository holds the implementation.
Layout
| Path | Content |
|---|---|
go/ |
The Go module github.com/fiberfx/ecd-runtime/go. |
go/engine/jacquard/ |
Jacquard, the archetype engine. Its files that port Ark files name their source file in their header. |
go/rt/ |
The package rt: a command buffer per system and the flush that commits and applies their deeds. |
go/sqlite/ |
The nested Go module github.com/fiberfx/ecd-runtime/go/sqlite: the owner store in one SQLite file, an implementation of rt.Committer that also hydrates an engine. |
go/ecr/ |
The nested Go module github.com/fiberfx/ecd-runtime/go/ecr: the facade package ecr, one import and one requirement for a host. |
go/enginecmp/gj/ |
Benchmarks of Jacquard against Ark in module go/enginecmp; rows/gj.bench.rows.sh runs them. |
go/NOTICE.txt |
Every part taken from another project: the project, its source, commit, licence and copyright line, what is taken and the files that hold it, with the licence text that the project's licence requires, and the projects whose design Entity Component Runtime follows. |
rows/loom.rows.sh |
The rows script. |
git diff --no-index between a ported file in go/engine/jacquard/ and its source file in a checkout of Ark at commit 723f2ac records the adaptation.
Runtime
The package rt, import path github.com/fiberfx/ecd-runtime/go/rt, is the write side of the owner process. A system
records its writes in a buffer and does not touch an engine. The host registers the systems and calls Flush, which
turns the buffers into deeds, commits them in the owner store and applies the committed ones to the engine. The package
imports the standard library, github.com/fiberfx/ecd-id/go and github.com/fiberfx/ecd-runtime/go/ecd only.
What the package gives
New(Config)returns theRuntime.ConfigholdsCatalog,Engine,Minter,CommitterandDeedKind, and every field is required.Newrefuses a nilCatalog,Engine,MinterorCommitter, and aDeedKindfor whichIsKind()is false, with an error that matchesErrConfig. It reads no environment variable and builds noMinter: the host passes the oneMinterof its lease.Runtime.Register(stage, name)returns theBufferof a new system. It refuses an empty name and a name registered before, with an error that matchesErrConfig. A stage is anyint; stages flush in ascending order.Buffer.Spawn,Buffer.Set,Buffer.UnsetandBuffer.Destroyrecord a write, andBuffer.Lenis the number of records.Setrecords a copy of its value. No record method returns an error, mints an eid or touches an engine.Buffer.SetRef(e, c, target)records a set of the eid-typed componentcofeto the eid oftarget: an entity that exists, byOf, or the placeholder of a spawn of the same buffer since its last flush, whose eid the flush writes once it has minted it. So a course and the lessons that name it commit in one deed, all or nothing. A component is eid-typed when the catalog declares it a component or an edge ofSize16 with no pointers; the catalog keeps no field types, so 16 plain bytes pass as well. A target that is the zeroRef, a placeholder of another buffer or of an earlier flush, or an entity that aDestroyof the same buffer names, and a component that is not eid-typed, refuse the flush withErrRef, naming the record and the component.Buffer.Discarddrops the buffer's records as a flush that empties it does, and commits nothing: its placeholders are refused afterwards, and its trace id and span id reset.Runtime.Pending()returns aHeldfor each buffer that holds a record, in flush order, with its system's name and its number of records, and nil when none does;Host.Closebuilds itsErrPendingerror from it.Buffer.SetSpan(t, s)sets the trace id and span id that the buffer's next deed carries, and the flush that empties the buffer resets them; a buffer that records nothing keeps them until its next deed, so a host that traces only some units of work callsSetSpanwith the zero values for the others.Refnames the entity of a record.Of(id)is theRefof an entity that exists, by its eid.Spawnreturns a placeholderRef, valid in the buffer that issued it until the next flush of that buffer.Runtime.Flush(ctx)runs the flush and returns aResult:Seq, the seq of the committed transaction, or 0 when no deed was committed;Deeds, the eid of each deed in ord order;Outcomes, theecd.Outcomeof each deed in ord order; andCommitted, the deeds answeredCommittedwith their ord, ids and ops, which is what a view'sLogof the SQLite store returns forSeq, so a host needs noLogafter a flush; it holds no other deed, and is nil whenSeqis 0.Result.Spawned(ref)answers the eid that the flush minted for the spawn whose placeholder isref, when its deed was answeredCommitted, and an error that matchesErrReffor every otherRef.Committeris the owner store as the flush sees it.Commit(ctx, deeds, out)commits the deeds of one flush in one store transaction, writes oneecd.Outcomeper deed intooutand returns the seq of the transaction. The outcomes areecd.Committed,ecd.Conflict,ecd.Refusedandecd.Unknown; only a deed answeredCommittedreaches the engine.ErrConfigis matched by every error ofNewandRegister.ErrRefis matched by a flush refused because a record names no entity of its buffer, and byResult.Spawnedof aRefthat it does not answer.- The owner check: in a build with the tag
ecrdebug, the goroutine of the firstFlushowns theRuntime, and aFlushor aRegisterfrom any other goroutine answers an error that matchesecd.ErrOwner, with every buffer as it was. Before the firstFlushany goroutine registers. A host enables it with-tags ecrdebugongo testorgo build; without the tag no check runs and it costs nothing. The record methods of aBufferare not checked. The check tells goroutines apart, not overlapping calls: aRuntimehanded on to another goroutine after its firstFlushanswersErrOwnerthere, and so does aFlushin a subtest (t.Run) after its test flushed.
The order of a flush
Flush runs on the owner goroutine with no system running, and takes these steps in this order.
- Collect the buffers that hold a record, in flush order: stage ascending, then registration order within a stage.
With none,
Flushreturns an emptyResultand a nil error, and mints, commits and applies nothing. - Resolve, before any mint or change: every record names an entity by a non-zero eid, or by a placeholder of its own
buffer issued since that buffer's last flush. Any other
Refrefuses the flush withErrRef. So does aSetRefwhose target is not such an entity, or names one that aDestroyof its buffer names, or whose component is not eid-typed. - Mint from the
Minter, in flush order: for each buffer the eid of its deed, ofConfig.DeedKind, then one eid per spawn in record order. A spawn eid of another kind than the spawn's refuses the flush withecd.ErrKind. - Build one
ecd.Deedper buffer: its ord is the buffer's index among the collected buffers, and its ops follow record order. A spawn is oneOpSpawn, and theSetrecords that name its placeholder follow asOpSetops. The value of aSetRef'sOpSetis the eid of its target: the eid minted in step 3 for a placeholder, so no deed holds a placeholder. - Check the deeds against the catalog. A refusal matches
ecd.ErrKindorecd.ErrOp, and nothing is committed. - Commit the deeds in one call of
Committer.Commitwith the flush's ctx. An error ofCommitis returned, and nothing is applied. - Apply the deeds answered
Committed, with their ord unchanged, in oneApplyof the engine at the seq of the transaction. With none committed there is noApply.
ctx bounds the flush up to the commit. A ctx error seen before step 2 or just before step 6, or an error of Commit
that matches ctx.Err(), returns the zero Result and an error that matches ctx.Err() and names each stage with the
number of records kept: every buffer keeps its records, Pending names them and the next Flush commits them; the
eids minted for them are burnt. Once the store committed, step 7 runs to its end whatever ctx says. An owner loop that
must not be interrupted passes context.WithoutCancel(ctx).
On every other path every buffer collected in step 1 is emptied before Flush returns, and the placeholders issued
before the flush are refused afterwards. A refusal in step 2, 3, 5 or 6 drops the records of every collected buffer; its error
names each stage that held a record with the number of records dropped, and matches what its cause matches. An error of
Apply is returned as the engine gives it, beside the Result, since its deeds are committed. A deed answered
Conflict, Refused or Unknown returns no error; Result.Outcomes names it by its ord.
A buffer with a record is one deed. A spawn and every record that names its placeholder are therefore in one deed and share one outcome, and no deed names an entity spawned by another deed of the same flush. The order of a flush depends only on the stages, the registration order and the record order.
Example
// tick registers one system, records three writes and flushes them. cfg is built by the host. The component pos is
// declared in the catalog with Size 2, so every value that Set records for it holds exactly 2 bytes.
func tick(ctx context.Context, cfg rt.Config, mover ecd.Kind, pos ecd.CID, known eid.ID) (rt.Result, error) {
r, err := rt.New(cfg)
if err != nil {
return rt.Result{}, err // matches rt.ErrConfig
}
buf, err := r.Register(0, "move")
if err != nil {
return rt.Result{}, err // matches rt.ErrConfig
}
e := buf.Spawn(mover) // a placeholder, valid in buf until the next flush
buf.Set(e, pos, []byte{1, 2}) // in the same deed as its spawn
buf.Set(rt.Of(known), pos, []byte{3, 4}) // an entity that exists, by its eid
return r.Flush(ctx) // Result.Outcomes names each deed's Outcome, for example ecd.Committed
}
Limits
- The store is the interface
Committer. Packagertholds no owner store: the modulego/sqliteimplementsCommitter, and the tests of packagertuse a fake. - A record names an entity by its eid or by a placeholder of its own buffer. No hot handle for an entity exists.
- A
SetRefnames a placeholder of its own buffer only: a reference across buffers or flushes is refused, and the flush does not check that an existing eid it names is alive. A retried flush mints anew, so its references resolve to the new eids. - The package runs no scheduler, no parallel stage and no observer. The host calls
Flush(ctx)at its sync points. - After the flush,
Result.Spawned(ref)returns the eid minted for the spawn whose placeholder isrefwhen its deed was answeredCommitted, and refuses any otherRefwithErrRef. - The package does not rebuild a stale engine:
Flushreturns the engine's error. - A deed answered
Conflict,RefusedorUnknownreturns no error, and its records are not listed by stage;Result.Outcomesnames the deed by its ord.
SQLite store
The module github.com/fiberfx/ecd-runtime/go/sqlite, in go/sqlite/, package sqlite, is an owner store in one
SQLite file. A host passes it to the Runtime as rt.Config.Committer, and after a restart it brings a fresh engine to
the seq of the committed history. The module has its own tags, go/sqlite/vX.Y.Z; go/sqlite/v0.4.0 is the first. It
requires github.com/fiberfx/ecd-runtime/go v0.11.0, github.com/fiberfx/ecd-id/go v0.11.0 and the pure-Go driver
modernc.org/sqlite v1.37.0. Inside this repository a replace directive points the requirement on the main module at
the parent directory. The main module go/ does not require the driver.
What the store gives
*Store implements store.Store and store.Importer, and *Reader implements store.Reader, of package store
(github.com/fiberfx/ecd-runtime/go/store), whose sentinels the store's errors match: store.ErrExist,
store.ErrHeld, store.ErrNested, store.ErrSeq, store.ErrClosed and store.ErrBusy. ErrSchema is the store's
own.
-
Create(ctx, path, cat)makes the store file for the catalogcatand returns theStoreopened and owned, asOpenreturns it, with no window between the two in which another owner could open it. It refuses a nil catalog, and one whose record the store cannot hold, before it makes any file. It refuses a path at which anything exists, and a path with no file but a-walor-shmfile, with an error that matchesstore.ErrExistand names the file, and changes nothing. It then takes the store's lock (below), looks again under it, sets the page size to 4096 bytes and auto-vacuum to incremental before the first table, then the journal to WAL, then in one transaction creates the schema, writes the store's identity in_store, each component of the catalog's record inecd_componentand one row ofecd_history, and setsuser_versionto 3, and opens the writer and the reader under the lock it still holds. After a failure it removes the files it made and drops the lock; the lock file stays. -
Open(ctx, path)returns theStore. It never creates the store file: a missing path is an error that makes no file. It takes the store's lock: an exclusiveflockon<path>.lock, beside the store's real path, which it makes, for an existing store, when it is absent. While another owner holds it, throughOpenorCreatein this process or another,Openanswers an error that names the store and matchesstore.ErrHeld, before it opens a connection; a lock file that cannot be opened for writing answers an error that names it and its cause. It refuses a file whoseuser_versionis not 3 or whose journal mode is not WAL, with an error that matchesErrSchema: it never migrates, so a store of user version 2 or 1 is refused too. It reads the store's identity and the catalog's record once and keeps them;Store.Catalog()answers the record andStore.Identity()the identity. It opens one writer connection and one reader connection, and each holds a connection beforeOpenreturns. The lock is held untilClose, and the kernel drops it when the process exits or is killed, so a standby's nextOpensucceeds with no file removed by hand. ctx bounds the open: a ctx done before the store is returned fails it. -
OpenReader(ctx, path)returns aReader: the store opened to read only, beside the owner that holds it, for a standby server or an agent that diagnoses an entity. It takes no lock. Its one connection is opened in moderowithbusy_timeoutof 2000 ms andquery_onlyon, so the database refuses any write through it, and it never creates, repairs or migrates a file: a missing path is an error that makes no file, and a file that is not an owner store of user version 3 or 2 matchesErrSchemaand is left as it is; a store of user version 2 reads as one of version 3. Its methods areView, theStore's, andClose; it has noCommitand noHydrate. AReaderis used by one goroutine at a time; a goroutine that reads concurrently opens its own. -
The writer opens an immediate transaction, with
busy_timeoutof 2000 ms, foreign keys on andsynchronousFULL. The reader hasbusy_timeoutof 2000 ms andquery_onlyon. -
Store.View(ctx, f)callsfonce with an*ecd.Viewof one read transaction on the reader at one seq,v.Seq(), and returnsf's error unchanged, never wrapped. ctx bounds the start of the view; the reads inside it take no context. The view's reads answer the values atv.Seq()whatever the owner commits whilefruns, and aCommitfromfruns on the writer and succeeds:v.Rows(k, ids, f)callsfonce with aRowSourceof the stored values of the entitiesidsof kindk, in eid order and then CID order. The ids may be in any order and may repeat; an eid of another kind is an error beforefis called. An entity that is not alive, or alive with no component value, yields no row.v.Scan(k, c, after, f)callsfonce with the stored values of componentcof the entities of kindkaboveafter, in eid order.v.Log(after, f)callsfwith each committed deed of a seq in(after, v.Seq()], in seq order and then ord order, with its commit time in Unix milliseconds, 0 when the store does not know it; the deeds of one transaction share it. A body that does not decode matchesErrSchema.v.Body(id, c, dst)appends the stored value of componentcof entityidtodst, whole.
A source is valid only until its callback returns, and every callback's error comes back unchanged. Reads one after another in one view are the normal case, and one read may run inside the callback of another, as a
Bodyinside aScan's callback: both read the one transaction. A view is valid only untilfreturns; a read after that answersecd.ErrView. -
Store.Commit(ctx, deeds, out)is thert.Committer. It commits the deeds of one flush in one SQLite transaction and writes oneecd.Outcomeper deed intoout. A ctx done before the transaction commits rolls it back, answers every deedUnknownand returns an error that matchesctx.Err(). -
Store.CommitAt(ctx, seq, ms, deeds, out)commits asCommitdoes, only at the seqseqthe caller expects: a store whose seq plus one is another refuses with an error that matchesstore.ErrSeqand names both seqs, commits nothing and answers every deedUnknown. A replay of a view'sLoginto a new store, oneCommitAtper seq, keeps every eid and seq, and a missing seq stops it instead of shifting every later deed. Its ms is the commit time in Unix milliseconds that the transaction keeps, 0 meaning now, so a replay keeps every known time. -
Store.Hydrate(ctx, e, cat)loads every kind of residencyAllof the catalog into a fresh engine and returns the seq. When the catalog has no All kind and the seq is above 0, it calls the engine'sStartwith the seq. ctx is checked before the transaction begins and between kinds, never inside a kind's rows. -
Store.Class()answersstore.D2: a deed answeredCommittedis synced to the host's storage. -
The reader of a
Storeis one connection, which a view holds while its callback runs. AViewor aHydratefrom that callback answers, at once, an error that names the call and matchesstore.ErrNested; aCommitfrom the callback runs on the writer and succeeds. The same holds for aReader. An error of the store, never of a callback, matchesstore.ErrBusywhen SQLite answered busy. -
Store.Closecloses both connections, then drops the lock, and a secondClosereturns nil; every other call afterCloseanswers an error that matchesstore.ErrClosed. -
ErrSchemais matched by anOpenof a file that is not an owner store of user version 3, anOpenReaderof one of neither user version 3 nor 2, and by a view'sLogthat reads a malformed eid, ord, body, trace id or span id.
A Store is used on the owner goroutine only. The tables are entity (one row per entity, with the seq of its last
change and the seq of its destroy), state (one row per component value of an entity, whatever its kind), deed and
deed_body (the log). The seq of the store is the highest seq of deed, so only a transaction that commits a deed
advances it. The store is at user version 3: version 2's tables, whose deed also holds each deed's trace id and
span id, NULL for the zero values, and _store (the store id and the lineage), ecd_component (the record of the
catalog) and ecd_history. Open refuses a store of user version 2, which is rebuilt into a new file, and of user
version 1, written by go/sqlite/v0.4.0 to go/sqlite/v0.5.1, and never migrates. Migrate of go/sqlite v0.10.1
brings a store of user version 1 to user version 2; v0.11.0 has none.
Starting a host
// start opens the store at path, creating it when the path is absent, brings the fresh engine of cfg to the seq of
// the store and returns the Runtime that commits into it. cfg holds the Catalog, a fresh Engine, the Minter and the
// DeedKind of the host.
func start(ctx context.Context, path string, cfg rt.Config) (*rt.Runtime, *sqlite.Store, error) {
s, err := sqlite.Create(ctx, path, cfg.Catalog) // the new store, opened and owned
if errors.Is(err, store.ErrExist) {
s, err = sqlite.Open(ctx, path) // matches sqlite.ErrSchema when the file is not an owner store
}
if err != nil {
return nil, nil, err
}
if _, err := s.Hydrate(ctx, cfg.Engine, cfg.Catalog); err != nil { // every All kind, read at one seq
s.Close()
return nil, nil, err
}
cfg.Committer = s
r, err := rt.New(cfg) // matches rt.ErrConfig
if err != nil {
s.Close()
return nil, nil, err
}
return r, s, nil
}
After Hydrate the engine is at the seq of the store, and the next flush commits at that seq plus one.
Jacquard serves All kinds (rule E9 of the contract), so start passes Hydrate the whole catalog, which loads every
All kind from one read transaction and stops at the first refusal. ecr.Open instead calls Hydrate once per All
kind, with a catalog of that kind alone, so each kind is read from a read transaction of its own and a kind over its
Budget (ErrBudget), or holding an entity alive with no component value (ErrCold), stays Cold while the others
load; it then calls Hydrate with the catalog without its All kinds, which brings an engine that loaded no kind to
the seq through Start. A miss on a Touched entity is served with a view's Rows: f passes its source, with
v.Seq(), to the engine's Hydrate, which answers ErrGap when the store has committed a transaction that the
engine has not applied.
The order of a commit
Commit runs on the owner goroutine and takes these steps in this order.
- A
len(out)that differs fromlen(deeds)is an error, and no transaction is begun. With no deed,Commitreturns 0 and a nil error, again with no transaction. - The writer begins an immediate transaction and reads the seq of the store. The seq of the transaction is that seq plus one.
- Each deed is handled in slice order, inside a savepoint. The deed row takes the eid, the seq of the transaction, the
ord and the commit time in Unix milliseconds. An eid that is already in the log answers
Conflict. Then the body is written, and each op follows in list order:OpSpawninserts the entity. An eid that exists, alive or destroyed, answersRefused.OpSetneeds a live entity, else it answersRefused; it then writes the value of the component.OpUnsetneeds a live entity, else it answersRefused; it then deletes the value of the component.OpDestroyneeds a live entity, else it answersRefused; it then marks the entity gone and deletes every value of the entity. The entity row stays as a tombstone, so a destroyed eid is never spawned again.- Any other op code answers
Refused.
- A deed whose ops all applied answers
Committedand its savepoint is released. A deed answeredConflictorRefusedis rolled back to its savepoint, so nothing of it stays. - With no committed deed the transaction is rolled back, and
Commitreturns 0 and a nil error. - Otherwise the transaction commits, and
Commitreturns its seq.
CommitAt adds one check to step 2: when the seq of the transaction is not the seq the caller expects, it rolls back
before any deed is written, writes Unknown into every outcome and returns 0 and an error that matches ErrSeq.
An SQL error in step 2 to 6 rolls the transaction back, writes Unknown into every outcome and returns 0 and the error
wrapped with the text sqlite: commit: . A value of length 0 is stored as NULL. Commit keeps no deed and no value
after it returns.
The outcomes are those of package ecd. Committed is a deed written to the log. Conflict is a deed whose eid is
already committed, which is a retry. Refused is a deed that the state of the store does not allow. Unknown is a
deed whose transaction failed. Only a deed answered Committed reaches the engine.
Limits of the store
- The store holds no outbox, no intents, no
_feedor_storetables, no lineage and no replication, and it projects nothing to a lake.wal_autocheckpointkeeps the default of SQLite. - The state of a kind of residency
Touchedis written, andHydrateloads none of it: it skips every Touched kind, and when the catalog has no All kind and the seq is above 0 it calls the engine'sStart, which loads no kind. A view'sRowsreads that state back for the entities a host names, and itsScanfor every entity of a kind that holds a component; the store keeps no residency. - An entity with no component value is alive in the store, and
Hydratecannot load it, since aRowof the hydration cannot name it.Hydraterefuses its All kind, before the engine changes, with an error that matchesErrColdand names the entity, and the kind stays Cold. A body's row names the entity with no value, so an entity that holds only bodies loads. Hydratereads on a connection of its own, which it opens with the reader's settings and closes before it returns, through the C interface of SQLite thatmodernc.org/sqlitecompiles to Go, so that a stored row allocates nothing and the engine's copy is the only allocation of a value (gate G6, row AD-06).- One
statetable holds opaque values for every kind. The store has no typed tables, routes no query and keeps no index per declared query. Conflictis answered only for a deed whose eid is committed. With one writer there is no revision conflict, and an entity row carries no revision. The seq of the first commit of a retried deed is not returned.- The lock is a
flockof one machine: it does not hold across machines, and two hard links of one file, or a filesystem that emulatesflock, are not measured. On Windows the lock isLockFileExon the first byte of the lock file, which builds and is not measured. - A
Readeris one connection. On a store that no owner holds it makes the-waland-shmfiles that a WAL reader needs when they are absent, and leaves them afterClose; in a folder it cannot write, with no-shmfile,OpenReaderfails, so a read-only mount is not served. - A value is stored in the row of its component whatever its size; a large value is not split into a separate table.
- The deed kind is provisional: the tests of the module use kind
dedof systemtst, a code registered nowhere. - On macOS the writer also sets
fullfsyncandcheckpoint_fullfsync. The rows run on Linux and do not measure them.
Rows SQ-01 to SQ-14, in rows/groups/78-sq40.sh, SQ-20 to SQ-22, in rows/groups/79-sq50.sh, SQ-30 with the
plants SQ-22q and SQ-22r, in rows/groups/80-fx51.sh, SP-03 to SP-06, in rows/groups/86-sp60.sh, L12-model, in
rows/groups/50-j0m.sh, MQ-01, in rows/groups/85-mq60.sh, LK-01 to LK-05, RD-01 to RD-05, NG-01, LT-01 and CA-01,
in rows/groups/98-st44.sh (the lock, Create's stale files, the reader, the nested-call guard, the commit time and
CommitAt), and the rows of group v26, in rows/groups/9b-v26.sh (the view, the contexts, ErrBusy and
ErrNested), measure the module. They load the driver and its modules from the offline module inputs.
One import for a host
The module github.com/fiberfx/ecd-runtime/go/ecr, in go/ecr/, package ecr, is the facade of Entity Component
Runtime. A host imports this one package and requires this one module. Every type of ecr is an alias of the type of
the package that defines it: the ids of github.com/fiberfx/ecd-id/go, the seam types of package ecd, View and
Outcome among them, the Runtime, Buffer, Ref, Result, Committer, Config and Held of package rt, and
the Store and Reader of go/sqlite; each carries a doc X is pkg.X: ... of its own. The constants have the values
of the constants they name, every sentinel holds the error of its package, so errors.Is matches an error of either
name (ErrHeld, ErrNested, ErrSeq, ErrExist, ErrClosed, ErrBusy and ErrCatalog are those of package
store, and CatalogError is its type), but ErrAllKind, the facade's own, of Host.Load and Host.Evict; and
each function calls the function of the same name, but ParseTraceparent, and CreateStore and OpenStore,
which are sqlite.Create and sqlite.Open. No package of Entity Component Runtime imports ecr.
CreateStore(ctx, path, cat)issqlite.Create: the new store for the catalogcat, opened and owned (ErrExistwhen anything is at the path,ErrHeldwhen another owner holds it).OpenStore(ctx, path)issqlite.Open: the existing store, opened and owned (ErrHeld, andErrSchemafor a file that is not an owner store of user version 3). Each is a separate call, so a host can read the store, and its record of the catalog, before it chooses the catalog. Any otherstore.Storeserves as well, such asmem.New(cat)ofgo/store/mem, of class D0.Open(ctx, Options)returns aHost.OptionsholdsStore,Catalog,Minter,DeedKindandEngine, a func that builds the engine from the catalog; a nilEnginebuilds Jacquard.Storeis required: an opened store that the caller owns.Openrefuses a nilStore, a nilCatalog, a nilMinterand aDeedKindthat is not a kind with an error that matchesErrConfig, and a ctx that is already done with an error that matchesctx.Err(), before it builds an engine. It then compares the catalog with the store's record,store.Compare(o.Store, o.Catalog), and refuses a catalog whose components differ with a*CatalogError, which matchesErrCatalogand names each changed component, before it builds an engine. It then builds the engine, hydrates each All kind of the catalog from a read transaction of its own and brings the engine to the seq of the store, as "Starting a host" states, and builds theRuntimewith the store as itsCommitter.Openopens, makes and migrates no store. An All kind whose rows exceed itsBudgetstays Cold and is named inHost.Cold(); an entity alive with no component value hydrates as a presence row, so its kind is Warm and aGetof it answersErrAbsent; any other error of a hydration, such asErrStaleafter a panic of the engine, failsOpen. The engine of anEnginefunc is hydrated as Jacquard is. ctx bounds each hydration: a ctx done then failsOpenwith an error that matchesctx.Err(). An error closes the engine thatOpenbuilt and leaves the store open, the caller's to close, and is wrapped withecr: open:.Hostembeds theRuntime, soRegisterandFlushare its methods. Its fields are unexported:Store()returns the read view of its store, astore.Viewer;Engine()the read side of its engine, anEngineReader; andCold()each All kind thatOpenleft Cold with its refusal, which matchesErrBudget.Cold()is nil when every All kind is Warm, and the caller must not change the map it returns.Host.Closecloses the engine, then the store, which theHostowns onceOpenreturns it, and returnserrors.Joinof their errors. The store is closed whatever the engine answers. While a buffer holds a record that no flush has taken,Closecloses nothing and answers an error that matchesErrPending, naming each system thatPending()lists: flush the records withFlush(ctx), orDiscardeach such buffer, andCloseagain.Host.Engine()returns anEngineReader(At,State,Get,Query,Stats): the engine holds every All kind whole afterOpen, and a host cannot callHydrate,Apply,StartorEvicton it.Host.Load(ctx, ids...)reads Touched entities through in one view at the engine's seq, andHost.Evict(ids...)drops them; both refuse an eid of an All kind withErrAllKindand one of an undeclared kind withErrKindbefore any change (see "Reading after a restart").ParseTraceparent(header)is the facade's own: it returns the trace id and span id of a W3Ctraceparentheader withParseTraceIDandParseSpanID, and refuses a version00header of another field count, a higher version with no dash after the flags, versionff, flags that are not two lowercase hex characters and an id that those refuse, with the zero ids and an error that matchesErrSpanIDfor the span id andErrTraceIDotherwise.OpenReader(ctx, path)issqlite.OpenReader, andReaderissqlite.Reader: a standby or an agent reads the store of aHostthat holds it, throughReader.View(ctx, f)and theViewthatfreceives, and cannot write. A secondOpenStoreof a held store answersErrHeld;ErrNested,ErrSeq,ErrClosedandErrBusyare the store's (see "Checking errors").Host.Store().View(ctx, f),Store.View(ctx, f)andReader.View(ctx, f)callfwith an*ecr.Viewof one read transaction at one seq; itsRows,Scan,LogandBody, and the generated reads, answer atv.Seq().New(Config)isrt.New, for a host that builds itsRuntimeover an engine and aCommitterof its own.- The package
ecrtest, ingo/ecr/ecrtest/, gives the tests of a host the reference engine:NewModel(cat)returns the model ofgo/engine/jacquard/model, which a host never runs, andecrtestis the one package of the module that imports it.
import "github.com/fiberfx/ecd-runtime/go/ecr"
// run opens the store at path, creating the file for cat when create is set, records one spawn with its value under the
// span of the caller and flushes it. cat declares kind with component pos of Size 2.
func run(path string, create bool, cat *ecr.Catalog, m ecr.Minter, deedKind ecr.Code, kind ecr.Kind, pos ecr.CID,
trace ecr.TraceID, span ecr.SpanID) (ecr.Result, error) {
ctx := context.Background()
open := ecr.OpenStore
if create {
open = func(ctx context.Context, path string) (*ecr.Store, error) { return ecr.CreateStore(ctx, path, cat) }
}
s, err := open(ctx, path)
if err != nil {
return ecr.Result{}, err // matches ecr.ErrExist, ecr.ErrHeld or ecr.ErrSchema, among others
}
h, err := ecr.Open(ctx, ecr.Options{Store: s, Catalog: cat, Minter: m, DeedKind: deedKind})
if err != nil {
return ecr.Result{}, errors.Join(err, s.Close()) // matches ecr.ErrConfig or ecr.ErrCatalog, among others
}
defer h.Close() // closes the engine and the store
buf, err := h.Register(0, "tx-0001")
if err != nil {
return ecr.Result{}, err // matches ecr.ErrConfig
}
e := buf.Spawn(kind)
buf.Set(e, pos, []byte{1, 2})
buf.SetSpan(trace, span) // the ids of the buffer's next deed
res, err := h.Flush(ctx)
if errors.Is(err, ecr.ErrRef) {
return res, fmt.Errorf("tx-0001 named no entity of its buffer: %w", err)
}
return res, err // Result.Outcomes names each deed's Outcome, for example ecr.Committed
}
A host requires the one module:
require github.com/fiberfx/ecd-runtime/go/ecr v0.11.0
The module requires github.com/fiberfx/ecd-id/go v0.11.0, github.com/fiberfx/ecd-runtime/go v0.11.0 and
github.com/fiberfx/ecd-runtime/go/sqlite v0.11.0, and its build graph is that of go/sqlite. Inside this repository
replace directives point the requirements on the main module and on go/sqlite at their directories. The refusals
of package eid and its lease and minting types are not in ecr, which gives the parse and build functions of an eid
(Parse, ParseString, FromBytes, FromParts, ParseCode and MustCode), and a Minter is passed in.
Rows FC-01 to FC-03, in rows/groups/87-fc60.sh, measure the module: its tests, go mod tidy and the rule that it is
a leaf whose packages import only the standard library, eid and the packages ecd, store, rt,
engine/jacquard and sqlite, with the model for ecrtest alone and store/mem for the tests alone. Its plants,
FC-01p to FC-01zb and FC-03p to FC-03t, each change one line of a copy; FC-01z to FC-01zb are the plants of the
refusal of a nil Store, of the refusal of an Engine func that returns no engine, and of the order in which Close
closes the engine and the store (FC-01y, the plant of Migrate, is retired with it in rung 26, and FC-01v in rung
29). Row V26-11, in rows/groups/9b-v26.sh, measures the ctx of Open. The rows of group r29, in
rows/groups/9e-r29.sh, measure the host on any store: TestHostStores runs one host on the store of store/mem and
on SQLite's, refuses a nil Store, leaves a store that Open refused open, and closes the store in Host.Close.
Rows AD-01 to AD-05, L11-jacquard, L13-jacquard and L14-jacquard, in rows/groups/95-ad42.sh, measure how Open
serves the All kinds on Jacquard: each All kind Warm after one hydration, reads through generated handles and
ecd.Engine equal to the store, declared queries equal to their SQL twins, a kind over its Budget left Cold, and a
panic in a hydration that fails Open; and rows L11, L13 and L14 of the contract through Open.
Rows RF-01 to RF-09, in rows/groups/97-rf48.sh, measure Buffer.SetRef and its refusals, on the fake store and
through Open on the SQLite store; ParseTraceparent;
Result.Committed against a view's Log; the owner check with the tag ecrdebug and without it; and the
ErrPending of Host.Close, with Buffer.Discard and Runtime.Pending. Each has a plant that changes one line of a
copy.
Rows
rows/loom.rows.sh is a POSIX shell script that runs the checks of the repository. Each check is a row with an id.
Rows sit in groups. The ROWS environment variable selects rows by a comma-separated list of row ids and group names.
The default is every row. The script runs from the root of the unpacked tree, offline, and prints one line per row:
ROW id | expect X | observed Y | VERDICT
The verdicts are PASS, FAIL, KILLED, SURVIVED and CNM. A KILLED or SURVIVED verdict belongs to a plant, a deliberate fault in a temporary copy: KILLED means the row turned red, SURVIVED means it stayed green. CNM means the row measured nothing, and it is never a PASS. The exit status is 0 when every row is as expected, 1 when a row is FAIL or a plant SURVIVED, and 3 when any row is CNM and none is FAIL. The header of the script lists every row and the command that runs it.
Attribution
Entity Component Runtime's own code is under the MIT License, in LICENSE and go/LICENSE. Code taken from other
projects is listed in go/NOTICE.txt with each project's licence text.
Inspecting an entity
An agent such as Claude Code, or a developer, finds an entity or a deed by its eid and reads its state and its history from the owner store, beside the owner that holds it:
ecr inspect <eid> --store <path> --catalog <file> [--json] [--body]
The command is built in go/ecr with go build -o DIR/ecr ./cmd/ecr, or run there as go run ./cmd/ecr inspect ....
The store is opened with sqlite.OpenReader, which takes no lock and never makes a file, and read in one view, so the
answer is that of one seq. The command runs while a
host owns the store and can never change it. The eid's system must be the catalog's (any system for a detached
catalog) and its kind one of the catalog's kinds; the command looks for an entity first, then for a deed of the deed
log, so a product that mints its deeds of its entities' kind finds both. A product that knows an entity by a route
resolves the route to its eid first.
With --json the answer is one object whose "is" is "entity" or "deed", and "seq" the store's seq of the read:
- an entity has
owner(the store, the catalog, the system, the kind and the catalog's kind: its residency, budget and listed components),state(each component present, in CID order, decoded by the catalog's field types; their names formarchetype;sourceis"store", andaliveis false once a deed destroyed it) andhistory(every deed whose ops touched it, in seq and ord order, up to the seq of the state: its eid, seq, ord, outcome, commit time, trace id, span id and its ops on the entity); - a deed has
owneranddeed: its seq, ord, outcome, commit time, trace id and span id, its ops and the entities they touched, in op order.
A body is shown as its size and its sha256 digest; --body adds its bytes, as text when they are UTF-8 and as
base64 otherwise. A trace id or span id that the deed does not carry is null. The outcome is always "committed":
Commit rolls a refused or conflicting deed back with its row and its body, so the log holds no other deed. A stored
value that does not decode, or a CID the catalog does not declare, keeps its bytes in hex with the reason in
error. Without --json the same answer prints as three sections, find, state and diagnose.
Exit codes: 0 found; 1 not found, neither an entity nor a deed at the store's seq; 2 a usage error, an eid that does not parse (with the eid refusal), a catalog that cannot be read or is refused, or an eid whose system or kind the catalog does not declare (named in the refusal); 3 the store cannot be opened or read, a path that does not exist among them, with no file made.
The same calls are functions of package github.com/fiberfx/ecd-runtime/go/ecr/inspect: Inspect(eid, Options{Store, Catalog, Body}) returns a *Report, whose JSON is the command's output, and an error that matches ErrParse,
ErrCatalog, ErrUndeclared, ErrNotFound or ErrStore; ExitCode maps the error to the command's exit code;
LoadCatalog, ParseEID and Read(ctx, r, cat, id, body), on a store.Viewer the caller holds (a Reader or an
owner's Store), are its steps; WriteText prints the
three sections. The history is read by one scan of the deed log, which has no index by entity. Naming the llm turn
behind a trace id is not done yet: the command prints the trace ids. The rows of group in43 (rows/groups/9z-in43.sh)
check it.