Documentation
¶
Index ¶
- Variables
- func AppendEvent(id string, ev StateEvent) error
- func AppendHistory(run *HelperRun) error
- func ApplyParamFlags(params []HelperParam, args []string) (map[string]string, []string, error)
- func CheckHelperPackages(meta HelperScriptMeta, envImg string, params map[string]string) error
- func CheckRequiredOverlays(ctx context.Context, requiredTemplate string, params map[string]string) ([]string, error)
- func DeleteHistoryEntry(id string) error
- func EnsureServer()
- func EventsFilePath(id string) string
- func ExecutePlan(ctx context.Context, plan *RunPlan, io IO) (string, error)
- func FormatGpuSpec(spec *scheduler.ResourceSpec) string
- func GetHelperConfigKey(name, key string) (string, bool)
- func HelperConfigPath(name string) string
- func HistoryPath() string
- func IsHeadlessProcessAlive(id string) bool
- func JobLogFilePath(id string) string
- func KillHeadlessProcess(id string) error
- func LoadHelperConfig(name string) (map[string]string, error)
- func ParseGPUSpec(s string) *scheduler.GpuSpec
- func ParseValueSpec(spec string) []string
- func PidFilePath(id string) string
- func PrintHelperUsage(scriptName string, params []HelperParam, spec *scheduler.ResourceSpec, ...)
- func ReadHelperPid(id string) (int, error)
- func RefreshRemoteMetadata(ctx context.Context, force bool, w io.Writer) (map[string]RemoteScriptEntry, error)
- func ResolveEnv(cwd string) string
- func ResolveEnvOverlayInDir(envImg, cwd string) string
- func ResolveHelperSpec(scriptPath string) *scheduler.ResourceSpec
- func ResolveResources(ctx context.Context, scriptPath string, overrides *scheduler.ResourceSpec) *scheduler.ResourceSpec
- func SaveHelperConfig(name string, cfg map[string]string) error
- func SetHelperConfigKey(name, key, value string) error
- func SingletonBlocked(meta HelperScriptMeta, running []*HelperRun) bool
- func StateDir(id string) string
- func UpdateHistoryRun(id string, fn func(*HelperRun)) error
- func UpdateHistoryStatus(id, status string, endedAt time.Time) error
- func UpdateRemoteScripts(ctx context.Context, name string, forceMetadata bool, w io.Writer) error
- func ValidateHelperParamConflicts(params []HelperParam) error
- func WriteHelperPid(id string, pid int) error
- type DoneState
- type EnvStatus
- type ErrEnvInUse
- type ErrMissingPackages
- type ErrMissingParam
- type ErrSingletonRunning
- type HelperParam
- type HelperRun
- type HelperScriptMeta
- type IO
- type MessageLine
- type PollResult
- type ReadyState
- type RemoteMetadataCache
- type RemoteScriptEntry
- type RunOptions
- type RunPlan
- type StateEvent
Constants ¶
This section is empty.
Variables ¶
var HistoryRetentionLimit = 100
HistoryRetentionLimit is the maximum number of completed (non-active) entries kept in history. Active entries are always preserved. 0 disables pruning.
var ReservedShortFlags = map[string]string{
"-c": "--cpus", "-m": "--mem", "-t": "--time", "-g": "--gpu",
"-b": "--base", "-e": "--env", "-o": "--overlay", "-w": "--cwd",
}
ReservedShortFlags is the set of short flags consumed by parsePostScriptHelperFlags. -l/-u are cobra-level only and never reach script arg parsing, so they are excluded.
Functions ¶
func AppendEvent ¶
func AppendEvent(id string, ev StateEvent) error
AppendEvent appends a StateEvent to the events file for the given helper ID. Sets Ts to now if zero. The state directory must already exist (created by newHelperID).
func AppendHistory ¶
AppendHistory appends a HelperRun record to the JSONL history file.
func ApplyParamFlags ¶
ApplyParamFlags scans raw CLI args for flags defined by params. Standard resource flags (-c/-m/-t/-g/-b/-e/-o/-w) are already parsed by cobra and must NOT be in args — this handles only helper-specific #PARAM: flags. Returns (values map, unrecognised args, error).
func CheckHelperPackages ¶
func CheckHelperPackages(meta HelperScriptMeta, envImg string, params map[string]string) error
CheckHelperPackages verifies that every package in meta.ImgPackages is installed in the conda environment inside envImg. {KEY} tokens in ImgPackages are substituted from params before checking. Public wrapper around checkPackages so the server can run pre-submission validation without going through PlanRun.
func CheckRequiredOverlays ¶
func CheckRequiredOverlays(ctx context.Context, requiredTemplate string, params map[string]string) ([]string, error)
CheckRequiredOverlays expands {tokens} in meta.RequiredOverlays using params, ensures each overlay exists on disk (building any missing ones via `condatainer create`), and returns the resolved absolute paths.
Returns (nil, nil) when the template is empty. Public wrapper around the previously unexported checkAndInstallNamedOverlays.
func DeleteHistoryEntry ¶
DeleteHistoryEntry removes the entry with the given ID from the JSONL history file and deletes the associated state directory (events, job.log, etc.). It is a no-op if the ID is not found. Active (in-flight) entries are rejected so callers must stop/cancel the job before deleting its history record.
func EnsureServer ¶
func EnsureServer()
EnsureServer auto-starts the condatainer server if not running. Delegates to "condatainer server start" so the fork logic stays in one place. Prints the dashboard URL on first start.
func EventsFilePath ¶
EventsFilePath returns the path to the events JSONL file for a helper run.
func ExecutePlan ¶
ExecutePlan submits the helper job (or runs it headless) using the supplied IO for any subprocess output. Writes a "pending"/"starting" history record and returns the helperID. Subprocess stdout/stderr go through io.Stdout/ io.Stderr; status messages go through logging.FromContext(ctx).
Does not poll — call helper.Monitor (CLI) or rely on the server watcher to observe ready/done events.
func FormatGpuSpec ¶
func FormatGpuSpec(spec *scheduler.ResourceSpec) string
FormatGpuSpec formats a ResourceSpec's GPU field back to a display string. Returns "" when no GPU is set.
func GetHelperConfigKey ¶
GetHelperConfigKey reads a single key from the per-helper config. Keys are case-insensitive. Returns ("", false) if the file or key is absent.
func HelperConfigPath ¶
HelperConfigPath returns the path to the per-helper saved config file. Path: ~/.config/condatainer/helper-config/{name}.conf
func IsHeadlessProcessAlive ¶
IsHeadlessProcessAlive reports whether the process in {stateDir}/pid is still running. Returns false if the pid file is absent, unreadable, or the process no longer exists.
func JobLogFilePath ¶
JobLogFilePath returns the path to the job output log.
func KillHeadlessProcess ¶
KillHeadlessProcess sends SIGTERM to the process group of the headless helper. PGID == bash wrapper PID because ExecutePlan sets Setpgid: true. The wrapper's SIGTERM trap calls condatainer _server_done and exits cleanly.
func LoadHelperConfig ¶
LoadHelperConfig reads the saved KEY=value config for a helper. Returns an empty map if the file doesn't exist.
func ParseGPUSpec ¶
ParseGPUSpec parses a GPU spec string into a GpuSpec. Formats:
"a100:2" → {Type:"a100", Count:2}
"a100" → {Type:"a100", Count:1}
"2" → {Type:"gpu", Count:2}
"" → nil
func ParseValueSpec ¶
ParseValueSpec parses a #VALUE: value specification into a string slice. Formats:
"opt1 | opt2 | opt3" → pipe-separated option list (spaces allowed in labels) "1.0,2.0,3.0" → comma-separated version list "EXPR:range:1-41" → expression (stored as single-element slice for future use)
func PidFilePath ¶
PidFilePath returns the path to the ephemeral PID file for a headless helper run.
func PrintHelperUsage ¶
func PrintHelperUsage(scriptName string, params []HelperParam, spec *scheduler.ResourceSpec, versions map[string][]string)
PrintHelperUsage prints the combined --help text for a helper. versions is the map from ParseHelperScriptMeta().ParamValues; pass nil if unavailable.
func ReadHelperPid ¶
ReadHelperPid reads the PID from {stateDir}/pid. Returns an error if the file does not exist or contains an invalid PID.
func RefreshRemoteMetadata ¶
func RefreshRemoteMetadata(ctx context.Context, force bool, w io.Writer) (map[string]RemoteScriptEntry, error)
RefreshRemoteMetadata refreshes or loads remote helper script metadata. Earlier URLs in ScriptsLinks take precedence.
func ResolveEnv ¶
ResolveEnv returns the env overlay path that the folder-based convention would auto-pick for the given cwd, or "" if none exists. Thin wrapper around ResolveEnvOverlayInDir for symmetry with CheckEnv.
func ResolveEnvOverlayInDir ¶
ResolveEnvOverlayInDir resolves the writable overlay path for a helper in a specific directory (delegates to utils.FindEnvOverlay).
func ResolveHelperSpec ¶
func ResolveHelperSpec(scriptPath string) *scheduler.ResourceSpec
ResolveHelperSpec returns the effective ResourceSpec for a helper script, merging script headers with global build defaults. Used for display and prompts. Never errors — missing values are left as zero.
func ResolveResources ¶
func ResolveResources(ctx context.Context, scriptPath string, overrides *scheduler.ResourceSpec) *scheduler.ResourceSpec
ResolveResources merges script headers with config defaults and explicit overrides. Pass a non-nil overrides to apply user-supplied resource values on top. Pure (no logger calls).
func SaveHelperConfig ¶
SaveHelperConfig writes KEY=value pairs to the per-helper config file.
func SetHelperConfigKey ¶
SetHelperConfigKey updates or inserts a single key in the per-helper config, preserving all other existing keys. Keys are normalized to lowercase.
func SingletonBlocked ¶
func SingletonBlocked(meta HelperScriptMeta, running []*HelperRun) bool
SingletonBlocked reports whether the script's #SINGLETON: meta forbids a new launch given the running set.
func StateDir ¶
StateDir returns the NFS state directory for a helper run.
When called from inside a helper job (e.g. _server_message, _server_ready, _server_done), the wrapper has already set CNT_HELPER_STATE_DIR to the exact absolute path. Using it directly avoids any XDG/HOME resolution differences inside the Apptainer container — so messages are always written to the same directory the server watcher reads, even when the server is down.
func UpdateHistoryRun ¶
UpdateHistoryRun rewrites the JSONL history, applying fn to the record for id. If no record with that ID exists the call is a no-op. Uses an exclusive file lock to prevent concurrent writers from losing updates.
func UpdateHistoryStatus ¶
UpdateHistoryStatus rewrites the JSONL history, setting status and endedAt for the given ID. endedAt should reflect when the job actually ended (e.g. the done-event timestamp or StartedAt+Walltime for synthesised expiry), not merely when the server noticed. Prunes old completed entries if HistoryRetentionLimit is set.
func UpdateRemoteScripts ¶
UpdateRemoteScripts syncs helper scripts from the configured remote script URLs. When name is non-empty, only that helper is updated.
func ValidateHelperParamConflicts ¶
func ValidateHelperParamConflicts(params []HelperParam) error
ValidateHelperParamConflicts returns an error if any #PARAM: short flag clashes with a short flag reserved by condatainer's script-level flag parser.
func WriteHelperPid ¶
WriteHelperPid writes the bash wrapper's PID to {stateDir}/pid.
Types ¶
type DoneState ¶
DoneState is derived from a "done" StateEvent.
func ReadDoneEvent ¶
ReadDoneEvent returns the first "done" event for the given helper, or nil if none yet.
type EnvStatus ¶
type EnvStatus struct {
Path string `json:"path"`
Exists bool `json:"exists"`
InUse bool `json:"in_use"`
Writable bool `json:"writable"`
SizeMB int64 `json:"size_mb,omitempty"`
}
EnvStatus describes the state of an env overlay path for UI display. Returned by CheckEnv. Both CLI and server consume this directly.
func CheckEnv ¶
CheckEnv inspects a single overlay path: existence, lock status, type, size. Returns (zero EnvStatus, nil) when path is empty so callers can probe an unresolved path without a special case. The lock probe uses the same kind (exclusive vs. shared) that an actual mount would request: exclusive for writable .img, shared for read-only .sqf.
type ErrEnvInUse ¶
type ErrEnvInUse struct {
Path string
}
ErrEnvInUse signals that the chosen writable overlay is locked by another process. The conflicting path is preserved so callers can render a useful message.
func (*ErrEnvInUse) Error ¶
func (e *ErrEnvInUse) Error() string
type ErrMissingPackages ¶
type ErrMissingPackages struct {
EnvImg string
Specs []string // raw specs for micromamba install, e.g. ["jupyterlab", "python>=3.12"]
Messages []string // human-readable per-spec descriptions
VersionChoices map[string][]string // package name → selectable versions (from #VALUE:)
}
ErrMissingPackages is returned by PlanRun when #IMG_PACKAGES: specs are not satisfied in the conda environment inside EnvImg. Specs holds the raw unsatisfied specs suitable for micromamba install; Messages holds matching human-readable descriptions for display. ErrMissingPackages is returned by PlanRun when #IMG_PACKAGES: specs are not satisfied in the conda environment inside EnvImg. Specs holds the raw unsatisfied specs suitable for micromamba install; Messages holds matching human-readable descriptions for display. VersionChoices is non-nil when one or more missing packages had an unresolved version token ({CONDA_PYTHON} etc.) with a known #VALUE: list — the UI should prompt the user to pick a concrete version before installing. Keys are package names (e.g. "python"); values are the selectable versions.
func (*ErrMissingPackages) Error ¶
func (e *ErrMissingPackages) Error() string
type ErrMissingParam ¶
type ErrMissingParam struct {
Params []HelperParam
}
ErrMissingParam is returned by PlanRun when one or more required #PARAM: values are not supplied. The CLI prompts; the server returns HTTP 400.
func (*ErrMissingParam) Error ¶
func (e *ErrMissingParam) Error() string
type ErrSingletonRunning ¶
type ErrSingletonRunning struct {
Existing []*HelperRun
}
ErrSingletonRunning indicates the script is marked #SINGLETON: true and at least one instance is already running. CLI prints "already running"; server returns HTTP 409.
func (*ErrSingletonRunning) Error ¶
func (e *ErrSingletonRunning) Error() string
type HelperParam ¶
type HelperParam struct {
Key string `json:"key"`
Default string `json:"default,omitempty"`
Optional bool `json:"optional,omitempty"` // true when declared as KEY=?
LongFlag string `json:"long_flag,omitempty"`
ShortFlag string `json:"short_flag,omitempty"`
Desc string `json:"desc,omitempty"`
}
HelperParam represents a single #PARAM: declaration from a helper script. Format: #PARAM: KEY=default --long-flag,-s "Description" Use KEY=? to mark the param as optional (passes through empty; script handles it).
func MissingParams ¶
func MissingParams(scriptPath string, supplied map[string]string) ([]HelperParam, error)
MissingParams returns the #PARAM: entries from scriptPath that need user input — i.e. not present in `supplied`, not optional (KEY=?), and without a literal default.
Pure: no prompts, no I/O beyond reading the script file.
func ParseHelperParams ¶
func ParseHelperParams(scriptPath string) ([]HelperParam, error)
ParseHelperParams extracts #PARAM: declarations from a helper script. Format per line: #PARAM: KEY=default --long-flag,-s "Description" - KEY=default: variable name and default value (empty after = means required) - --long-flag,-s: optional flag spec (comma-separated; either part may be omitted) - "Description": quoted description string
type HelperRun ¶
type HelperRun struct {
ID string `json:"id"` // "{name}-YYYYMMDD-HHMMSS"
Name string `json:"name"` // helper script name
JobID string `json:"job_id"` // scheduler job ID or ""
Node string `json:"node"` // compute node hostname
Port int `json:"port"` // 0 = URL-only service (vscode-tunnel)
CWD string `json:"cwd"` // working directory
Walltime time.Duration `json:"walltime_secs"` // from #TIME: / -t flag
CPUs int `json:"cpus,omitempty"`
Mem string `json:"mem,omitempty"` // e.g. "32GB", "1536MB" — via utils.FormatMemoryMB
GPU string `json:"gpu,omitempty"` // e.g. "a100:1"
BaseImage string `json:"base_image,omitempty"` // overridden with -b
EnvOverlay string `json:"env_overlay,omitempty"` // writable .img (-e)
Overlays []string `json:"overlays,omitempty"` // read-only .sqf (-o)
Params map[string]string `json:"params,omitempty"` // resolved #PARAM: values
URLPath string `json:"url_path"` // appended to proxy URL (e.g. "?token=abc123")
ExternalURL string `json:"external_url"` // shown as-is, no proxy (e.g. vscode-tunnel URL)
BindAll bool `json:"bind_all,omitempty"` // true = direct TCP proxy (no SSH tunnel)
StartedAt time.Time `json:"started_at"`
EndedAt *time.Time `json:"ended_at,omitempty"`
Status string `json:"status"` // "running"|"done"|"failed"
}
HelperRun records one execution of a helper (stored in JSONL history).
func HistoryEntryForID ¶
HistoryEntryForID returns the most recent JSONL record for the given helper ID.
func LoadHistory ¶
LoadHistory reads the JSONL history file and returns all records (oldest first).
func RecentHistoryByName ¶
RecentHistoryByName returns the last N distinct-CWD runs for a helper name.
func Running ¶
Running returns the active HelperRun records for name (empty = any). Symmetric alias for RunningHelpers.
func RunningHelpers ¶
RunningHelpers returns all HelperRun records with an active status, verifying each is still alive via the events file (no done event yet).
func (*HelperRun) AccessURL ¶
AccessURL returns the link the user should open. ExternalURL takes priority; otherwise returns the subdomain proxy URL (http://{id}.localhost:{port}/{urlPath}).
func (*HelperRun) EstimatedEnd ¶
EstimatedEnd returns StartedAt + Walltime; zero value if walltime is unknown.
type HelperScriptMeta ¶
type HelperScriptMeta struct {
// ImgRequired is true when the #IMG_PACKAGES: header is present, meaning the
// helper requires a writable overlay (.img) even if no packages are listed.
ImgRequired bool
// ImgPackages is a template of conda packages for guided overlay creation and
// pre-submission package verification. {KEY} tokens are substituted from
// resolved #PARAM: values before use. Empty when #IMG_PACKAGES: has no value.
ImgPackages string
// RequiredOverlays is a space-separated template of named condatainer overlays
// (SquashFS images) to load before the helper runs. {KEY} tokens are substituted
// from resolved #PARAM: values (e.g. "rstudio-server build-essential r{POSIT_R}").
// Parsed from #REQUIRED_OVERLAYS: (alias: legacy #OVERLAY_PACKAGES:).
RequiredOverlays string
// PostInstallCmd is run inside the container after micromamba installs ImgPackages.
PostInstallCmd string
// Singleton is true when at most one running instance of this helper is allowed.
Singleton bool
// Binds is a list of extra bind-mount specs from #BIND: headers, in "src:dest" form.
// {KEY} tokens are substituted from resolved #PARAM: values before use.
// $VAR references (e.g. $CNT_HELPER_STATE_DIR, $HOME) are passed verbatim and
// expanded by the shell when the wrapper runs on the compute node.
Binds []string
// ParamValues holds the valid-value lists parsed from #VALUE: headers.
// Keys are param names (e.g. "POSIT_R", "CONDA_PYTHON"); values are the parsed list.
ParamValues map[string][]string
// NCPUs is the default CPU count from #NCPUS:. Zero means not set.
NCPUs int
// MemMB is the default memory in MB from #MEM:. Zero means not set.
MemMB int64
// Walltime is the default walltime from #TIME:. Zero means not set.
Walltime time.Duration
// GPU is the default GPU spec from #GPU:. Empty means not set.
GPU string
}
HelperScriptMeta holds overlay and singleton metadata extracted from a helper script.
func ParseHelperScriptMeta ¶
func ParseHelperScriptMeta(scriptPath string) (HelperScriptMeta, error)
ParseHelperScriptMeta extracts metadata from a helper script. Recognised headers: #NCPUS:, #MEM:, #TIME:, #GPU:, #IMG_PACKAGES:, #REQUIRED_OVERLAYS:, #OVERLAY_PACKAGES: (legacy), #POST_INSTALL_CMD:, #SINGLETON:, #BIND:, #VALUE:.
type IO ¶
IO carries explicit streams for ExecutePlan. The CLI passes os.Stdout/os.Stderr; the server passes an HTTP response writer so install/post-install subprocess output reaches the browser instead of the daemon log.
type MessageLine ¶
type MessageLine struct {
Level string `json:"level"`
Text string `json:"text"`
Ts time.Time `json:"ts"`
}
MessageLine is derived from a "msg" StateEvent.
func ReadMessages ¶
func ReadMessages(id string, offset int64) ([]MessageLine, int64, error)
ReadMessages reads "msg" events from the events file starting at byte offset. Returns message lines, the new offset, and any error.
type PollResult ¶
type PollResult struct {
NewMessages []MessageLine
NewOffset int64
Ready *ReadyState // non-nil when a "ready" event appears in this window
Done *DoneState // non-nil when a "done" event appears in this window
}
PollResult is the outcome of one non-blocking pass over a helper's events file.
func PollOnce ¶
func PollOnce(id string, offset int64) PollResult
PollOnce reads new events from the helper's events file starting at offset. Returns new messages, a ready state (if the ready event fell within this window), a done state (likewise), and the advanced byte offset for the next call.
type ReadyState ¶
type ReadyState struct {
Port int `json:"port"`
Node string `json:"node"`
Timestamp time.Time `json:"ts"`
WalltimeSec int64 `json:"walltime_secs"`
JobID string `json:"job_id"`
URLPath string `json:"url_path"`
ExternalURL string `json:"external_url"`
}
ReadyState is derived from a "ready" StateEvent; used by callers that need the ready information as a typed struct.
func ReadReadyEvent ¶
func ReadReadyEvent(id string) (*ReadyState, error)
ReadReadyEvent returns the first "ready" event for the given helper, or nil if none yet.
type RemoteMetadataCache ¶
type RemoteMetadataCache struct {
FetchedAt time.Time `json:"fetched_at"`
SourceURL string `json:"source_url"`
Metadata map[string]remoteHelperEntry `json:"metadata"`
}
RemoteMetadataCache is the on-disk envelope for cached helper script metadata.
type RemoteScriptEntry ¶
RemoteScriptEntry represents a helper script entry from remote metadata.
type RunOptions ¶
type RunOptions struct {
ScriptPath string
ScriptName string
// Resources holds user-specified resource values (nil = use script/config defaults).
Resources *scheduler.ResourceSpec
// Container options
BaseImage string
EnvImg string // writable overlay (.img)
Overlays []string // additional read-only overlays
CWD string // working directory inside job
// Behaviour
ForceNew bool
// ExtraBinds is the resolved list of extra bind-mount specs ("src:dest") from
// #BIND: headers, with {KEY} tokens already substituted from params.
// $VAR references are left as-is for shell expansion when the wrapper runs.
ExtraBinds []string
// #PARAM: values resolved from flags + prompts (raw args passed through)
FlagArgs []string
Params map[string]string
}
RunOptions holds all resolved options for running a helper.
type RunPlan ¶
type RunPlan struct {
Options RunOptions
Meta HelperScriptMeta
Spec *scheduler.ResourceSpec
Scheduler scheduler.Scheduler
UserOverlays []string
NamedOverlays []string
Params map[string]string
ContainerCmd string
}
RunPlan is the resolved, validated state of a helper invocation. PlanRun produces it; ExecutePlan consumes it.
func PlanRun ¶
func PlanRun(ctx context.Context, opts RunOptions) (*RunPlan, error)
PlanRun validates and resolves opts into a RunPlan without any user I/O. All prompts (param menus, resource menus, history menu, guided overlay creation) are the caller's responsibility — fill opts first.
Returns typed errors (*ErrMissingParam, *ErrSingletonRunning, *ErrEnvInUse) so callers can react contextually. Other errors are plain.
type StateEvent ¶
type StateEvent struct {
Type string `json:"type"`
Ts time.Time `json:"ts"`
// "msg" fields
Level string `json:"level,omitempty"` // "info"|"warn"|"error"
Text string `json:"text,omitempty"`
// "ready" fields
Port int `json:"port,omitempty"`
Node string `json:"node,omitempty"`
WalltimeSec int64 `json:"walltime_secs,omitempty"`
JobID string `json:"job_id,omitempty"`
URLPath string `json:"url_path,omitempty"`
ExternalURL string `json:"external_url,omitempty"`
// "done" fields — pointer so exit_code:0 is preserved in JSON (not omitted by omitempty)
ExitCode *int `json:"exit_code,omitempty"`
}
StateEvent is one entry in the unified events JSONL file per helper run. Type is one of "msg", "ready", or "done".
func ReadEventsFrom ¶
func ReadEventsFrom(id string, offset int64) ([]StateEvent, int64, error)
ReadEventsFrom reads StateEvents from the events file starting at byte offset. Returns the events, the new byte offset, and any error. Returns offset unchanged and nil slice if the file does not exist yet.