Skip to content

feat(api): write agents' log batches to VictoriaLogs (part of #232) - #461

Merged
samuelmbabhazi merged 8 commits into
mainfrom
feat/232-logs-ingest
Nov 25, 2026
Merged

samuelmbabhazi merged 8 commits into
mainfrom
feat/232-logs-ingest

Conversation

@samuelmbabhazi

Copy link
Copy Markdown
Collaborator

Part of #232 (M6.1): the control plane's half of ADR 0029. It is stacked on #458 (the ShipLogs contract), which sits on #452 (the ADR). The agent's shipper is the other half, in its own PR. VictoriaLogs joins the Compose project in #460.

What changed

  • Gateway, ShipLogs (fleet/interface/log-stream.ts). It runs behind the shared mTLS and database identity guard.
    • Refusals:
      • with no log store configured: FAILED_PRECONDITION;
      • when the first frame is not LogsOpen with the node's current lease epoch, read through AuthenticateNode: FAILED_PRECONDITION;
      • when batches are not numbered 1, 2, 3, …: INVALID_ARGUMENT.
    • Acknowledgement. Each batch gets its LogAck only once the store has kept it. A failed write ends the stream with UNAVAILABLE and no acknowledgement, so the agent sends again from its cursor.
  • Welcome.logs is true only when a store is registered.
  • fleet/application/log-batches.ts is the hook the observability module registers on, as MetricsReports is for metrics.
  • observability:
    • Domain, domain/logs.ts, pure:
      • entries are bounded: at most 256 per batch, a container name in the agent's grammar, a valid time, a line of at most 16 KiB;
      • labels come from the node's placed allocations: org, project, env, app, instance (the replica), node and stream. A line of any other container is dropped, and no name the agent sent becomes a label;
      • a time more than 5 minutes from the control plane's clock is replaced by it;
      • a per-node byte bucket allows 512 KiB/s with bursts of 4 MiB.
    • LogsIngest: it registers only with a store, drops malformed entries with a warning, maps containers in the tenant transaction, and waits for the node's rate before writing.
    • VictoriaLogsStore: POST /insert/jsonline with _stream_fields=org,app,instance,stream, _time_field and _msg_field, and a 10-second timeout. A failure never carries the store's text.
  • Config: VICTORIALOGS_URL is optional, as VICTORIAMETRICS_URL is. The Compose file (feat(deploy): VictoriaLogs in the control plane's Compose project (part of #232) #460) and .env.example set it.
  • SPEC 12: the refusals and what is dropped.

How it was tested

  • Domain:
    • bounds and malformed entries;
    • labels from the allocation, with the agent's container name absent from the records;
    • the skew rule;
    • the token bucket.
  • Stream:
    • in-order acknowledgements after the store kept each batch;
    • a missing open, a stale epoch, out-of-order numbers and a second open are refused;
    • no acknowledgement when the store fails;
    • the stream is refused without a store.
  • Ingest: registration only with a store, labels and drops, waiting past the rate, a store failure.
  • Store, against a local HTTP server: the query and the JSON lines, quotes and newlines included. A 500 fails without the server's text, and no records means no request.
  • node-stream.spec.ts passes the new dependency.
  • vitest --project api: 764 tests pass, and ESLint is clean.

Security considerations

  • Tenant isolation rests on the certificate identity and the control plane's records. An agent can only write lines for containers placed on its own node, and every label is set here.
  • The batch, line and rate bounds protect the API and VictoriaLogs from a flooding agent: past its rate, a node waits instead of being dropped.
  • Logs change no state, so nothing is audited, as for metrics (ADR 0024).

#232)

The maintainer chose a dedicated ShipLogs stream, as for metrics (ADR 0024): no published port, agent credential or agent label to trust. Acknowledged batches and a cursor per container let logs survive a control plane outage within Docker's rotation; the agent redacts secret environment values first.

Signed-off-by: samuel mbabhazi <[email protected]>
ADR 0029: LogsOpen with the lease epoch, LogBatch of entries (container, stream, Docker time, line, truncated) acknowledged by sequence number, and Welcome.logs. ConfigUpdate.logs_endpoint is deprecated.

Signed-off-by: samuel mbabhazi <[email protected]>
ShipLogs on the gateway checks the open's lease epoch and the batches' order, and acknowledges each one once VictoriaLogs kept it. Lines are labelled from the node's placed allocations only, malformed entries are dropped, and each node writes at most 512 KiB/s with 4 MiB bursts. VICTORIALOGS_URL is now optional; Welcome.logs says whether logs are kept.

Signed-off-by: samuel mbabhazi <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 56 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 962dbf1 and 69ac748.

Files selected for processing: 20

  • apps/api/src/modules/fleet/application/log-batches.spec.ts
  • apps/api/src/modules/fleet/application/log-batches.ts
  • apps/api/src/modules/fleet/domain/logs-not-kept.ts
  • apps/api/src/modules/fleet/fleet.module.ts
  • apps/api/src/modules/fleet/interface/agent-gateway.ts
  • apps/api/src/modules/fleet/interface/log-stream.spec.ts
  • apps/api/src/modules/fleet/interface/log-stream.ts
  • apps/api/src/modules/fleet/interface/node-stream.spec.ts
  • apps/api/src/modules/fleet/interface/node-stream.ts
  • apps/api/src/modules/fleet/interface/stream-frames.ts
  • apps/api/src/modules/observability/application/logs-ingest.spec.ts
  • apps/api/src/modules/observability/application/logs-ingest.ts
  • apps/api/src/modules/observability/application/ports.ts
  • apps/api/src/modules/observability/domain/logs.spec.ts
  • apps/api/src/modules/observability/domain/logs.ts
  • apps/api/src/modules/observability/infrastructure/victoria-logs.store.spec.ts
  • apps/api/src/modules/observability/infrastructure/victoria-logs.store.ts
  • apps/api/src/modules/observability/observability.module.ts
  • apps/api/src/platform/config/config.schema.ts
  • docs/SPEC.md
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@samuelmbabhazi
samuelmbabhazi changed the base branch from feat/232-ship-logs-proto to main November 24, 2026 22:12
@samuelmbabhazi

Copy link
Copy Markdown
Collaborator Author

An independent review of this PR (high effort, while CodeRabbit is rate limited) raised eight points. Seven are fixed; the eighth is covered by #460.

  • A log stream checked the node only at LogsOpen. LogStreams (f5bd55d) now checks the node's credential and lease epoch again before each batch, and every 10 s while none comes. Revocation, removal or a new lease ends the stream. A newer stream of the same node replaces the older one, as SPEC 3.3 already said. A stream that sends no LogsOpen within 30 s ends. The frame wait shared with Connect moved to stream-frames.ts.
  • NodeAuthenticationError reached the agent as Internal. It is now Unauthenticated, as on Connect.
  • The rate counted UTF-16 code units, after the lookup, and only for kept lines. A batch is now charged before anything is looked up (fdf5d1d). The charge is the UTF-8 bytes of all its lines, kept or dropped, and at least 16 KiB, so a flood of batches for unknown containers is held back too.
  • An entry with a stream other than stdout or stderr was stored as stdout. It is now dropped as malformed.
  • Raw Errors. The VictoriaLogs store throws ServiceUnavailableException without its text, whether it answers non-2xx or cannot be reached. LogBatches.deliver without a store throws LogsNotKeptError (precondition_failed).
  • One bucket per node was kept forever. Buckets that have refilled are forgotten every minute.
  • Production compose has no VictoriaLogs. feat(deploy): VictoriaLogs in the control plane's Compose project (part of #232) #460 adds the pinned service and VICTORIALOGS_URL; this PR only makes the variable optional.

Also fixed here, found in the lab: a line sent again after an agent restart took the control plane's time when it was more than five minutes old (a2802c3). It keeps Docker's time now; only a time ahead of the clock is replaced, and a line past the 30 days of retention is dropped. This was checked in the lab by restarting the agent: the replayed lines landed at their original time.

SPEC 3.3 and 12 describe the checks, the charge and the dropped entries. nx typecheck lint for the API passes, and the fleet, observability and deployments tests pass (360).

@samuelmbabhazi
samuelmbabhazi merged commit 3971dd2 into main Nov 25, 2026
23 of 25 checks passed
@samuelmbabhazi
samuelmbabhazi deleted the feat/232-logs-ingest branch November 25, 2026 09:14
samuelmbabhazi added a commit that referenced this pull request Nov 25, 2026
Part of #232 (M6.1). This is the read side of ADR 0029: searching an
application's logs. It is stacked on #461, which writes them. The web UI
comes next.

## What changed

- **`GET …/applications/{applicationId}/logs`** (`environment.read`,
sessions and API tokens).
  - **Parameters:**
    - `text`: at most 256 characters, a phrase the lines contain;
    - `stream`: `stdout` or `stderr`;
    - `instance`: the replica;
- `from` and `to`: the last hour by default, and a period of 30 days at
most, starting before it ends;
    - `limit`: 200 by default, 500 at most.
  - **Answer:**
    - `kept`, false without a log store;
- `lines`, newest first, each with `time`, `stream`, `instance`, `line`
and `truncated`.

  The live view asks again from its newest line's time.
- **`logsQuery`** (domain, pure):
- It filters on `org` and `app`, the labels the control plane wrote
(#461), from identifiers it validates as UUIDs.
- It adds `_time:[from, to]`, the stream and the instance, then the text
as one quoted phrase: backslashes and quotes escaped, control characters
removed.
  - It ends with `| sort by (_time desc) | limit n`.
- **`logLineOf`** reads back only well-formed records.
- **`VictoriaLogsStore.query`** calls `/select/logsql/query`.
  - The answer is read up to 16 MiB.
- Any failure (connection, status, size, JSON) is a `503` "Logs
temporarily unavailable.", never the store's text.
- **`LogsQueries`** checks the permission and that the application
exists in its environment, then searches.
- Generated `openapi.json`, API client and route-role matrix. **SPEC
12:** the route.

## How it was tested

- **Domain:**
  - the exact query;
- injection attempts stay one phrase and cannot add a filter, a pipe or
another app: `" | delete`, a backslash before a quote, newlines and NUL,
and `} {org="other"}`;
  - a scope that is not two UUIDs is refused;
  - malformed records are dropped.
- **Store**, against a local HTTP server: the query and limit
parameters, JSON lines with blank lines between them, and a 500 or a
non-JSON answer giving a 503 without the store's text.
- **Service:** labels and drops; `kept: false` without a store; an
unknown application or no permission gives 404.
- `nx run-many -t typecheck lint -p api` passes, and the 53
observability tests pass.

## Security considerations

- A caller reads only their organization's application: the filters come
from validated identifiers, never from the caller's text.
- Lines are already redacted by the agent (#459 and the shipper).
- Bounded answers keep the API's memory in check.

---------

Signed-off-by: samuel mbabhazi <[email protected]>
samuelmbabhazi added a commit that referenced this pull request Nov 25, 2026
…464)

Part of #232 (M6.1). The agent side of ADR 0029: it follows every
managed container's output and sends it to the control plane on the
`ShipLogs` stream, which #461 writes to VictoriaLogs.

Stacked on #459 (the Docker logs reader). Retarget to `main` once #459
is merged.

## What changed

- **`agent/internal/logship`**: the shipper.
- It follows every running container labelled `sk.managed`, from that
container's cursor, and rescans every 10 s for new ones. A follower that
ends is started again on the next scan, including when the daemon
restarts with live-restore.
- Lines go out in batches of at most 256 entries and 60 KiB, flushed
every second. At most 4 batches wait for their acknowledgement.
- When a batch is acknowledged, the cursor of each container in it moves
to that batch's last `LogLine.Resume`. `Resume` is the time from which
reading again loses nothing, even while a line of the other stream is
still being joined (#459). Lines therefore arrive at least once, and
none is lost while Docker still holds it.
- **Redaction** (`redact.go`): the values of the container's secret
environment variables of 8 bytes or more become `[redacted]` before a
line leaves the agent, longest first. Their names come from the new
`sk.secret_env` label, and their values from the container's own
environment. A redacted line is cut again to 16 KiB.
- **`actions`**: `CreateContainer` sets `sk.secret_env`, the sorted
names of the spec's secrets. Names are not secret.
- **`journal`**: a `log_cursors` table, keyed by container name. A
cursor only moves forward, and those of containers that are gone are
forgotten.
- **`gateway`**: `Streams.OpenLogs` opens the stream. The runner starts
the shipper with the session's lease epoch once Welcome says logs are
kept, and stops it with the session. A failed stream is retried after 5
s.
- **CI**: the integration job also runs `./agent/internal/logship/`.

## How it was tested

- Unit tests: batching and bounds, acknowledgements that move cursors
only once kept, out-of-order or unexpected answers ending the stream,
redaction (short values left alone, overlapping values, the cut after
redaction), and cursor storage.
- `TestRealShipperSendsAContainersRedactedLinesAndKeepsItsCursor` runs
against a real Docker Engine: a busybox container prints a secret on
stderr, which arrives as `token is [redacted]`, and the cursor is
stored. It now checks only its own container, so it also passes on an
engine that runs other managed containers (it did, in the lab node).
- **Lab**, agent `0.1.0-lab.27` from this branch on a node with an nginx
application:
- lines printed before, during and after an agent restart all reached
VictoriaLogs and were found by the API's search;
- the last acknowledged line came once more after the restart, as
at-least-once allows; #463 shows it once.
- `go test ./agent/...` and golangci-lint pass.

## Security considerations

- Container output is untrusted. Lines are bounded by #459 and by the
batch limits. The control plane validates every entry and sets every
label itself, so an agent can only write lines for its own placed
containers (#461).
- Secret values are read from the container's environment for redaction
only. They are never logged, stored or sent. Secrets mounted as files,
and values an application derives from a secret, are not redacted. ADR
0029 and THREAT_MODEL say so.
- No new action and no new shell invocation. The shipper uses Docker's
logs and inspect APIs only.

---------

Signed-off-by: samuel mbabhazi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant