How It Works
glci sits between your .gitlab-ci.yml and the official gitlab-runner. Instead of talking to a real GitLab instance, the runner talks to a mock GitLab API server running as a daemon-scoped container. Jobs execute in real containers with the same shell scripts, image pulls, and lifecycle that GitLab CI uses in production — no simulation, no approximation.
glci drives a container engine by shelling out to its CLI (docker or podman). Both Docker and Podman are supported; the engine is selected via [docker] engine in config (per-runner override with [runners.<name>] engine). When engine is unset (omitted), glci uses Docker, or auto-falls back to Podman if Docker is unreachable and Podman is — printing a one-time notice to stderr; set engine = "podman" to silence it. An explicit engine = "docker" opts out of that probing and never falls back. The choice of engine is orthogonal to the gitlab-runner executor: the generated runner config always uses executor = "docker" even under Podman, because gitlab-runner has no podman executor — glci simply points it at Podman’s Docker-compatible API socket. See Container engine for the engine setting.
Component overview#
Data flow#
The mock server is the central hub — the only component both the daemon and the runner communicate with. Jobs push/pull artifacts, cache, and container images directly to/from the mock server via an extra_hosts entry pointing at the Docker host, with FF_NETWORK_PER_BUILD. When runners target a Docker daemon on a different machine, a relay proxy bridges the gap (shown in dashed lines).
Infrastructure#
Daemon-managed (shared across pipelines)#
glci-mock— mock server container (API + embedded OCI registry on port 39741 by default, configurable viamock_server_port). Started once by the daemon; jobs reach it via anextra_hostsentry and the port published on the Docker host, withFF_NETWORK_PER_BUILD. The entry’s address is decided per daemon when a pipeline starts: Docker’shost-gatewayon Docker Desktop’s WSL2 backend, the gateway of glci’s persistent bus network (glci-bus*) everywhere else — see[network] host_gateway. The bus network’s subnet is a /24 of[network] bus_subnet(172.16.0.0/16by default), outside the pools adocker:dindservice hands its own networks out of, so a network a job creates inside DinD normally never shadows that gateway (it can underbus_subnet = "auto", a range that overlaps the default pools, or when no subnet of the range was free).Runner containers — persistent
gitlab/gitlab-runnercontainers managed byRunnerManager. Three tiers:- Shared runner (
glci-runner-{suffix}) — handles projects with default config; jobs without matching named-runner tags go here. - Per-project runner (
glci-runner-{suffix}-{project}) — created when[runner] config_templateis set for the project, in either config file. Isolated from the shared runner. - Named runner (
glci-runner-{suffix}-{project}-{name}) — one per[runners.<name>]config entry. Jobs whose tags match the runner name are routed here viarun_untagged=false.
Each runner container polls the mock server for jobs via tag-based dispatch. Config is written to a Docker volume and reloaded via SIGHUP. When a
config_templateproduces multiple[[runners]]blocks, glci derives sub-tokens and registers each runner separately. Named runners can target different Docker daemons viadocker_host(endpoint URL) ordocker_context(Docker context name). Remote runners get their own bus network on the remote daemon and reach the mock server through the mock port published on that daemon’s host — by a relay proxy container when the daemon is on a different machine. The runner container and its job containers both resolveglci-mockthrough the sameextra_hostsentry, its address decided for that daemon (host-gatewayon Docker Desktop WSL2, the runner’s bus network gateway elsewhere).- Shared runner (
All containers are long-lived. They start on first use and stop when the daemon shuts down. If a container is missing (manually removed, Docker restart), the daemon recreates it on demand. Per-project and named runners are created lazily when a pipeline first needs them.
Per-pipeline#
glci-net-{id}— Docker bridge network. The shared mock and runner containers are connected to it for the pipeline’s lifetime.- DinD jobs without a
resource_groupof their own are serialized via the_glci_dindresource group to prevent concurrent DinD jobs from conflicting on thedockerservice alias, in a pipeline resumed after a daemon restart too. runner-*— Transient job execution containers, spawned by the runner’s Docker executor. One per job, destroyed after the job finishes.
Pipeline execution lifecycle#
This is the sequence of events when you run glci run [jobs...]:
Detailed steps#
- CLI sends StartPipeline to daemon via Unix socket (daemon auto-starts if not running). If another pipeline is already being prepared for the same directory, the request is queued instead of rejected — the daemon holds the HTTP connection open and starts the queued pipeline automatically when the current preparation finishes. Cancelling the request (Ctrl+C) dequeues it. A maximum queue depth of 3 prevents resource exhaustion.
- Daemon parses
.gitlab-ci.yml— offline parser resolves includes (deciding each entry’sinclude:rules first), extends,!referencetags; expandsparallel:jobs into shards. It evaluatesworkflow:rules (rejecting the pipeline outright when none of them accept, as GitLab does), and the planner then evaluates each job’srules:— after expansion, so every shard is judged on its own matrix values — and builds the execution plan (stages, DAG, auto-include upstream deps) - Daemon creates per-pipeline Docker network (
glci-net-{id}) - Daemon prepares source code — creates a bare git repo from the working directory (including uncommitted/untracked files in dirty mode), tar.gz for upload. In dirty mode, the changed files are hashed in your project under its own Git configuration, with a temporary index and the object database pointed at the bare repo. Your index and object store are never written, and the tree and commit are written in the bare repo. Repeated runs on the same commit reuse a cached copy — see the bare repo cache below
- Daemon ensures mock container is running — connects to pipeline network, registers per-pipeline state (secret), configures S3 cache credentials, uploads git repo. When a job asks for submodules, one additional bare repo per submodule is prepared and served alongside it, each pinned to the commit the superproject records
- Daemon ensures runner container is running — connects to pipeline network, Docker socket or
DOCKER_HOSTfor remote Docker - Scheduler dispatches jobs — concurrent within stages, DAG-aware, respects
resource_groupexclusions. Per job: queue on mock server with HMAC token, persistent runner polls for job, clones source, downloads artifacts, executes scripts, uploads artifacts, streams trace, reports completion - Trigger jobs spawn child pipelines sharing the same mock and runner containers (max depth: 2). The child’s config is parsed with the parent’s GitLab credentials and include cache, so its own
include: project:/component:resolve the same way the top-level config’s do. A child gets its own submodule walk when it asks for more than the pipeline that spawned it served, and a cross-project target’s submodules are read from that project’s own commit - Daemon persists artifacts to
~/.glci/projects/{key}/pipelines/{id}/ - EventBus streams events to all connected CLI clients
The bare repo cache#
Preparing the repository is the slowest part of starting a pipeline, so the result is cached and reused whenever HEAD names the same commit, whichever branch you are on.
Entries live at ~/.glci/bare-repos/{project}/cache-{SHA}.git, where {project} is the project’s directory name followed by a digest of its path. Every project on the machine shares the one bare-repos directory, so each gets a subdirectory of its own and keeps a single entry: evicting the previous entry for a project never reaches another project’s. A cross-project trigger whose target is a local directory is a project in its own right and gets a subdirectory of its own; submodule repositories are prepared fresh on every run and are not cached.
~/.glci itself is created 0700, so the listing alone does not say which registries you configured or which workdirs are live. An existing ~/.glci keeps its mode; only fresh installs get the tighter one.
bare-repos holds copies of your source - the cached entries, plus the per-run copies that carry uncommitted changes in dirty mode and repositories cloned from GitLab - so it is created readable only by you (0700).
A bare-repos directory created by an older version keeps its mode; tighten it with chmod 700 "${GLCI_HOME:-$HOME/.glci}/bare-repos".
Two things guard what ends up in it:
- An entry is only stored once its objects have been accounted for. glci builds the copy in a staging directory, checks it, and moves it into place in a single step, so an interrupted preparation leaves no entry rather than a damaged one. The usual shallow copy is walked for missing objects; on the rare full-clone fallback the repack that path already performs is that walk, and a repack that fails means the repository is not stored. A repository that is shallow, or whose objects are borrowed from the developer’s own checkout, is never stored either — both work now and break later.
- A stored copy that cannot be used is rebuilt, not served. Anything empty, unreadable, damaged, or not a repository at all is discarded and replaced by a fresh clone from the project.
An entry is keyed on the commit alone, but it holds the branch of the run that first stored it. A later run can reach the same commit on another branch, for example after git checkout -b feature with no new commit. That run’s copy therefore gets the branch you have checked out in place of the stored one, plus the default-branch alias, which is exactly what a fresh clone would carry. In the default context, where $CI_COMMIT_BRANCH is the branch you have checked out, jobs can fetch origin/$CI_COMMIT_BRANCH, and a branch you deleted since the entry was stored is not advertised. With a detached HEAD there is no branch to use, so the copy keeps the stored one, even if you have deleted it since. If the copy cannot be given your branch, glci clones from the project instead and keeps the entry (see Troubleshooting).
Concurrent access to one project’s entry is coordinated through ~/.glci/bare-repos/{project}.lock, so that a pipeline reading an entry cannot have it evicted underneath it. Readers share the lock and do not block each other; replacing or discarding an entry takes it exclusively. A reader holds the lock while it copies out of the entry, which is a fast local hardlink clone; building and checking a new entry happens outside the lock entirely. Failing to take the lock is never fatal — glci falls back to cloning from the project.
Entries are never reclaimed on age: a project keeps its single entry, and its subdirectory and lock file remain even if the project itself is deleted. glci system prune clears the whole directory, locks included - with the daemon stopped, so no pipeline is preparing or serving a repository from it: prune stops an idle daemon first and refuses while one runs a pipeline.
The mock server’s base cache#
The persistent mock server keeps a second cache of its own, a bare repo per project in the mock container’s temp directory that lasts as long as the mock does, so a pipeline does not have to upload a repository the mock already holds. It keeps one entry per project: the commit the last full upload served, before any dirty-mode overlay. When the next pipeline of the project starts on the same commit, the mock clones that entry instead of receiving an upload. A clean checkout reuses the entry as it is. In dirty mode, only the objects of the uncommitted-changes commit are sent, and the mock adds them on top.
Both requests name the commit the pipeline checked the entry for. Another pipeline of the same project can replace the entry between that check and the request, and the mock then refuses the request instead of building on a commit the pipeline never saw. The pipeline falls back to a full upload, which also puts its commit back in the entry. A full upload from a dirty-mode run still caches the clean commit beneath the overlay, so a later clean run is not served the earlier run’s uncommitted changes.
The entry is keyed on the project and matched on its commit. Neither changes when the default branch does, for example after git remote set-head origin -a between two runs, or when you switch to another branch at the same commit. The pipeline therefore also sends the branches its own repository has at the served commit and the one its HEAD names. The reused repository is given exactly those, rather than the ones stored in the entry, so it advertises what a full upload would. As with a full upload, a job that records origin/HEAD (git 2.47 or newer, see Context simulation) agrees with $CI_DEFAULT_BRANCH.
Every request serving the pipeline’s own repository, a full upload, a reuse or an overlay, also names the ref the pipeline runs on (refs/heads/<branch>, or refs/tags/<tag> for a tag pipeline). The mock adds it to the repository it serves for that pipeline, at the commit the pipeline serves, after any overlay (see Context simulation). Neither cache ever holds it: the daemon’s copy is never given it, and the mock’s entry is cloned from a full upload without it, so a later pipeline in another context is not served this one’s ref.
A merge request pipeline also names its target branch when the checkout has it and the served repository lacks it, or has it only as an alias of the commit under test (see Context simulation). The daemon writes a commit with that branch’s tree into its copy, without a ref, on a parentless commit with the tree of the checkout’s merge base of HEAD and the branch (the branch’s commit itself when the merge base has the branch’s tree), copying from the checkout only the objects the served tree lacks. It also writes the commit under test again with that merge base as its one parent (with --dirty, the commit the overlay is laid over, and the overlay commit on it), and hands the runner that commit. Neither is written when the merge base is the commit the served repository starts from, or, in a full clone, in its history, nor is the branch’s commit when its real tip is: the commits there are served as they are. A full upload carries the commits in its tarball. A reuse or an overlay sends them in the request’s pack, as the objects the base’s tree lacks, so a reuse costs a merge request pipeline a few commits and the files they change. The mock first moves every branch naming the served commit (and a detached HEAD) to the commit under test the request names (target_head), once it has checked that commit has the served tree and a parent in the target branch’s history, then adds the pipeline’s ref and refs/heads/<target>, and, as with the pipeline’s ref, keeps all of it out of the base cache, undoing the moves before it caches the repository. A target the served repository already has as an alias of the commit under test, the default branch in most merge requests, gets the same commit when your checkout’s branch has another tree: the request says so (target_alias=1), and the mock moves the alias, and with it the HEAD that names the default branch, to the commit, after adding the pipeline’s own ref, and only while another ref (that one or the checked-out branch) still names the commit under test. The daemon’s copy and its bare repository cache keep the alias, and the commit under test as it was, and the mock puts both back before it caches the repository.
The daemon and the mock server image can be different glci versions. A mock server older than the daemon ignores the commit, the branches, the pipeline’s ref and the merge request’s target branch, so it builds on whatever its entry holds and serves no ref the checkout lacks, as before. One that serves the target branch but predates target_alias refuses to move the default branch, a name its copy has at another commit, and serves it as the commit under test, as before. One that predates target_head does not move the commit under test onto the target branch’s history, so jobs fail to get their source, the runner being asked for a commit no ref names, until the mock server is upgraded. One that refuses the target_head commit, which only a daemon bug makes it do, has the daemon serve the repository again without it, the commit under test as it is and checked out as such, and warn in its log. The daemon still asks the runner to fetch the pipeline’s ref by name (see What the runner fetches), so when the checkout lacks that ref (--context branch= or tag=, --mr-source, or a detached HEAD named after a remote branch), jobs fail to get their source until the mock server is upgraded. A daemon older than the mock server does not name the commit it checked, so the mock refuses every reuse, and each pipeline uploads its repository in full until the two match again.
Mock server API#
The mock server (pkg/mockserver/) is the central hub. It implements the subset of the GitLab API that gitlab-runner needs, plus infrastructure services and an internal control API consumed by the daemon.
GitLab runner API#
These endpoints are consumed by the runner, which thinks it is talking to a real GitLab instance:
| Endpoint | Purpose |
|---|---|
POST /api/v4/jobs/request | Token-routed job dispatch — each job is routed to the runner presenting its unique HMAC-derived token |
PUT /api/v4/jobs/{id} | Job state updates (running/success/failed) |
PATCH /api/v4/jobs/{id}/trace | Trace output chunks streamed in real time |
POST /api/v4/jobs/{id}/artifacts | Artifact upload (multipart) |
GET /api/v4/jobs/{id}/artifacts | Artifact download for needs:/dependencies: |
GET /api/v4/personal_access_tokens/self | Token validation for glab auth login --job-token |
POST /api/v4/projects/{path}/releases | Release creation |
PUT /api/v4/projects/{id}/packages/generic/... | Generic package upload |
GET /api/v4/projects/{id}/packages/generic/... | Generic package download |
GET /api/v4/projects/{path}/repository/tags/{tag} | Tag info lookup |
GET /api/v4/projects/{path}/releases/{tag} | Release info |
POST /api/v4/projects/{path}/releases/{tag}/assets/links | Release asset link creation |
Infrastructure services#
| Endpoint | Purpose |
|---|---|
GET /{path}/info/refs | Git smart HTTP ref advertisement (dynamic path per pipeline) |
POST /{path}/git-upload-pack | Git smart HTTP pack data |
PUT /cache/{key} | S3-compatible cache upload (AWS Signature V4 auth) |
GET /cache/{key} | S3-compatible cache download |
HEAD /cache/{key} | S3-compatible cache existence check |
GET /cache | S3 GetBucketLocation (region detection) |
/v2/* | OCI container registry (embedded, see Embedded Registry) |
Internal API (daemon to mock server)#
These endpoints are consumed by the daemon to manage pipelines. The mock server serves them only on a control listener bound to loopback inside its container (127.0.0.1:39740, or 39741 when mock_server_port is 39740). The port is never published, so the daemon reaches it with docker exec <mock> glci internal proxy[-session], which runs in the container’s own network namespace. Job containers, runners and anything on the host or the bus network reach only the API listener (mock_server_port), which answers every /internal/* request with 403 Forbidden. So a job script that only has the network can’t queue or cancel jobs, replace the pipeline secret, or change the /internal/status ground truth that crash recovery trusts. Refusals are logged in the mock server’s log, at most once a minute. No shared secret is involved, so the daemon has nothing to persist across a restart or keep out of logs. The boundary is the mock container’s network namespace: a job that can drive the container engine (the host’s engine socket mounted into it) or break out of its container can docker exec into the mock like the daemon does. Jobs run privileged by default so docker:dind services work, and a privileged container on a rootful engine is not a strong boundary.
| Endpoint | Purpose |
|---|---|
POST /internal/config | Set pipeline-wide configuration (git_url_path claims the pipeline’s URL path, 403 when it isn’t the pipeline’s to claim; see below) |
POST /internal/pipeline | Register a new pipeline (multi-pipeline routing) |
DELETE /internal/pipeline/{id} | Tear down per-pipeline state, and unregister the git repos at the URL paths the pipeline owns |
POST /internal/queue-job | Queue a job for dispatch to runner |
POST /internal/cancel-job | Cancel running/pending jobs for a pipeline (or a single job) |
POST /internal/register-runner | Register a project runner for tag-based dispatch |
POST /internal/unregister-runner | Unregister a project runner |
POST /internal/upload-git-repo | Upload bare git repo as tar.gz (simulated_ref, a refs/heads/ or refs/tags/ name, adds the pipeline’s ref at the served commit, or is ignored with a warning when it cannot be added; target_ref and target_sha add a merge request’s target branch, a refs/heads/ name at a commit the tarball carries without a ref, likewise ignored with a warning when it cannot be added; with target_alias=1 the name is an alias of the served commit, the default or checked-out branch as the target of a merge request, which is moved to that commit instead while another ref still names the served commit; target_head, beside them, is the commit under test on the target branch’s history, which every branch at the served commit (and a detached HEAD) is moved to first; with it, a malformed target_ref/target_sha/target_head is 400 rather than ignored, as is a tarball with no commit, or no such commit with the served tree, one parent and history shared with the target; the base cache is filled without any of it, the alias and the moved branches put back) |
GET /internal/git-repo-sha | Get the cached base SHA for a project path (the clean commit, before any dirty overlay) |
POST /internal/reuse-git-repo | Reuse git repo from a previous pipeline (base_sha must match the cache, else 409; branch and default_branch set the served branches and HEAD; simulated_ref as for the upload, but 400 when it is not a refs/heads/ or refs/tags/ name; target_ref, target_sha and target_head as for the upload, the commits’ objects in the body, 400 when they are not a refs/heads/ name and full object names together, target_alias is given other than as 1 beside them, or the target_head commit cannot be served) |
POST /internal/apply-git-overlay | Apply incremental overlay to git repo (same base_sha, branch, default_branch, simulated_ref and target_ref/target_sha/target_alias/target_head rules, the pipeline’s ref naming the overlay commit, or the target_head commit standing in for it, and the delta carrying the target branch’s commits too; the delta must build on base_sha) |
POST /internal/artifact/{jobID} | Inject reused artifact data (offset appends a chunk, total pre-allocates) |
GET /internal/artifact/{jobID} | Retrieve artifact data after job completion (offset/limit read one chunk, at most 64 MiB) |
DELETE /internal/artifact/{jobID} | Drop a stored artifact (cleans up a partial injection) |
GET /internal/trace/{jobID} | Retrieve complete trace for a job |
GET /internal/events | Hybrid binary/JSON event stream |
GET /internal/status | Ground-truth job state per job ID: state, exit code, the runner’s failure reason, whether it was cancelled, and the job it was queued for (crash recovery) |
GET /internal/health | Health check |
GET /internal/cache/keys | List all cache keys |
GET /internal/cache/get/{key} | Retrieve cached entry |
PUT /internal/cache/preload/{key} | Preload cache entry |
GET /internal/releases | List releases created by pipelines |
GET /internal/packages/keys | List generic package keys |
GET /internal/packages/get?key={name}/{version}/[{path}/]{filename} | Retrieve generic package |
POST /internal/push-through-config | Set push-through mirror configuration |
GET /internal/registry-stats | Registry storage statistics |
POST /internal/registry-clean | Clean registry blobs |
Every URL path the mock serves a repo at has one owner: the pipeline whose /p<ID>/ prefix the path sits under. Only the owner can register a repo there, and only the owner’s DELETE /internal/pipeline/{id} unregisters it:
- A config call (
git_url_path) claims a path under the prefix of the pipeline or of one of its ancestors. It can’t claim any other path, so no pipeline can take a path before its own pipeline configures it. A child pipeline configuring its root pipeline’s path shares the path without owning it. When the child is torn down, the repo stays for the root’s jobs, and the child can’t register a repo over it. - An upload, reuse or overlay names the pipeline it registers for in
owner_pipeline_id. A request without one speaks for the default pipeline. The first registration under that pipeline’s own prefix claims the path, so the daemon can upload a pipeline’s repo before its config call. A submodule or a triggered project’s repository is claimed the same way. A registration anywhere else is served, but nobody owns it, so only stopping the mock removes it. - Every route, config included, answers
403at a path another pipeline owns. Reuse and overlay keep409for a base cache that moved. - A pipeline that hasn’t configured a path has none. Only the default pipeline falls back to
/repoand can configure any path. A new pipeline’s first config call never moves the repo served at/repo.
Docker exec transport#
The daemon communicates with the mock server container exclusively through docker exec, which enables remote Docker daemon support (TCP via DOCKER_HOST, Docker contexts, SSH tunnels, cloud Docker).
Three transport implementations exist in pkg/daemon/transport.go:
| Transport | How it works | Used for |
|---|---|---|
httpTransport | Direct HTTP client | Unit tests with in-process mock server |
execTransport | One-shot docker exec <container> glci internal proxy <METHOD> <PATH>, which calls the mock server’s loopback control listener | Long-lived streaming (/internal/events) |
persistentExecTransport | Long-lived docker exec -i <container> glci internal proxy-session with binary framing, to the same control listener | All control-plane requests |
The persistentExecTransport keeps a single subprocess alive, multiplexing all requests over shared stdin/stdout with the muxproto binary protocol. This avoids the overhead of spawning a new docker exec for every API call.
Relay proxy for cross-machine Docker daemons#
When a named runner targets a Docker daemon on a different machine (docker_host or docker_context pointing to a non-localhost address), the host gateway its containers see routes to the remote machine’s own host — not back to where the mock server lives. glci therefore deploys a relay proxy container on the remote daemon, published on that machine’s port 39741, which bridges HTTP requests back through docker exec. Job containers keep using the ordinary extra_hosts entry (glci-mock → that daemon’s host gateway), which now lands on the relay’s published port; the runner container carries the same entry, so it reaches the relay the same way.
How it works:
- The daemon starts a
glci-proxy-*container on the remote daemon using the resolved glci image — normally the registry-qualified tag, sinceglci:localonly exists on the machine that built it — connected to the runner’s bus network with theglci-mocknetwork alias - Inside the container,
docker exec -irunsglci internal relay-proxy --port 39741, which starts an HTTP server - The runner and its job containers reach
glci-mock:39741through theirextra_hostsentry — the remote host’s gateway, where the relay container’s port is published (on the bus network theglci-mockalias resolves to the relay too) - The relay serializes each HTTP request into a muxproto binary frame and writes it to stdout
- On the daemon machine,
mockRelayLoopreads frames from thedocker execstdout pipe, forwards them as HTTP to the local mock server, and writes muxproto responses back to stdin - The relay reads the response frame from stdin and returns it as an HTTP response to the job container
All HTTP headers (including Job-Token for authentication) are forwarded through the relay chain. The relay serializes concurrent requests through a mutex since the muxproto pipe is single-threaded. No direct TCP connectivity is needed from the remote machine back to the daemon host.
Muxproto binary protocol#
pkg/muxproto/ implements a length-prefixed binary protocol for multiplexing HTTP-like request/response pairs over a byte stream:
Request: int64(methodLen) method int64(pathLen) path int64(ctLen) contentType int32(headerCount) [int64(keyLen) key int64(valLen) val]... int64(bodyLen) body
Response: int32(statusCode) int64(ctLen) contentType int32(headerCount) [int64(keyLen) key int64(valLen) val]... int64(bodyLen) body
All integers are big-endian. Max frame size is 1 GB; a body that would exceed it is rejected rather than truncated, so a partial payload never reaches the peer looking complete. Payloads that legitimately outgrow a frame — artifact archives, in particular — are transferred in 32 MiB chunks over /internal/artifact/{jobID} using offset/limit query parameters. The transport auto-restarts on stream corruption.
Event streaming#
The mock server emits events on /internal/events as a hybrid binary/JSON stream:
- Control events (
job_result,job_dispatched) are JSON lines - Trace data uses a binary frame format to avoid JSON overhead for high-volume output:
\x00 | uint64(pipelineID) | uint64(jobID) | uint32(offset) | uint32(dataLen) | data
Both event types flow on a single FIFO channel per subscriber (buffer 4096), so a job_result never overtakes an earlier trace frame. Trace drops are tolerated and reconciled via GET /internal/trace, attempt by attempt: each retry attempt runs under a job ID of its own, so before a retry starts, the daemon reconciles the attempt it replaces under that attempt’s ID. A job that ends without a result (it timed out, or it or its run was cancelled) is reconciled too, before its trace is closed, and a timed-out job’s Job exceeded the timeout limit notice is written after the recovered output, so it stays the last line of the log. Control drops fall back to /internal/status polling. The daemon also polls /internal/status every 5 seconds as a safety net for results missed during event stream reconnection.
Each job’s trace writer is guarded by its own lock rather than the client-wide event lock, so one job’s slow writer no longer holds up the daemon’s SetJobTraceWriter / RemoveTraceWriter / FlushTrace calls for other jobs. It does not isolate the jobs themselves: the event stream is read and dispatched on a single goroutine, so a writer blocked on disk stalls frame delivery for every job until it returns, whichever lock guards it. Two things depend on the per-job lock. The reconciliation reads its position after the fetch instead of carrying a copy across it, so frames the stream delivers while the request is in flight aren’t written to the trace file a second time. And unregistering a writer waits for any write already in flight, so the executor’s close cannot race the event-stream goroutine — a write landing on a closed trace file would still be published to the event bus, reaching live viewers but never disk.
The daemon tracks that position using each frame’s absolute offset, in the same coordinate space GET /internal/trace serves, rather than by summing the lengths of frames it received. A sum cannot express a hole, and the bus drops whichever frame is publishing when a buffer fills — not necessarily the last one. Reconciliation therefore resumes from the first byte the writer is missing: the gap gets filled, and the bytes after it are written twice, the same trade the trace handover makes.
EventBus#
The daemon’s EventBus (pkg/daemon/eventbus.go) manages in-memory event storage and streaming for CLI consumers:
- Two-tier storage: Status events (
stage_start,job_status,warning,pipeline_done, and every other type butjob_logandjob_variables) are kept permanently.job_variablesevents go to live subscribers only and are never kept, since they carry unmasked values. Log events (job_log) are bounded by byte size (default 10 MB) with slice compaction. - SubscribeWithReplay: Atomically returns replay history and registers a subscriber under a write lock, preventing event loss between replay and subscription.
- Unbounded subscriber queues: Each subscriber gets an
eventQueuebacked by a mutex-protected slice and a drain goroutine. Publish never blocks and never drops events. The drain goroutine feeds a 64-element output channel the consumer reads from.
Trace handover: disk before bus#
A client attaching to a running job (GET /api/logs/{pipelineID}/{jobName}) subscribes, sends the job’s trace file as a snapshot, and then streams live events, discarding those stamped strictly before a cutoff so the snapshot isn’t repeated wholesale (an event stamped exactly at the cutoff is kept, since a coarse clock can collapse the two readings and a duplicate beats a drop). Two rules keep that handover lossless:
history.TeeWriterwrites each trace line to the file before publishing it to the bus (the file is deliberately unbuffered, since the reader snapshots it withos.ReadFile).- The handler stamps the cutoff before reading the file, not after sending it.
Together these guarantee that a line missing from the snapshot is stamped after the cutoff and therefore survives the filter. The residual race runs the other way — lines appended while the file is being read are in the snapshot and pass the filter, so they are displayed twice — which is the intended trade. When the pipeline finishes while the snapshot is in flight, the handler re-reads the trace and emits the tail before returning on the done check.
Scheduler#
The scheduler (pkg/scheduler/) provides DAG-aware concurrent job dispatch with resource_group support. It dispatches each job as soon as its dependencies are satisfied; how many run in parallel is governed by the gitlab-runner concurrent setting, not the scheduler.
Scheduling modes#
| Mode | When used | Behavior |
|---|---|---|
| Stage-based | Jobs without needs: | All jobs in a stage run in parallel. Next stage starts when all jobs in the current stage complete. An unplayed non-blocking manual job is not waited for: one with allow_failure: true, which a bare job-level when: manual defaults to. A blocking one (allow_failure: false or the exit_codes: form) holds every later stage-based job. |
| DAG | Jobs with needs: (even empty needs: []) | Job starts as soon as all its declared dependencies complete, regardless of stage boundaries. One that was skipped, or is an unplayed non-blocking manual job, decides the job at once, without waiting for the others (see Skip logic). needs: [] means no dependencies — start immediately. |
| Mixed | Pipeline has both types | DAG jobs follow their needs:; stage-based jobs wait for all prior stages (except unplayed non-blocking manual jobs). |
Optional needs#
needs: optional: true is resolved when the plan is built, matching how GitLab resolves it when the pipeline runs. A need whose target is not in the pipeline — excluded by its rules:, declared in a stage that stages: does not list, or never declared at all — is dropped from the dependent’s needs:, and the dependent runs as though the entry had never been written.
A job whose every need was dropped this way stays in DAG mode with no dependencies, so it starts immediately rather than falling back to stage ordering, and it downloads no artifacts from preceding stages. That matches GitLab, where a job’s scheduling type is fixed by whether the needs: key was written at all, never by whether any target survived.
compile:
stage: build
rules:
- if: '$COMPILE == "true"' # unset, so compile is not in the pipeline
unit_tests:
stage: test
needs:
- job: compile
optional: true # edge dropped; unit_tests runs
The dropped edge is not drawn in glci show or glci jobs, which render the plan; GitLab’s pipeline graph drops the same link. The TUI draws the plan too, so the edge is absent from its graph and its job detail pane, in Browse Pipeline and during a live run. glci merged also shows the needs: as written, since it reports the merged config rather than the plan.
In --json output a job whose needs were all pruned is indistinguishable from one that never declared needs: — both omit the field — even though the two schedule differently. That is not new: an explicitly written needs: [] has always serialised the same way.
An optional need on a job that is in the pipeline is an ordinary dependency: if that job is skipped, the cascade applies as usual.
A need without optional: true on a job that rules: leave out is a pipeline GitLab refuses to create: a push shows a failed pipeline with the error and no jobs. glci refuses it the same way when it plans, before any job starts, with GitLab’s message:
CI configuration is invalid:
'unit_tests' job needs 'compile' job, but 'compile' does not exist in the pipeline. This might be because of the only, except, or rules keywords. To need a job that sometimes does not exist in the pipeline, use needs:optional.
glci run (including a downstream pipeline, which fails its trigger job, and a resume after a crash), glci show, glci jobs and the TUI preview all refuse it. Which jobs exist depends on rules:, so the verdict depends on the context: the same config can plan as a tag pipeline and be refused as a branch push. glci lint evaluates no job rules and does not report it, as GitLab’s own lint does not without a dry run. Every job in the pipeline is checked, not only the ones --job, --stage or a preset select, since GitLab refuses the pipeline as a whole. A job that rules: leave out is not checked itself, and a manual job is part of the pipeline whether or not anyone plays it, so needing one is fine. Each shard of a parallel: target is checked on its own, under its shard name ('test' job needs 'build: [gcp]' job, ...). One case is not checked yet: a need that picks shards with parallel: matrix:, which glci does not resolve, so it waits on every shard of the target. If rules: leave out a shard it never picked, the dependent stalls and fails the pipeline instead.
Job lifecycle states#
Jobs move through these states: pending -> running -> done (or skipped). Manual jobs (when: manual) start in a separate manual state and move to pending only when triggered.
The run ends when nothing is running and nothing else can start. Each job still waiting then gets a terminal outcome. A pending job waiting on an unplayed manual job is skipped, and a manual job that was never played stays manual. Neither fails the pipeline. GitLab would instead keep the waiting jobs created and show the pipeline as blocked, as Skip logic describes. A job waiting on something that can never finish is stalled: a needs: target not in the pipeline, or another stalled job, whether it waits through needs: or an earlier stage (a needs: cycle would be one too, but the planner refuses a cycle before the run starts). A stalled job is reported as failed, with the reason in its own trace, and so is the pipeline; pipeline_done’s error names what the stall comes down to. A trigger job whose downstream pipeline stalls fails too, whatever its strategy:, as GitLab fails a trigger job whose downstream pipeline it could not create. A cancelled run stalls nothing: the jobs it never dispatched are skipped.
A job is processed once, the first time its prerequisites are met, as GitLab processes a job only while it is still created. From then on the scheduler treats its prerequisites as satisfied. Playing a non-blocking manual job of an earlier stage makes it an ordinary job of that stage, which later stages that have not been reached yet wait for, but it never re-holds a job already past its stages, such as one waiting for its resource_group. A play does bring back skipped jobs, as GitLab’s ResetSkippedJobsService does: every skipped job that needs the played job, directly or through other needs, and every skipped job of a later stage is decided again. One skipped only because the manual job was unplayed now waits for it; one skipped for another reason, such as a failed prerequisite, is skipped again.
Skip logic#
Each job is decided by its own prerequisites, as GitLab’s ProcessBuildService decides it, never by whether the pipeline as a whole has failed. A stage-based job’s prerequisites are every job of the earlier stages; a DAG job’s are the jobs in its needs:. When they are all complete, or, for a DAG job, as soon as one of its needs is skipped or is an unplayed non-blocking manual job, the job’s when: either accepts their status, and the job runs, or the job is skipped:
when: | Stage-based job runs when the earlier stages | DAG job runs when its needs |
|---|---|---|
on_success (default), manual, delayed | have no failed job | all succeeded |
on_failure | include a failed job | include a failed job and none was skipped |
always | are complete | are complete, or one was skipped or is an unplayed non-blocking manual job |
A tolerated failure (allow_failure) counts as success, and an unplayed manual job with allow_failure: true in an earlier stage is ignored. A DAG job that needs such a manual job sees it as skipped, as GitLab’s Composite status does with dag: true: an on_success, manual or on_failure dependent is skipped, and a when: always one runs, without waiting for a play. A manual job is counted this way only once it is reached, that is once its own prerequisites are met; before that it is waited for, as on GitLab, where it is still created. A failure outside a job’s prerequisites plays no part: one in a later stage, in the job’s own stage, or in a parallel DAG branch the job does not need neither skips its on_success job nor runs its on_failure one. The verdict is reached once and then stands: a job released while it waits for its resource_group still runs after a failure that arrives in the meantime. A skip stands too, unless a manual job that the skipped job needs, or one of an earlier stage, is played (see Job lifecycle states). An on_failure job whose earlier stages passed is skipped at once, so it does not hold the stages after it.
- Cascading skips: a DAG job whose need was skipped is skipped too, unless it is
when: always. It is decided as soon as that need is skipped, even while its other needs still run, so awhen: alwaysjob can start before them, as on GitLab. - Manual jobs behind a failure: by the same rule, a manual job is skipped when its prerequisites include a failure that was not tolerated, whatever its own
allow_failure, and stays playable after a failure elsewhere. A skipped manual job no longer holds later stages, so a laterwhen: alwaysjob still runs. A manual job played before its prerequisites completed is processed the same way. The verdict depends only on finished jobs and on which manual jobs were played, so a resumed pipeline reaches the same one. - Held by a blocking manual job: a stage-based job behind an unplayed blocking manual job (
allow_failure: falseor theexit_codes:form) never becomes ready. Once nothing else can run, glci skips every such job, and that skip is what ends the run. Every later stage-based job is held, not just the next stage’s. GitLab instead leaves those jobscreatedand shows the pipeline as blocked; the skip is how glci reaches a terminal state. A DAG job that needs an unplayed blocking manual job is held the same way and skipped by the same sweep,when: alwaysincluded. A manual DAG job whose need this skips is skipped with it. resource_group: only one job per resource group runs at a time
Authentication#
Pipeline-level security without a real GitLab instance:
- Pipeline secret: 32 bytes from
crypto/rand, generated per pipeline - Job tokens:
HMAC-SHA256(secret, jobID)— each job gets a unique token - Runner dispatch: job routed to the runner presenting the matching token (prevents FIFO dispatch races when multiple jobs are queued)
- Git auth: HTTP Basic with job token
- Registry auth: Docker-standard token auth
- Cache (S3): AWS Signature V4 with daemon-secret-derived credentials (stable across pipeline runs)
Crash recovery#
The daemon performs recovery on startup (pkg/daemon/recovery.go):
- Find recoverable pipelines: Scan
~/.glci/active-workdirs/markers, read execution state from~/.glci/projects/{key}/pipelines/{id}/execution.json, check if both mock and runner containers are still alive viadocker inspect. - Preserve resources: Build sets of container names, volume names, and network names belonging to recoverable pipelines.
- Clean orphaned resources: Remove this
GLCI_HOME’sglci-*containers, volumes, and networks (those with itsglci.homelabel) not in the preserve sets. Aglci-net-*orglci-bus*network any container, running or stopped, is still connected to is kept, as is one less than 15 minutes old or one the engine cannot be asked about, so this sweep leaves alone the networks another daemon on the same engine uses or is still setting up. Two windows remain: a setup that takes longer than 15 minutes before its first container connects, and a container connecting between the check and the removal (a running one makes the engine refuse the removal, and a bus network that vanished is recreated on connect). Unlabelled networks from older releases are left alone. Also remove these temp files a daemon that died left in the system temp dir ($TMPDIR, or/tmpwhen it is unset;%TMP%on Windows): the rendered runner config (glci-runner-config-*.toml, which holds the runner token, orglci-config-*.tomlfrom releases before 0.6.0), the synthetic include root of a trigger or of aci_config_pathpointing at another project (glci-child-root-*.tmp), and a dirty overlay’s temp git index (glci-dirty-index-*, and its.lock). Only a regular file at least 15 minutes old, and on Unix owned by this user, is removed, never a symlink or a directory: daemons with differentGLCI_HOMEs share the temp dir, and a younger file may be one another live daemon is still using. The sweep runs once more 15 minutes after start-up, so the files a daemon that crashed and was respawned at once left behind do not wait for a later start. Theregistry-certs-*directories older releases staged under thisGLCI_HOMEare removed too. - Finalize stuck pipelines: Mark pipelines without surviving containers as failed in history.
- Resume: Reconnect to containers via
docker exec, query ground-truth state viaGET /internal/status, re-parse the CI config — refusing the resume, and failing the pipeline, if it no longer parses or GitLab would reject it — then reconcile with persisted state and re-dispatch pending jobs. A manual job played before the crash but not yet dispatched is played again, since the re-parsed config still marks itwhen: manual. The jobs the scheduler had already released when a job was played are restored first, so a played job still running at the crash does not hold them back again, and the replay itself releases nothing the live run had not. A job still running at the crash keeps itsresource_group, so a pending job of the same group waits for it as it would have in the live run.
A job is reported running as soon as it is queued, before a runner has asked for it, so a crash in that window leaves a job the mock server still has queued. That job is not lost: the mock server hands it to the next runner that asks, and the resumed pipeline waits for its result as it does for a job that was already running, for up to the job’s timeout, as in a live run. There is nothing to rebuild for it, so its output is appended to the job’s log from its first byte. A job the mock server has no record of, or holds cancelled before any runner took it, will never report a result and is failed.
A job using retry: resumes on the attempt it had reached, with the retries it had left. Every attempt runs under a job ID of its own and is recorded only after it is queued, so a crash between queuing attempt N+1 and recording it leaves attempt N recorded as running in the execution state, while the mock server holds it failed and attempt N+1 queued. GET /internal/status lists each job ID under the name of the job queued under it, so the daemon takes the newest ID under the job’s name as its current attempt and waits for that one rather than failing the job. The IDs before it are the job’s earlier attempts, which is how GitLab counts a job’s retries too, so they also say how many retries are left. An attempt that fails after the resume is retried if the job’s retry: allows another, and so is one that failed while the daemon was down. A retry: 2 job whose second attempt was in flight at the crash gets one more retry if that attempt fails; one whose first attempt failed during the downtime still gets both. A cancelled attempt is not retried, and glci stop <job> stops a job the resumed pipeline is waiting on as it stops any other. Nor is an attempt the runner ended for running out of time (failure_reason: job_execution_timeout, which the mock server keeps with the result): in a live run the daemon’s own timeout, counted from when the attempt was queued, fails such an attempt first, and that is never retried. The job’s log is rebuilt from every attempt’s trace in turn, the way the live run writes them, so the attempts before the crash keep their output; the notices glci itself wrote between them, such as a timeout notice, are not in the mock server’s traces and are not restored. A retry override in .glciconfig.toml counts, as it does in the live run.
When a resumed pipeline finishes, or its resume is refused, only its status and finish time are written to its glci history entry. The ref, commit, stages, config file and inputs recorded when it started stay as they were, and so does a child pipeline’s link to its parent. The same rule applies when a child or cross-project pipeline finishes.
A job that was running when the daemon died has its trace rebuilt from the mock server’s copy rather than appended to. The mock container outlives the daemon and keeps collecting the job’s output the whole time nothing is listening, so its copy runs ahead of what the daemon managed to persist, and the difference — everything printed during the downtime — belongs in the middle of the log file rather than at the end. Both outcomes are covered: a job that finished while the daemon was down has its whole trace restored as the pipeline is reconciled, and one still running is restored up to its last complete line, with the live stream continuing from the point the mock server had reached. A job killed before it printed a whole line has nothing to rebuild the file from, and carries the incomplete line forward into the live stream instead. The rebuilt file is written beside the original and renamed over it, so a reader sees either the old file or the finished one, never a half-written prefix. Leftovers from an attempt that was itself interrupted between the write and the rename are swept before the next one starts, so repeated crashes cannot accumulate a copy of the trace per attempt.
Every rebuild finishes before the daemon accepts connections. The recovered middle goes to the log file and deliberately never to the event bus, so a client that attached while a rebuild was still running would snapshot the pre-rebuild file and then receive only live events, which start after the recovered bytes: the downtime output would be on neither side of the handover. Doing the rebuilds on the startup path is what keeps the disk-before-bus rule true across a crash as well as within a single write. It costs one bounded trace fetch and one file rewrite per resumed job before the socket opens.
Handing the live stream over to the rebuilt file leaves a gap about one frame wide: the runner posts a trace update about once a second, and the fetch that rebuilt the file takes longer than that, so a frame usually arrives while no writer is registered and is dropped. The daemon closes that seam by reconciling against the mock server’s copy as soon as the writer is registered, retrying a few times, because a seam left open is a hole the stream cannot close: every later frame begins past it, and the reconciliation at the end of the job then recovers from the hole rather than from the end, writing everything printed after the resume to the log a second time. A seam that could not be reconciled is logged as a warning.
Offsets throughout are counted in raw trace bytes, the coordinate space the mock server serves and the event stream’s frames index into. The log file holds parsed, colourised output — a different measure entirely — so its size can never stand in for one of these offsets. When the mock server’s copy cannot be read, or would replace a surviving log with nothing, the file is left as the crash left it and the job’s trace is published to the event bus alone.
Execution state is written atomically (temp file + rename) on every job state transition and every interactive play of a manual job. It contains container names, job states, runner tokens, pipeline secret, the manual jobs played during the run, the original StartPipelineRequest for re-parsing CI config during resume, and the commit and ref preparation told the runner to check out. The commit cannot be re-derived on resume: preparation serves a rewritten repository — the shallow clone becomes a freshly timestamped parentless commit, and dirty mode (the default) stacks the uncommitted tree on top of it — so the served commit is never CI_COMMIT_SHA, and recovery reuses the mock container without rebuilding the repo. The ref is persisted alongside it because it is read from the working tree too, and drifts if the branch moves while the daemon is down. So is a merge request pipeline’s CI_MERGE_REQUEST_DIFF_BASE_SHA as its jobs see it, a commit of the served repository that the working tree has no name for.
CI config parsing#
glci includes a full offline .gitlab-ci.yml parser as the primary parsing path (pkg/config/). It implements GitLab’s processing pipeline in Go:
- Load YAML with
yaml.Node-based parser preserving!referencetags. A!referenceGitLab cannot read is refused here — one that is not a non-empty list of segments GitLab’s YAML 1.1 reader takes for strings, one read through an alias, one used as a merge (<<:) source, a mapping key or a document root — and so is a document root that is not a mapping. A scalar value GitLab’s YAML 1.1 reader takes for a boolean is one here too: an unquotedyes,no,on,off,trueorfalsein any letter case, or one of those words under a tag Psych types by its value, such as!!bool; untagged and quoted, in a block or tagged!!str, it is a string. A number is likewise what GitLab’s reader takes for one, not what YAML 1.2 does: an unquoted0x1F,0b11,010(octal 8),1_000,1,000or1:30(base 60, which Psych reads as 5400) is an integer, and1e3or0o17a string; quoted, each is the string written. A mapping key is typed the same way: one GitLab reads as a boolean is marked, so that onceinclude:,extends:and!referencehave put every block where GitLab validates it, a job, variable or jobinputs:entry it names is refused in GitLab’s words, right after step 5; everywhere else, such as under a hidden key, it is then namedtrueorfalse, its Rubyto_s, unless the same mapping also holds that text as a quoted key, which wins. Aspec: inputs:key is checked where the header is read. Every mapping that is a list item keeps its declared key order until step 5, sincematrix: !reference [...]can make any list’s items a job’s matrix entries, whose order names the shards. Merge keys (<<:) apply where they stand, as GitLab’s Psych applies them: a merge overwrites the keys written before it, a key written after it overwrites the merge, and of a merge list the earlier mapping wins. A merge of a mapping still being read, its own anchor or an ancestor’s, takes the pairs written in it before, as Psych does, so.a: &a {x: 1, <<: *a}is{x: 1}. A key written twice in one mapping keeps its last value, as Psych keeps it, and an input written twice keeps the place it was first written; aspec:header and aspec: include:file are read the same way. Where a header is read, only the header is: a fault elsewhere in an included file is the loader’s to refuse, in its own words, not asparsing spec.inputs. Aliases are expanded with yaml.v3’s guards: an anchor whose value holds an alias to itself, a document past the excessive-aliasing ratio yaml.v3 enforces, and a tree nested deeper than 10,000 levels are refused - Resolve and interpolate placeholders —
$[[ inputs.key ]]in each file once, against that file’s ownspec:header and before its includes are expanded (a file with no header keeps its blocks as written, and the root’s inputs never reach an included file), substituted into the parsed YAML rather than the raw text and applying any functions piped after the key, and$[[ component.name ]],reference,versionandshain a component’s own body before its nested includes are fetched, so a component that pins a child to its own release (component: .../child@$[[ component.version ]]) resolves against the version the component was included at.nameandreferencecome from the address;versionandshaare looked up through the Releases and Commits APIs, once per component and only when a file reads them. The component context is opt-in, as on GitLab: a value is substituted only where the file’sspec:header lists its key undercomponent:(Header::Spec defaults that list to empty), only in the body after the header, and only in a file actually reached through acomponent:include. A component’s nestedlocal:includes count as reached through it, since GitLab passes the component data down that path and resets it forproject:,remote:andtemplate:. A file that declares the key with no component context to read it from is an interpolation error, not a placeholder left to be used as a git ref. See component includes. An input whoseoptions/defaultcome fromrules:has them evaluated first; those rules see the other inputs and no CI/CD variables, matchingCi::Inputs::RulesEvaluator, and one input’s rule may reference another, so they are resolved in dependency order. An included file whose inputs do not resolve fails the parse rather than merging uninterpolated, which GitLab also refuses. So does an include entry that names an input its file does not declare, or that gives inputs to a file with nospec:header, with GitLab’s messages. The root file’s own--input/--inputs-filevalues meet the same two checks, since GitLab creates a pipeline by including its CI file with the pipeline’s inputs - Resolve all includes —
local:(disk),remote:(HTTP),template:(the raw file ingitlab-org/gitlab, at the tag of the instance’s release, read from the configured instance and, when that read fails, from gitlab.com, since GitLab reads templates from its own installation; or from[includes] templates_urlalone when that is set),project:(API),component:(API). Each entry’srules:are decided first, once per entry, as GitLab’sMapper::Filterdoes: the first matching rule keeps the entry unless itswhen:isnever, and no matching rule drops it, so a dropped file is never validated or read. In the top-level pipelineif:sees the simulated context’s predefined variables, then the CI/CD variables fetched from the API (onlyglci runand its crash-recovery re-prepare fetch them, before they parse; the CLI’s preview commands fetch none), then the local variable layers, but not the globalvariables:block; in a child or multi-project downstream pipeline it sees what the downstream’sinclude:locations expand against, the fetched CI/CD variables and the variables the trigger job forwards included, but not the downstream’s own globalvariables:block. A multi-project downstream’s predefined variables are the target’s own, as its jobs get them, not the upstream pipeline’s.exists:checks the project’s non-ignored files, or for an include inside aproject:orcomponent:file that project’s tree at its ref, listed through the API: a listing that fails (a token withoutread_api, a403/404, offline) leaves the rule undecided, and one that reaches its cap (20,000 files, or 200 pages of the tree API) makesexists:match, with a warning.changes:compares against the pipeline’s diff, a child pipeline’s against its parent’s; a multi-project downstream has no diff, sochanges:matches, whilecompare_to:is evaluated against the target’s tree. An entry’s invalid rules refuse the config before they are evaluated, as GitLab’sExternal::Rulesdoes:CI configuration is invalid: parsing CI config: resolving includes: include:rule .... Achanges: compare_to:that names no commit refuses it too, once the rule reaches it, withinclude:rules:changes:compare_to is not a valid ref. Inside aremote:ortemplate:file, nested include rules see no variables andexists:matches nothing, as on GitLab. A child pipeline’s include rules seeCI_PIPELINE_SOURCE=parent_pipeline, a multi-project downstream’spipeline, which neither a forwarded variable nor the parent run’s--env,--env-fileor presetenvoverrides (a project CI/CD variable or.glci.envdoes), as for the downstream’s job rules. A rule glci cannot evaluate (regexp:inexists:orchanges:,project:/ref:inexists:, anexists:in a tree that could not be listed) keeps its entry, with a warning, and an entry kept that way is dropped, with a warning, if its location is invalid or its file does not resolve, as GitLab may leave it out unread; a rule GitLab refuses inside the dropped file then refuses nothing. These warnings go to stderr, prefixedglci:, on a CLI parse (lint,jobs,show,variables,merged), to the daemon log, prefixeddaemon:, onglci run, and to the trigger job’s log for a downstream pipeline. Wildcards in the kept entries are then expanded and aproject:entry’sfile:list split into an entry per file, as GitLab’sLocationExpanderdoes, so each file is read against its ownspec:header; then$VARreferences are substituted (a wildcard a variable delivers to alocal:mapping is not expanded, as on GitLab: it is a path, solocal: $PATTERNholdingci/*.ymlfails as a missing file; a plain-stringinclude: $PATTERNis expanded before anything else, as GitLab’s normalizer does, so its wildcard is), then every location is validated for a.yml/.yamlextension (and atemplate:for GitLab’s.gitlab-ci.ymlsuffix), and only then is anything fetched — the order GitLab’s own mapper uses, which is why a bad extension is reported as one rather than as a missing file. Component version selectors (@~latest, and partial versions such as@2or@2.3) are resolved to the newest matching published release via the GitLab Releases API before fetching. A fetch answered with a web page, such as the sign-in page a redirect lands on, is refused rather than parsed as YAML, and is never cached. Includes are deduplicated within a parse and cached on disk under~/.glci/cache/includesacross parses — for an hour, or for as long as it keeps being used when theref:names a complete version such as1.2.3. Once a day the cache is swept: an entry neither fetched nor served for 30 days is removed (a pinned entry counts as used whenever a parse reads it), as are scratch files more than an hour old that an interrupted write left behind.glci system dfreports its size andglci system pruneclears it. A partial version is not pinned:@1.2selects the newest1.2.*, so what it names changes as versions are published. Every parse route shares that cache and the same GitLab credentials: the CLI (glci lint/jobs), the daemon’s pipeline prepare, crash-recovery re-prepare, and the parse of a child pipeline or cross-project trigger target. Entries are keyed by GitLab instance, so a project pointed at a self-managed host never reads another instance’s copy.project:andcomponent:entries are keyed by a fingerprint of the token they were fetched with too, so a file pulled with one credential is never served to a parse holding a different one (or none).template:entries, which are public, are keyed by their source instead:[includes] templates_url, or a fingerprint of the token the instance’s version was read with (none readsmaster); a copy read atmasteronly because the version or tag could not be read this time is not cached. - Resolve
extends:— recursive deep merge with circular/depth detection (10 levels max). A missing target is an error, as on GitLab, unless aninclude: project:/component:was skipped for want of a token in step 3: the target may live in that file, so a top-level parse then warns instead: the CLI’slint/jobs/show/merged, andglci run’s daemon prepare, which logs it to~/.glci/daemon.log.glci lintreports such a config as not fully verified; a downstream parse stays strict. A target that exists but is not a mapping is an error either way. The same holds for an absent!referencetarget in step 5 - Resolve
!referencetags — path lookup with cycle detection, sequence flattening. A path whose key exists but holdsnullorfalsecounts as not found, as on GitLab (!reference [".tmpl", "allow_failure"] could not be found), and it is an error even where an absent target is only a warning because an include was skipped: the key is written in the file, so a skipped include almost never accounts for it.stages:is the one exception: a referenced sequence is left nested there, because GitLab still has it as a single node when it subtracts the edge stage names in step 6 - Re-anchor edge stages —
.preand.postare stripped out ofstages:and re-added at the front and the back, sostages: [.post, build]still runsbuildbefore the.postjobs. The strip matches only top-level entries, mirroringGitlab::Ci::Config::Stages.wrap_with_edge_stages, whosestages - EDGEScompares elements of the list as written: an edge name nested inside a sub-list is not one of those elements, so it survives and keeps its position once the list is flattened.stages: [a, ['.post'], b]therefore runs.postjobs betweenaandbon GitLab, and does the same here - Apply
default:inheritance withinherit:control (true/false/[keys]) - Parse
workflow:rules withauto_cancel:support. They are evaluated later, at planning time, once the pipeline’s variables and git context are known — see workflow rules - Parse all job fields into enriched types (trigger, release, retry, environment, hooks, id_tokens, etc.)
- Expand
parallel:jobs —parallel: Nintojob 1/N…job N/N,parallel: matrix:into one job per permutation, enumerated with the first-declared matrix variable outermost (as GitLab does), which is what fixes each shard’s name and index. Each shard records its 1-based index and the shard total, which the runner emits asCI_NODE_INDEXandCI_NODE_TOTAL
Also handles: rules: changes: (git diff matching), rules: exists: (non-ignored file glob: tracked + untracked, minus .gitignore), YAML anchors/aliases, multi-document YAML (read as GitLab reads it: a spec: header and one content document, the rest ignored).
API-assisted mode (optional)#
Set GLCI_PREFER_API=1 to use the GitLab CI Lint API for YAML resolution. This requires a GitLab token but delegates include:, extends:, and !reference resolution to the server. The offline parser is the default because it requires no network access and handles the vast majority of CI configurations.
The two parsers back each other up. By default the Lint API is tried only when the offline parse fails and a token and project are configured; with GLCI_PREFER_API=1 the order is reversed. When both fail, the error reports both reasons whichever ran first — the offline one first, then GitLab Lint API also failed: … — because the two often fail differently (an include glci cannot fetch may be one GitLab rejects as content not found). The API reason is left out only when the API was never asked, or when it declined the config rather than failing on it (a root whose spec: has an include:, which only the offline parser resolves).
A local include that names a file outside the repository, or one reached through a symbolic link, is refused on both routes, and a refusal is never retried on the other one. It cannot be: the API-assisted route inlines local includes into the YAML before POSTing it, so the server never sees those entries and cannot reject them — which is how a refusal on the offline route once ended up sending the very file glci had just declined to read. Both routes refuse it now, so the no-fallback rule changes no outcome; it stops a settled answer being reported as though a fallback had been tried. See refusing a local include. The same holds for a config GitLab refuses for its YAML alone. A !reference it cannot read and a document root that is not a mapping are checked on both routes — in the root file and its local includes before anything is sent, in a fetched file once it is loaded. An include: entry that is neither a string nor a mapping is refused by the offline parser and left for GitLab to refuse on the API-assisted route, where the error then carries both reasons. An include entry’s inputs: that its file cannot take is also settled: an undeclared name, inputs for a header-less file, or an inputs: that is not a mapping. A local: entry carrying inputs: is inlined like any other local include, interpolated with those inputs, so both routes check it against the working-tree file. Either way the refusal is final. See a config refused for its YAML alone.
The content the API-assisted route POSTs is written from the YAML node tree, with local includes merged in: keys keep the order they were declared in (which names matrix shards, including a matrix GitLab only assembles from a !reference), each scalar keeps the quoting and tag that decide how GitLab’s YAML 1.1 reader types it (a plain on stays a boolean, 0o17 a string), !reference tags stay tagged, and aliases and merge keys are expanded so no anchor is separated from its aliases by the merge. Whatever an included file still includes — every entry not inlined: remote:, project:, template:, component:, a local: whose rules: glci leaves for GitLab (see below), a string or local: location still holding a $VAR glci could not expand — takes the place of the entry that included it in the root’s include: list, so GitLab merges those files in the order it would have met them; the inlined files themselves rank with the root’s own content, above every include left to GitLab. Before it is sent, $VAR / ${VAR} in the include: entries of the root and of each inlined file is expanded with the predefined variables of the simulated context and the local variable layers (not the global variables: block, and not a masked variable), once, after the file’s own input interpolation: the root is interpolated against its header before anything is inlined, and each inlined local file against its own header, with its entry’s inputs: and its defaults, before its entries are expanded. A local file with no header is inlined with its blocks as written. So GitLab resolves them at the commit glci simulates rather than at its default branch’s head. A variable glci does not hold is left for GitLab.
include: rules in the root and in each inlined file are decided by glci before the request, with the simulated context, as on the offline route: an entry whose rules do not pass is removed, and one whose rules pass loses its rules:, so a plain local: file is inlined and GitLab does not decide the rules again against its default branch. Three kinds of entry are sent unchanged, for GitLab to decide: one whose rules reference a masked variable, since a masked value never shapes the request; one whose rules glci cannot evaluate (regexp: in exists: or changes:, project:/ref: in exists:); and one whose rules: glci’s checker refuses, for GitLab’s lint to report. When the rules drop every entry of the root’s include:, the entries are sent anyway with their rules: replaced by [{when: never}]: GitLab still validates each entry’s shape (an unknown key, a project: without file:) but reads no file for it, as it does when its own rules leave no file. Include rules inside a file GitLab fetches (remote:, project:, template:, component:) are decided by GitLab’s lint against its default branch, not the simulated context. glci cannot see inside those files, so it warns once whenever the request sends such an entry, whether or not the file holds include rules.
Local files are always the working tree’s#
glci never lets a Lint API verdict on GitLab’s copy of a local file stand in for a working-tree copy that is broken. GitLab reads a local: entry from the project’s repository, at the default branch’s head (a lint request names no commit), so an entry the API-assisted route left for it would be checked against that copy, not the one in your working tree. So glci inlines every local file GitLab would read: a plain local: entry, one with inputs: (interpolated with them), and one whose rules: keep it in the simulated context (one they leave out is removed, and GitLab never reads its file). A file that does not resolve in the working tree is then refused before anything is sent, with the error naming the include, as glci merged refuses it.
Two kinds of entry stay entries: one whose rules: glci leaves for GitLab (rules that reference a masked variable, rules glci cannot evaluate, and rules glci’s checker refuses, as above), and one whose location still holds a $VAR glci cannot expand, which GitLab expands. glci resolves the files of the first kind (and what they include) in the working tree before it sends the request. Then it holds the working tree against the files the response’s includes: says GitLab read: every local file listed there was read from the default branch, since what glci inlined is never listed. A file of the project’s own (a local: nested in a project: or component: file is read in that project and skipped):
- that no entry left under
rules:names, such as one a$VARlocation expanded to, is checked as GitLab reports it, with theinputs:GitLab lists for it. If its working-tree copy does not resolve, the parse fails withthe Lint API read the default branch's copy of local include "sub/child.yml", and the working-tree copy does not resolve: .... - that an entry left under
rules:names: GitLab’s rules passed, so every file the entry names in the working tree is part of the pipeline, a wildcard’s other matches included. If any of them does not resolve (it does not parse, is missing, is reached through a symbolic link, which GitLab never follows, or itsinputs:do not fit its header), or GitLab read a wildcard match the working tree does not have, the parse fails withinclude local "child.yml" is under rules: the Lint API's verdict rests on the default branch's copy, and the working-tree copy does not resolve: .... The same holds for a wildcard entry written in a file glci inlined: it reaches GitLab in the root’sinclude:, where GitLab no longer leaves out the file it was written in, so a verdict that read that file’s default-branch copy is refused too. - whose working-tree copy resolves: the result stands, with the warning
include local "child.yml" is under rules: GitLab read it from the default branch, not your working tree, so its jobs and the Lint API's verdict on it come from that copy, since an edit in the working tree was not checked. It is printed on every parse that takes this route, whether or not the file differs from the default branch.
On the default route the offline error comes first, then GitLab Lint API also failed: checking the files the Lint API read: ...; under GLCI_PREFER_API=1 the offline parser is tried next and fails on the same file. Fix the working-tree file, or the rules glci leaves for GitLab.
An entry left under rules: that GitLab did not read is no part of GitLab’s verdict. GitLab evaluated its rules for the default branch, though, not for the context glci simulates, so when its working-tree copy does not resolve glci warns: include local "child.yml" is under rules: GitLab left it out on the default branch, so nothing checked its working-tree copy, which does not resolve: ....
When the response does not say which files GitLab read (an older GitLab), a file left under rules: that does not resolve in the working tree fails the parse, ending the Lint API did not report which files it read, so its verdict may rest on the default branch's copy. A file left under rules: whose header uses spec: include: cannot be checked this way: when GitLab reads it, the API-assisted route declines the config, as it does when an inlined file has one, and the offline parser resolves it.
Inlined files rank with the root’s own content, above every include left to GitLab, so a key a later remote:, project:, template: or component: file sets as well is the inlined file’s on this route, where GitLab merges the later file over it. That holds for every inlined local: entry, one with inputs: included.
An entry its rules: keep is not exempt from the location rules, on either route: GitLab reads and validates such a file, so a non-YAML extension is refused and a symbolic link is not followed, as for an entry without rules:.
API-assisted mode does not apply to downstream pipelines. A child pipeline’s config is a synthetic root glci merges from the trigger’s include files, and a cross-project target’s config is read from its checkout or, when it was cloned, from a tree of .yml/.yaml files extracted from its bare repo into a private temporary directory (the whole tree, so the target’s own include: local: entries resolve from its repository root), or — when its ci_config_path names another project or a URL — through a synthetic root that includes that location, the way GitLab reads such a setting — neither is a file the server can see, so linting it would have GitLab resolve the include entries itself against the committed copies in the repository and hand back a different pipeline. Child and cross-project configs are therefore always parsed offline, GLCI_PREFER_API notwithstanding. Their include: project:/component: entries are still fetched from the API as usual.
API Lint response — field inventory#
When using API-assisted mode, glci calls POST /projects/:id/ci/lint with include_jobs: true, dry_run: false. The API returns merged_yaml (fully resolved YAML), a jobs array, and an includes array listing every file it read, which glci holds against the local entries left for GitLab (see above). These fields are available from each source:
| Feature | In merged_yaml? | In jobs array? | Notes |
|---|---|---|---|
include: resolution | Yes (key removed) | N/A | Recursively merged |
extends: resolution | Partially (keys remain) | N/A | Values merged, key not removed |
!reference tags | Yes | N/A | Resolved to actual values |
rules: evaluation | dry_run only | dry_run only | Static returns ALL jobs |
needs: | N/A | Static mode only | NOT in dry_run mode |
image:, services:, variables:, artifacts:, cache: | Yes | No | Must parse from merged_yaml |
parallel: N / parallel: matrix: | Yes (unexpanded) | No | Must expand ourselves |
$[[ inputs ]] | Yes (expanded) | N/A | Component interpolation done |
$VAR expansion | No | No | Shell expands at runtime |
Daemon API#
The daemon runs as a background process and exposes an HTTP/JSON API over a Unix socket (~/.glci/daemon.sock). The CLI is the primary consumer. The socket is owner-only (0700), and the daemon refuses to start if it cannot restrict it.
| Endpoint | Purpose |
|---|---|
POST /api/start-pipeline | Start a pipeline (accepts the CI file path, variables and options; the daemon parses). If another pipeline is being prepared for the same directory, the request is queued (max depth 3) and the connection is held open until preparation finishes. Context cancellation dequeues the request. A refusal carries error; one over the CI configuration itself (it does not parse, GitLab would reject it, or GitLab would not create the pipeline in the run’s context) also carries error_kind: "config_invalid", with error holding the report glci lint prints, and answers 422 when the status line has not already gone out for a queued request. The CLI exits 1 on it and 2 on any other refusal. |
POST /api/cancel-pipeline | Cancel a running pipeline |
POST /api/cancel-job | Cancel a single job |
POST /api/trigger-manual-job | Trigger a manual (when: manual) job. A refused play answers 409 with error set to pipeline is being canceled, pipeline has finished or job is skipped behind a failed or skipped prerequisite, or 404 with job not found or not in manual state; a refused play never runs the job |
GET /api/pipeline-status | Pipeline status for a project |
GET /api/watch/{pipelineID} | Event stream for a pipeline (NDJSON) |
GET /api/logs/{pipelineID}/{jobName} | Stream job log output |
GET /api/registry-info | Registry connection info |
GET /api/registry-catalog | List all repositories and tags in the embedded registry |
GET /api/registry-manifest | Fetch a manifest by repo and ref (tag/digest) |
GET /api/registry-blob | Download a blob by repo and digest |
POST /api/registry-clean | Clean up registry data |
GET /api/active-pipelines | List all active pipelines and their job statuses |
GET /api/health | Daemon health check |
The daemon auto-starts on the first glci run and auto-stops after 30 minutes with no active pipelines and an empty embedded registry (set by [daemon] idle_timeout). A version guard auto-restarts it if the CLI/daemon build versions mismatch. It also resolves its container-engine endpoint once at startup and reports it via /api/health; a command whose shell selects a different endpoint gets a warning rather than a restart, since the daemon is shared across shells and projects.
On SIGTERM (what glci daemon stop sends) or SIGINT, the daemon cancels its running pipelines, stops its runner and mock containers, removes its bus network and stops accepting connections. It removes its socket and PID file just before the process exits. glci daemon stop --force sends SIGKILL instead, which skips all of this and leaves the containers running for crash recovery.
A stop that arrives before the daemon begins serving is handled the same way, and the daemon never serves. If it arrives while the daemon resumes pipelines left by a crash, the daemon resumes no further ones and does not record them as failed: they keep their execution state for the next start’s crash recovery. A stop that arrives before the daemon has written its PID file also skips starting the registry, but glci daemon stop cannot find such a daemon and reports daemon is not running; only a signal sent to its process reaches it.