|
| 1 | +# Architecture |
| 2 | + |
| 3 | +**Analysis Date:** 2026-03-18 |
| 4 | + |
| 5 | +## Pattern Overview |
| 6 | + |
| 7 | +**Overall:** Layered Go library for native ONNX Runtime interop, with a low-level FFI core in `ort/` and model-specific convenience layers in `embeddings/`. |
| 8 | + |
| 9 | +**Key Characteristics:** |
| 10 | +- No-CGO design: native symbols are loaded dynamically through `purego` |
| 11 | +- Global runtime lifecycle managed once per process in `ort/environment.go` |
| 12 | +- Explicit resource ownership for tensors, sessions, memory info, and embedders |
| 13 | +- Higher-level embedding packages build reusable batching and post-processing on top of the raw ORT session API |
| 14 | + |
| 15 | +## Layers |
| 16 | + |
| 17 | +**FFI Runtime Layer (`ort/`):** |
| 18 | +- Purpose: map the ONNX Runtime C API into Go and expose safe-ish wrappers for environment, tensor, memory, and session lifecycle |
| 19 | +- Contains: `InitializeEnvironment`, `DestroyEnvironment`, `AdvancedSession`, `Tensor[T]`, bootstrap/download logic, OS-specific library loading |
| 20 | +- Depends on: `purego`, `unsafe`, native ONNX Runtime shared libraries, and generated `OrtApi` bindings |
| 21 | +- Used by: all example programs and all packages under `embeddings/` |
| 22 | + |
| 23 | +**Model Adapter Layer (`embeddings/*`):** |
| 24 | +- Purpose: hide raw tensor/session wiring behind model-specific APIs |
| 25 | +- Contains: `minilm.Embedder`, `splade.Embedder`, `openclip.Embedder`, session cache management, tokenizer usage, pooling/post-processing |
| 26 | +- Depends on: `ort/`, `pure-tokenizers`, and model-specific local artifacts |
| 27 | +- Used by: example programs and downstream applications that want dense, sparse, or CLIP embeddings |
| 28 | + |
| 29 | +**Utility Layer (`embeddings/internal/ortutil`):** |
| 30 | +- Purpose: small shared helpers for resource cleanup |
| 31 | +- Contains: `DestroyAll` |
| 32 | +- Depends on: only local interfaces and the Go standard library |
| 33 | +- Used by: embedding packages when tearing down grouped ORT resources |
| 34 | + |
| 35 | +**Executable/Tooling Layer (`examples/`, `tools/`, `.github/workflows/`):** |
| 36 | +- Purpose: provide runnable demos, generators, and CI/release automation |
| 37 | +- Contains: basic/inference/openclip examples, OpenCLIP export tooling, `gen_ortapi.go`, GitHub Actions workflows |
| 38 | +- Depends on: lower library layers plus external services such as GitHub and Hugging Face |
| 39 | +- Used by: maintainers, CI, and users validating real-world flows |
| 40 | + |
| 41 | +## Data Flow |
| 42 | + |
| 43 | +**Core ORT Inference Flow:** |
| 44 | + |
| 45 | +1. Caller resolves a runtime library path explicitly or via `EnsureOnnxRuntimeSharedLibrary()` in `ort/bootstrap.go` |
| 46 | +2. `ort.InitializeEnvironment()` loads the native library, registers function pointers, and creates a process-global ORT environment |
| 47 | +3. Caller creates tensors via `ort.NewTensor` / `ort.NewEmptyTensor` |
| 48 | +4. Caller constructs an `ort.AdvancedSession` with model path, input names, and output names |
| 49 | +5. `AdvancedSession.Run()` acquires session-local and global runtime locks, converts names/values into native handles, and invokes ORT |
| 50 | +6. Callers read tensor-backed output slices and then destroy sessions/tensors/environment in reverse order |
| 51 | + |
| 52 | +**Embedding Flow:** |
| 53 | + |
| 54 | +1. Caller initializes `ort` once for the process |
| 55 | +2. Embedder loads tokenizer/model metadata and validates artifact paths |
| 56 | +3. Inputs are tokenized or preprocessed into reusable backing buffers |
| 57 | +4. Package-specific session caches keyed by batch size reuse tensors and `AdvancedSession` instances |
| 58 | +5. Post-processing converts raw outputs into dense vectors, sparse vectors, or CLIP similarity matrices |
| 59 | + |
| 60 | +**Bootstrap/Asset Resolution Flow:** |
| 61 | + |
| 62 | +1. Bootstrap resolves cache directory and target artifact names from platform/runtime config |
| 63 | +2. Downloads are guarded by file/process locks |
| 64 | +3. Archives/files are validated for size, checksum, and path traversal |
| 65 | +4. Resolved local file paths are returned to the caller for normal `ort` or embedding setup |
| 66 | + |
| 67 | +**State Management:** |
| 68 | +- Process-global ORT state lives in package globals in `ort/environment.go` |
| 69 | +- Session-level mutable state lives on `AdvancedSession` and embedder caches |
| 70 | +- Persistent state is file-based only (user cache directories and generated artifacts) |
| 71 | + |
| 72 | +## Key Abstractions |
| 73 | + |
| 74 | +**`AdvancedSession`:** |
| 75 | +- Purpose: wrap an ONNX Runtime session plus fixed input/output bindings |
| 76 | +- Examples: `ort/session.go`, used directly by `examples/inference/main.go` and all embedding packages |
| 77 | +- Pattern: stateful handle wrapper with explicit `Run()` / `Destroy()` |
| 78 | + |
| 79 | +**`Tensor[T]`:** |
| 80 | +- Purpose: represent ORT values backed by Go slices pinned for native access |
| 81 | +- Examples: `ort/tensor.go` |
| 82 | +- Pattern: generic resource wrapper with finalizer safety net and explicit destroy semantics |
| 83 | + |
| 84 | +**`BootstrapOption` / embedding `Option`:** |
| 85 | +- Purpose: configure bootstrap and embedder behavior without large constructors |
| 86 | +- Examples: `ort/bootstrap.go`, `embeddings/minilm/embedder.go`, `embeddings/splade/embedder.go`, `embeddings/openclip/embedder.go` |
| 87 | +- Pattern: functional options |
| 88 | + |
| 89 | +## Entry Points |
| 90 | + |
| 91 | +**Library Entry Points:** |
| 92 | +- `ort/environment.go` - global runtime initialization and teardown |
| 93 | +- `ort/session.go` - model session creation and inference |
| 94 | +- `ort/tensor.go` - tensor allocation and lifecycle |
| 95 | + |
| 96 | +**Example Programs:** |
| 97 | +- `examples/basic/main.go` - minimal runtime initialization example |
| 98 | +- `examples/inference/main.go` - end-to-end single-model inference flow driven by env vars |
| 99 | +- `examples/openclip/main.go` - OpenCLIP text/image embedding demo with manifest-backed fixtures |
| 100 | + |
| 101 | +**Tooling:** |
| 102 | +- `tools/gen_ortapi.go` - regenerates `ort/ortapi_generated.go` from ONNX Runtime headers |
| 103 | + |
| 104 | +## Error Handling |
| 105 | + |
| 106 | +**Strategy:** return Go `error` values aggressively, validate inputs early, and use deferred cleanup to keep native handles from leaking. |
| 107 | + |
| 108 | +**Patterns:** |
| 109 | +- Wrap lower-level failures with `fmt.Errorf(...: %w)` |
| 110 | +- Translate ORT `OrtStatus` handles into Go strings via helper functions in `ort/environment.go` |
| 111 | +- Use `errors.Join` when cleanup steps can fail independently |
| 112 | +- Treat nil receivers as safe no-ops for most `Destroy()` methods |
| 113 | + |
| 114 | +## Cross-Cutting Concerns |
| 115 | + |
| 116 | +**Concurrency:** |
| 117 | +- `ort/environment.go` defines a lock hierarchy spanning global runtime state, session runs, and tensor lifetimes |
| 118 | +- Several tests in `ort/session_test.go` and `ort/environment_test.go` exist specifically to protect these invariants |
| 119 | + |
| 120 | +**Memory Management:** |
| 121 | +- The code pins Go slice backing arrays while native ORT uses them (`ort/tensor.go`) |
| 122 | +- Finalizers are present as leak backstops, but the design still expects explicit `Destroy()` calls |
| 123 | + |
| 124 | +**Security and Integrity:** |
| 125 | +- Bootstrap code validates checksums, path traversal, redirect safety, and download size limits in both `ort/bootstrap.go` and `embeddings/openclip/bootstrap.go` |
| 126 | + |
| 127 | +--- |
| 128 | + |
| 129 | +*Architecture analysis: 2026-03-18* |
| 130 | +*Update when major patterns change* |
0 commit comments