package bamllib import ( "context" "encoding/json" "errors" "fmt" "os" "path/filepath" "runtime" "sync" "sync/atomic" "time" ) // Library is one loaded shared library: its C functions, its description, // and the event pump that wakes waiting calls. // // How a call waits without holding an OS thread: a goroutine blocked inside // a C call holds its thread for as long as the call blocks, so 10,000 // waiting calls would mean 10,000 threads. A call that may wait is therefore // started with baml_lib_call, which returns at once, and the goroutine waits // on a channel. One pump goroutine waits for the library's wake descriptor // through Go's poller (kqueue, epoll), so waiting costs it no thread either; // when the descriptor is readable it takes every queued event with // baml_lib_next_event and hands each to the channel of its call. type Library struct { path string api capi desc Description syncPath bool // syncSlots bounds the calls on the direct path at once: each holds an // OS thread while it runs, and Go's thread limit is fatal. Calls over // the bound go through baml_lib_call and wait on a channel instead. syncSlots chan struct{} mu sync.Mutex waiters map[uint64]*waiter early map[uint64]event // events that arrived before their call registered // pumpDead is set when the pump stopped: every waiting call got it, and // every later waiting call fails with it at once. pumpDead error pumpOnce sync.Once pumpErr error wake *os.File takes atomic.Int64 // results fetched with baml_lib_take (for tests) // Host functions passed to BAML, by id (never reused), until the // library says the closure is gone (HOST_FN_DROPPED). fnMu sync.Mutex hostFns map[uint64]*hostFn nextFn atomic.Uint64 // Host values sent to BAML, counted per token (see hostvalue.go). hv hostValues // progs are the programs loaded on this library (the first decodes // failures nobody awaited). progs []*Program // handles counts the handles alive in Go (for tests). handles atomic.Int64 } // waiter is an async call waiting for its FINISHED event: the channel it // arrives on, the context host calls of the call run under, and what the // call must keep alive until it ends (handles it sent: the library reads an // async call's arguments after baml_lib_call returns). type waiter struct { ch chan event ctx context.Context pins []*Handle // discard reads the result of a call nobody waits for any more, so the // handles in it are released (nil: it cannot hold any). discard func(status uint32, data []byte) } // event is one finished async call, or the pump's failure. type event struct { status uint32 data []byte err error } // Config is how the library is started. type Config struct { // Workers is the number of worker threads; 0 lets the library choose. Workers uint32 // MaxCalls bounds the calls in flight; 0 lets the library choose. MaxCalls uint32 // AsyncOnly sends every call through baml_lib_call, also those // `describe` says can never wait (which otherwise use // baml_lib_call_sync on the calling thread). The environment variable // BAML_LIBRARY_ASYNC_ONLY=1 sets it too. For measurements, and for a // program that wants every call to hold no thread. AsyncOnly bool } var ( openMu sync.Mutex opened = map[string]*Library{} ) // Open loads the library at path and starts it, once per process and file. // Every Open of the same file (by any path that resolves to it) returns the // same Library, so two generated packages that use one library share its // pump and its table of waiting calls. A second, different library is // refused. func Open(path string, cfg Config) (*Library, error) { openMu.Lock() defer openMu.Unlock() if resolved, err := filepath.EvalSymlinks(path); err == nil { if abs, err := filepath.Abs(resolved); err == nil { path = abs } } if lib, ok := opened[path]; ok { return lib, nil } // The same file under another name (a hard link): the same library. if info, err := os.Stat(path); err == nil { for other, lib := range opened { if otherInfo, err := os.Stat(other); err == nil && os.SameFile(info, otherInfo) { return lib, nil } } } if len(opened) > 0 { // The library's runtime is process-wide; a second, different // library would share its exported names. for other := range opened { return nil, fmt.Errorf("a BAML library is already loaded in this process (%s)", other) } } api, err := openAPI(path) if err != nil { return nil, fmt.Errorf("load BAML library %s: %w", path, err) } ib := newInitBuf() ib.cfg.workers = cfg.Workers ib.cfg.maxCalls = cfg.MaxCalls switch rc := api.init(ib); rc { case rcOK, rcAlready: case rcInitFailed: n := min(int(ib.errLen), len(ib.err)) return nil, fmt.Errorf("BAML library %s: program initialization failed: %s", path, ib.err[:n]) default: return nil, fmt.Errorf("BAML library %s: baml_lib_init returned %d", path, rc) } n := api.describe(ib) ib.out = make([]byte, n) if got := api.describe(ib); got != n { return nil, fmt.Errorf("BAML library %s: description changed size", path) } lib := &Library{ path: path, api: api, syncPath: !cfg.AsyncOnly, syncSlots: make(chan struct{}, 4*runtime.GOMAXPROCS(0)), waiters: map[uint64]*waiter{}, early: map[uint64]event{}, hostFns: map[uint64]*hostFn{}, } lib.hv.init() if err := json.Unmarshal(ib.out, &lib.desc); err != nil { return nil, fmt.Errorf("BAML library %s: bad description: %w", path, err) } lib.desc.prepare() opened[path] = lib return lib, nil } // Description is what baml_lib_describe returns. func (l *Library) Description() *Description { return &l.desc } // Stats returns the library's counters as JSON. func (l *Library) Stats() []byte { ib := newInitBuf() for { n := l.api.stats(ib) if n <= uintptr(len(ib.out)) { return append([]byte(nil), ib.out[:n]...) } // The counters grew between the calls: ask again with room to spare. ib.out = make([]byte, n+64) } } // startPump starts the event pump on first use: for async calls, and as // soon as a host function or host value is sent (their drop notices and the // host calls of tasks that outlive a call arrive as events). func (l *Library) startPump() error { l.pumpOnce.Do(func() { fd := l.api.wakeFD() if fd < 0 { l.pumpErr = errors.New("BAML library has no wake descriptor (not initialized)") return } wake, err := pollable(fd) if err != nil { l.pumpErr = err return } l.wake = wake raw, err := l.wake.SyscallConn() if err != nil { l.pumpErr = fmt.Errorf("poll the BAML wake descriptor: %w", err) return } go func() { eb := newEventBuf() // Read calls the function, and while it returns false waits in the // poller until the descriptor is readable again. The library keeps // the descriptor readable exactly while events are queued, and // baml_lib_next_event drains it, so the pump never reads it. err := raw.Read(func(uintptr) bool { l.drain(eb) return false }) // Read returns only when polling fails. Waiting calls would then // wait forever: fail them, and every later one, with the cause. if err == nil { err = errors.New("stopped") } l.stopPump(fmt.Errorf("BAML library event pump stopped: %w", err)) }() }) return l.pumpErr } // stopPump fails every waiting call and makes later waiting calls fail. func (l *Library) stopPump(err error) { l.mu.Lock() l.pumpDead = err waiters := l.waiters l.waiters = map[uint64]*waiter{} l.early = map[uint64]event{} l.mu.Unlock() for _, w := range waiters { for i, h := range w.pins { h.unpin() w.pins[i] = nil } w.ch <- event{err: err} } } // drain takes every queued event and handles it. func (l *Library) drain(eb *eventBuf) { for { switch rc := l.api.nextEvent(eb); rc { case rcOK: ev := eb.ev switch ev.kind { case eventFinished: data := append([]byte(nil), eb.out[:ev.len]...) l.deliver(ev.call, event{status: ev.status, data: data}) case eventHostCall: // Host calls of async calls, and of tasks a call left // running: each runs on a goroutine of its own, under the // context of the call running the code (when it still runs). data := append([]byte(nil), eb.out[:ev.len]...) fn := l.hostFn(ev.hostFn) ctx := l.callContext(ev.call) read := l.hv.beginRead() go l.answerEvent(ctx, ev.call, ev.reply, ev.hostFn, fn, data, read) case eventHostFnDropped: l.fnMu.Lock() delete(l.hostFns, ev.hostFn) l.fnMu.Unlock() case eventHostValueDropped: l.hv.drop(ev.hostFn) case eventUnhandled: data := append([]byte(nil), eb.out[:ev.len]...) read := l.hv.beginRead() go l.unhandled(ev.status, data, read) } if len(eb.out) > 1<<20 { // Do not keep the largest event's room forever. eb.out = make([]byte, 4096) } case rcTooSmall: eb.grow(eb.ev.len) default: l.hv.sweep() return } } } func (l *Library) deliver(call uint64, ev event) { l.mu.Lock() w, ok := l.waiters[call] if ok { delete(l.waiters, call) } else { l.early[call] = ev } l.mu.Unlock() if ok { // The call has ended: the handles it sent can go. for i, h := range w.pins { h.unpin() w.pins[i] = nil } if w.discard != nil { // Nobody reads this result (the caller gave up): read it here, // so its handles are owned, and released, by Go. go w.discard(ev.status, ev.data) } w.ch <- ev // buffered: never blocks, also when the caller gave up } } // settle keeps what a call's arguments handed to the library, except the // host functions of a call it refused (no BAML closure holds them). func (l *Library) settle(w *Writer, status uint32) { if status == StatusRefused { l.unregisterHostFns(w.fns) } w.commit() } // callContext is the context of a running async call, or Background for a // call that has finished (a task it left running makes the host call). func (l *Library) callContext(call uint64) context.Context { l.mu.Lock() w, ok := l.waiters[call] l.mu.Unlock() if ok && w.ctx != nil { return w.ctx } return context.Background() } // call runs a call (target kind and target: a function id, or the handle of // a function value) with the arguments in b, and returns the status and the // result bytes. The bytes live in b (sync path) or in a fresh slice (async // path) and stay valid until b goes back to the pool. timeoutMs > 0 is the // call's deadline in the library. func (l *Library) call(ctx context.Context, kind uint32, target uint64, mayWait bool, timeoutMs uint64, b *callBuf) (uint32, []byte, error) { if !mayWait && l.syncPath { select { case l.syncSlots <- struct{}{}: status, data, err := l.callSync(ctx, kind, target, timeoutMs, b) <-l.syncSlots // call_sync read the arguments before it returned. l.settle(&b.args, status) b.args.unpinAll() // The direct path cannot be cancelled. A deadline that passed // while it ran still ends the call with the context's error, so // both paths report a passed deadline alike; the work is done. if err == nil { if cerr := ctx.Err(); cerr != nil { return 0, nil, cerr } } return status, data, err default: // Too many direct calls at once: wait on a channel instead. } } if err := l.startPump(); err != nil { b.args.rollback() return 0, nil, err } l.mu.Lock() dead := l.pumpDead l.mu.Unlock() if dead != nil { b.args.rollback() return 0, nil, dead } b.wt.ctx = ctx b.wt.pins = b.args.pins // One lock across baml_lib_call and the registration of the id: the // pump reads events (and host calls naming this id) on another thread. l.mu.Lock() callID := l.api.call(kind, target, b, timeoutMs) if callID == 0 { l.mu.Unlock() b.wt.ctx, b.wt.pins = nil, nil b.args.rollback() return 0, nil, errors.New("BAML library refused to start the call (not initialized)") } if l.pumpDead != nil { dead := l.pumpDead l.mu.Unlock() l.api.cancel(callID) b.wt.ctx, b.wt.pins = nil, nil b.args.commit() b.args.unpinAll() return 0, nil, dead } ev, arrived := l.early[callID] if arrived { delete(l.early, callID) } else { l.waiters[callID] = &b.wt } l.mu.Unlock() if arrived { b.wt.ctx, b.wt.pins = nil, nil l.settle(&b.args, ev.status) b.args.unpinAll() return ev.status, ev.data, nil } done := ctx.Done() if done == nil { ev = <-b.wt.ch b.wt.ctx, b.wt.pins = nil, nil l.settle(&b.args, ev.status) return ev.status, ev.data, ev.err } select { case ev = <-b.wt.ch: b.wt.ctx, b.wt.pins = nil, nil l.settle(&b.args, ev.status) return ev.status, ev.data, ev.err case <-done: // A cancelled context and a passed deadline end the wait at once, // as with the default back end; the call ends in the library where // it next waits (baml_lib_cancel, or its own deadline). Its event // still arrives: a detached waiter keeps the call's handles alive // until then, and b gets a fresh channel. l.mu.Lock() _, registered := l.waiters[callID] if registered { l.waiters[callID] = &waiter{ch: b.wt.ch, pins: append([]*Handle(nil), b.wt.pins...), discard: b.discard} } l.mu.Unlock() if registered { l.api.cancel(callID) b.wt.ch = make(chan event, 1) } else { // Delivered meanwhile: wait until the pump has given the pins // back (it sends the event after), and read the result nobody // will, so its handles are released. ev := <-b.wt.ch if b.discard != nil { go b.discard(ev.status, ev.data) } } b.wt.ctx, b.wt.pins = nil, nil b.args.commit() // The detached waiter (or the delivery) unpins; this write must not. for i := range b.args.pins { b.args.pins[i] = nil } b.args.pins = b.args.pins[:0] return 0, nil, ctx.Err() } } // callSync runs a call on this goroutine's thread. Host calls it makes come // back here (BAML_LIB_HOST_CALL): each runs on a goroutine of its own (a // callback may call runtime.Goexit) while this one waits, and is answered // with baml_lib_reply_sync, which waits for the call again. func (l *Library) callSync(ctx context.Context, kind uint32, target uint64, timeoutMs uint64, b *callBuf) (uint32, []byte, error) { rc := l.api.callSync(kind, target, b, timeoutMs) for { var args []byte switch rc { case rcOK: return b.res.status, b.out[:b.res.len], nil case rcTooSmall: b.grow(b.res.len) l.takes.Add(1) if b.res.kind == eventHostCall { if rc := l.api.take(b.res.reply, b); rc != rcOK { return 0, nil, fmt.Errorf("baml_lib_take returned %d for host-call arguments", rc) } args = b.out[:b.res.len] break } if rc := l.api.take(b.res.call, b); rc != rcOK { return 0, nil, fmt.Errorf("baml_lib_take returned %d", rc) } return b.res.status, b.out[:b.res.len], nil case rcHostCall: args = b.out[:b.res.len] default: return 0, nil, fmt.Errorf("baml_lib_call_sync returned %d", rc) } reply, fnID := b.res.reply, b.res.hostFn done := make(chan uint32, 1) w := &b.reply w.reset() w.lib = l go l.invoke(ctx, fnID, l.hostFn(fnID), args, w, func(status uint32) { done <- status }) status := <-done w.commit() rc = l.api.replySync(reply, status, b) // reply_sync returned once the library took the answer: the // handles it carried can go. w.unpinAll() } } // keepPins keeps the handles a host reply carried until the call that // made the host call ends (the library reads the reply when the waiting // task resumes). A call that already ended (a task it left running made // the host call) keeps them for a while instead. func (l *Library) keepPins(call uint64, pins []*Handle) { if len(pins) == 0 { return } l.mu.Lock() w, ok := l.waiters[call] if ok { w.pins = append(w.pins, pins...) } l.mu.Unlock() if !ok { time.AfterFunc(10*time.Second, func() { for _, h := range pins { h.unpin() } }) } }