summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--AGENTS.md426
-rw-r--r--CLAUDE.md1
-rw-r--r--README.md98
-rw-r--r--doc/asciinema/README.md41
-rw-r--r--doc/auth-key-fast-reconnect.md200
-rw-r--r--doc/index.md1
-rw-r--r--doc/installation.md59
-rw-r--r--doc/logformats.md5
-rw-r--r--doc/performance_optimization_summary.md69
-rw-r--r--doc/pgo_commands_detail.md216
-rw-r--r--doc/pgo_implementation.md173
-rw-r--r--doc/profiling.md376
-rw-r--r--doc/querylanguage.md40
-rw-r--r--doc/refactoring_guide.md240
-rw-r--r--doc/turbo_performance_analysis.md104
-rw-r--r--doc/turboboost_optimization.md117
-rw-r--r--docs/SERVERLESS_LARGE_FILES_ISSUE.md61
-rw-r--r--docs/turbo-vs-normal-benchmark-20260718-run1.csv127
-rw-r--r--docs/turbo-vs-normal-benchmark-20260718-run2.csv127
-rw-r--r--docs/turbo-vs-normal-benchmark-20260718.md126
-rw-r--r--examples/dserver-prune-logs.service.example8
-rw-r--r--examples/dserver-prune-logs.timer.example9
-rw-r--r--examples/dserver.service.example2
-rw-r--r--examples/firewalld-dserver-port.sh.example21
-rw-r--r--examples/prune_dserver_logs.sh.example10
25 files changed, 2609 insertions, 48 deletions
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 0000000..90ac627
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,426 @@
+# CLAUDE.md
+
+This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
+
+## Project Overview
+
+DTail (Distributed Tail) is a DevOps tool written in Go for distributed log operations across multiple servers. It provides secure, concurrent access to logs on many machines using SSH protocol, supporting tail, cat, grep, MapReduce operations, and auth-key fast reconnect optimization for repeated SSH connections.
+
+## Build Commands
+
+```bash
+# Build all binaries
+make build
+
+# Build individual components
+make dtail # Client for tailing log files
+make dserver # Server component (required on target machines)
+make dcat # Client for displaying files
+make dgrep # Client for searching files
+make dmap # Client for MapReduce queries
+make dtailhealth # Health check client
+
+# Clean build artifacts
+make clean
+
+# Enable ACL support (requires libacl-devel)
+DTAIL_USE_ACL=yes make build
+
+# Build without zstd (CGO-free cross-compiles; .zst logs unsupported)
+DTAIL_NO_ZSTD=yes make build
+
+# Enable proprietary features
+DTAIL_USE_PROPRIETARY=yes make build
+
+# Build PGO-optimized binaries (requires existing profiles)
+make build-pgo
+
+# Generate PGO profiles and build optimized binaries
+make pgo
+```
+
+## Testing & Development
+
+```bash
+# Run all tests (unit tests only)
+make test
+
+# Run all tests including integration tests
+# IMPORTANT: Always rebuild binaries before running integration tests
+make clean && make build
+DTAIL_INTEGRATION_TEST_RUN_MODE=yes make test
+
+# Quick integration test workflow (recommended)
+make build && DTAIL_INTEGRATION_TEST_RUN_MODE=yes make test
+
+# Run linting
+make lint
+
+# Run go vet
+make vet
+
+# Run integration tests individually (requires binaries built first)
+cd integrationtests && go test
+```
+
+## Benchmarking
+
+```bash
+# Run all benchmarks
+make benchmark
+
+# Quick benchmarks (subset of tests)
+make benchmark-quick
+
+# Full benchmarks with longer runs
+make benchmark-full
+
+# Create a baseline for comparison
+make benchmark-baseline
+
+# Compare current performance against a baseline
+make benchmark-compare BASELINE=benchmarks/baselines/baseline_TIMESTAMP.txt
+```
+
+## Profile-Guided Optimization (PGO)
+
+```bash
+# Full PGO workflow: generate profiles and build optimized binaries
+make pgo
+
+# Quick PGO with smaller datasets (faster)
+make pgo-quick
+
+# PGO for specific commands only
+make pgo-commands COMMANDS='dcat dgrep'
+
+# Generate PGO profiles only (without building)
+make pgo-generate
+
+# Build PGO-optimized binaries using existing profiles
+make build-pgo
+
+# Install PGO-optimized binaries to system
+make install-pgo
+
+# Clean PGO artifacts
+make pgo-clean
+
+# Show PGO help
+make pgo-help
+```
+
+### PGO Notes
+
+- PGO provides additional performance improvements on top of DTail's default optimized read/output path
+- Measured improvements are workload-dependent and modest: on a 100 MB
+ serverless run, DGrep ~7-8%, DCat ~3%, DMap within measurement noise. PGO
+ output is byte-identical to non-PGO output (verified with `cmp`).
+- Profiles are saved in `pgo-profiles/` directory
+- `pgo-profiles/` and `pgo-build/` are **gitignored**: profiles are regenerated
+ locally with `make pgo` / `make pgo-generate`, not committed. They are
+ workload-specific; regenerate them after significant hot-path changes.
+- Optimized binaries are built in `pgo-build/` directory
+- Use `make build-pgo` to rebuild optimized binaries without regenerating profiles
+- The tooling verifies every captured profile has non-zero CPU samples and
+ fails loudly otherwise (see `internal/tools/pgo`), so an idle-server or
+ I/O-bound capture can no longer silently produce an empty/zero-sample profile.
+- **dtail is intentionally excluded from PGO.** Its follow client does not
+ return from `client.Start` under `-shutdownAfter`, SIGINT or SIGTERM (the
+ pre-existing "auto shutdown does not work" bug noted in `cmd/dtail/main.go`),
+ so it never flushes a CPU profile. Attempting to profile it produced the
+ 0-byte `dtail.pprof`. The `dtail-tools pgo` default command set therefore
+ covers dcat, dgrep, dmap and dserver only, matching the existing
+ `internal/tools/profile` harness which also omits dtail. Re-enable dtail here
+ once its follow shutdown is fixed.
+
+## Profiling
+
+```bash
+# Profile all commands (dcat, dgrep, dmap)
+make profile-all
+
+# Profile individual commands
+make profile-dcat # Profile dcat with test data
+make profile-dgrep # Profile dgrep with test data
+make profile-dmap # Profile dmap MapReduce queries
+
+# Quick profiling with smaller datasets
+make profile-quick
+
+# Full automated profiling (includes larger files)
+make profile-auto
+
+# Clean all profile data
+make profile-clean
+
+# Analyze a specific profile interactively
+make profile-analyze PROFILE=profiles/dcat_cpu_*.prof
+
+# Generate flame graph visualization
+make profile-flamegraph PROFILE=profiles/dcat_cpu_*.prof
+
+# Custom profiling options
+PROFILE_SIZE=10000000 make profile-all # Profile with 10M lines
+PROFILE_DIR=myprofiles make profile-dcat # Custom profile directory
+
+# Show all profiling options
+make profile-help
+```
+
+### Profiling Notes
+
+- Profiles are saved in the `profiles/` directory by default
+- Each command generates CPU, memory, and allocation profiles
+- Use `go tool pprof` for detailed analysis of profile files
+
+## Test Execution Details
+
+- Integration tests require binaries to be built before execution
+- **IMPORTANT:** Always recompile binaries after code changes before running integration tests:
+ ```bash
+ make clean && make build
+ DTAIL_INTEGRATION_TEST_RUN_MODE=yes make test
+ ```
+- Integration tests are run by setting DTAIL_INTEGRATION_TEST_RUN_MODE to yes, and by running 'make test'
+- Integration tests verify: DCat, DGrep, DMap (MapReduce), DServer, DTail, DTailHealth, and auth-key fast reconnect functionality
+- All tests run with race detection enabled (`--race` flag)
+
+## Known Limitations
+
+### Interactive Query Reload
+Interactive query control is opt-in on the client with `--interactive-query`.
+The controlling TTY accepts `:reload <flags>`, `:show`, `:help`, and `:quit`.
+
+**Compatibility and session semantics:**
+- Initial interactive bootstrap prefers `SESSION START` when the server
+ advertises capability `query-update-v1`
+- If that capability is absent, startup falls back to the legacy command stream
+ automatically so mixed-version client/server combinations still run
+- Live `:reload` updates require every active server connection to advertise
+ `query-update-v1`; unsupported servers cause the reload to be rejected while
+ the current workload keeps running
+- Successful reloads reuse the existing SSH session and advance a generation
+ boundary so stale output from older workloads is dropped
+
+### Auth-Key Fast Reconnect
+Auth-key fast reconnect is enabled by default. The client can register a public key with `dserver` over an already-authenticated session, and subsequent connections can use this in-memory key before falling back to normal SSH auth.
+
+**Technical Details:**
+- Client sends `AUTHKEY <base64-pubkey>` command during session setup
+- Server stores keys in memory, per user, with TTL and max-keys limits
+- SSH `PublicKeyCallback` checks in-memory auth-key store before `authorized_keys`
+- If fast-path auth misses (restart/expiry/mismatch), normal SSH auth is used automatically
+
+**Config and Flags:**
+- Client flag: `--auth-key-path` (default `~/.ssh/id_rsa`)
+- Client flag: `--no-auth-key` (disable feature)
+- Client env: `DTAIL_AUTH_KEY_PATH` (primary env alias for auth key path; takes precedence over `DTAIL_SSH_PRIVATE_KEYFILE_PATH`)
+- Client env: `DTAIL_SSH_PRIVATE_KEYFILE_PATH` (legacy alias; used only when `DTAIL_AUTH_KEY_PATH` is not set)
+- Env var precedence (highest to lowest): CLI flag → `DTAIL_AUTH_KEY_PATH` → `DTAIL_SSH_PRIVATE_KEYFILE_PATH`
+- Server config: `AuthKeyEnabled` (default `true`)
+- Server config: `AuthKeyTTLSeconds` (default `86400`)
+- Server config: `AuthKeyMaxPerUser` (default `5`)
+
+### Journal Source Reads
+Journal targets use `journal:unit.service` syntax. Permission rules should match the full target, for example `Server.Permissions.Users[user]: ["readfiles:^journal:.*\\.service$"]`.
+
+**Technical Details:**
+- Server capability `journal-v1` is required for any journal-backed read target; clients reject journal sources when the server does not advertise it.
+- The capability is advertised only on Linux when `journalctl` is available on `PATH`.
+- Journal reads use `journalctl` via `os/exec` only; there is no cgo or `libsystemd` path, and the feature is Linux-only at runtime.
+- Non-follow reads the current journal snapshot once. Follow mode adds `-f -n 0` and keeps restarting `journalctl` until canceled.
+
+### Client Log Contents: Diagnostics vs Payload
+The default client logger is `fout` (stdout + a daily file at
+`<LogDir>/YYYYMMDD.log`, `LogDir` defaults to `~/log`). By default that file
+records DIAGNOSTICS ONLY — the small connection/audit lines (INFO/WARN/ERROR).
+The full retrieved PAYLOAD (the bulk `dcat`/`dgrep`/`dtail` output) is NOT written
+to the file by default, so a large read no longer silently grows the daily log by
+the full payload size. Payload always still goes to STDOUT/terminal, unchanged.
+
+**Restoring the legacy full-payload tee (opt-in):**
+- Client flag: `--log-payload` (all client commands: dcat, dgrep, dtail, dmap)
+- Client config: `Client.LogPayload` (default `false`)
+- When enabled, retrieved payload is teed into the daily log file as before.
+
+**Seam and scope:**
+- The split happens in the `fout` logger: diagnostics arrive via `Log`/`LogWithColors`
+ (always written to both stdout and file); payload arrives via `Raw`/`RawWithColors`
+ (always to stdout, to the file only when `LogPayload` is set).
+- Only the default `fout` logger is affected. `--logger stdout` (no file sink) and
+ `--logger none` are unaffected. `--logger file` is a pure file sink with no stdout
+ tee; it deliberately still writes payload to the file, because otherwise its output
+ file would be empty — payload teeing there is not gated by `--log-payload`.
+- Note: the serverless direct-output path can bypass the logger and write payload
+ directly to stdout; that path never wrote payload to the file and is unaffected.
+ The disk-fill footgun lives on the `fout` file path (the server-mode receive
+ path), which is what this setting gates.
+
+### Output Path and MapReduce Operations
+DTail uses a single, channel-less read/output path for both direct output
+operations (cat, grep, tail) and MapReduce operations in server mode. This was
+formerly called "turbo boost" mode and offered as an opt-out optimization; it is
+now the one and only mode. There is no on/off toggle: the old
+`DTAIL_TURBOBOOST_DISABLE` environment variable and the `Server.TurboBoostDisable`
+config field have been removed. `DTAIL_TURBOBOOST_DISABLE` is now inert (a no-op),
+and a leftover `TurboBoostDisable` key in an old config file is silently ignored
+(config decoding does not reject unknown keys).
+
+**Technical Details:**
+- For cat/grep/tail: the read path writes directly to the output/connection
+ without channel hand-offs.
+- For MapReduce in server mode: lines are processed directly without channels.
+- For MapReduce in serverless/client mode: the server-side direct processing does
+ not apply — client-side aggregation runs on the client.
+
+**Server-Side MapReduce (dserver):**
+- Lines are processed directly without channel overhead
+- Batch processing reduces lock contention
+- Memory pooling reduces garbage collection pressure
+- Same output format and accuracy regardless of workload
+
+**Tuning knobs (server config):**
+The output path timing and buffer knobs live in the `Output*` / `Shutdown*` config
+namespace (formerly `Turbo*Ms` / `TurboChannelBufferSize` /
+`ShutdownTurboSerializeWaitMs`). See `internal/config/server.go` for the current
+fields: `OutputTransmissionDelayMs`, `OutputEOFWaitBaseMs`,
+`OutputEOFWaitPerFileMs`, `OutputEOFWaitMaxMs`, `OutputChannelBufferSize`,
+`OutputFlushTimeoutMs`, `OutputFlushPollIntervalMs`, `OutputReadRetryIntervalMs`,
+`OutputEOFAckTimeoutMs`, and `ShutdownOutputSerializeWaitMs`. All are optional
+(`omitempty`) internal tuning knobs with sensible defaults; the old `Turbo*` keys
+are gone, so a config that still sets them reverts silently to the defaults.
+
+**Best Practices for High-Concurrency MapReduce:**
+1. Increase MaxConcurrentCats in the server configuration to match workload
+2. Use server mode for large-scale MapReduce operations
+3. Monitor logs for performance metrics
+
+Note: three operator-facing diagnostic log lines still contain the word "turbo"
+verbatim ("Using turbo mode for reading", "Using turbo aggregate processor for
+MapReduce", "Creating turbo aggregate for MapReduce"). These are deliberately kept
+as stable log strings and do not imply a separate mode.
+
+## Benchmarking & Profiling
+
+```bash
+# Run benchmarks
+make benchmark
+
+# Run performance profiling
+make profile
+
+# Generate profiling reports
+make profile-report
+
+# Run specific benchmark suites
+make benchmark-network
+make benchmark-mapreduce
+make benchmark-ssh
+```
+
+## Profile-Guided Optimization (PGO)
+
+```bash
+# Run PGO for all commands
+make pgo
+
+# Quick PGO with smaller datasets
+make pgo-quick
+
+# PGO for specific commands
+make pgo-commands COMMANDS='dcat dgrep'
+
+# Clean PGO artifacts
+make pgo-clean
+
+# Show PGO help
+make pgo-help
+
+# Direct usage with dtail-tools
+dtail-tools pgo # Optimize all commands
+dtail-tools pgo dcat dgrep # Optimize specific commands
+dtail-tools pgo -v -iterations 5 # Verbose with 5 iterations
+
+# After PGO, optimized binaries are in pgo-build/
+```
+
+### PGO Notes
+
+- PGO uses profile data from real workloads to optimize binary performance
+- The process involves: building baseline → generating profiles → building with PGO
+- Typical improvements range from 5-20% depending on the workload
+- Optimized binaries are placed in the `pgo-build/` directory
+
+## Architecture & Code Organization
+
+### Binary Entry Points
+- `/cmd/dtail/` - Remote log tailing client
+- `/cmd/dserver/` - Server daemon
+- `/cmd/dcat/` - Remote file reading client
+- `/cmd/dgrep/` - Remote file searching client
+- `/cmd/dmap/` - MapReduce query client
+- `/cmd/dtailhealth/` - Health check client
+
+### Core Implementation
+- `/internal/clients/` - Client implementations for each tool
+- `/internal/server/` - Server daemon logic
+- `/internal/mapr/` - MapReduce engine and query parsing
+- `/internal/ssh/` - SSH client/server components
+- `/internal/config/` - Configuration management
+- `/internal/io/` - File operations, logging, compression handling
+
+### Key Architectural Patterns
+
+1. **Client-Server Communication**: All clients communicate with dserver instances via SSH protocol on port 2222 (configurable)
+
+2. **MapReduce Query Engine**: Located in `/internal/mapr/`, implements SQL-like query language for distributed log aggregation
+
+3. **Configuration System**: JSON-based configuration in `/internal/config/`, supports both client and server settings
+
+4. **SSH Integration**: Custom SSH server implementation in `/internal/ssh/server/` and client in `/internal/ssh/client/`
+
+5. **Compression Support**: Automatic handling of gzip and zstd compressed files in `/internal/io/`
+
+6. **Auth-Key Fast Reconnect**: Client registers a public key via `AUTHKEY`; server validates against in-memory auth-key cache before falling back to `authorized_keys`
+
+## Important Implementation Details
+
+- **Main Server Loop**: `/internal/server/server.go` - Core server processing logic
+- **Client Base**: `/internal/clients/baseClient.go` - Common client functionality
+- **MapReduce Parser**: `/internal/mapr/parse/` - SQL-like query language parser
+- **Log Format Parsers**: `/internal/mapr/logformat/` - Extensible log parsing system
+- **SSH Authorization Callback**: `/internal/ssh/server/publickeycallback.go` - auth-key fast-path + `authorized_keys` fallback
+- **Auth-Key Cache**: `/internal/ssh/server/authkeystore.go` - in-memory per-user key cache (TTL/max-keys)
+- **AUTHKEY Handler**: `/internal/server/handlers/serverhandler.go` - session command handling for auth-key registration
+
+## Configuration Files
+
+- Server config: `/etc/dserver/dtail.json` or `./dtail.json`
+- Example configs: `/examples/`
+- Docker configs: `/docker/`
+
+### Auth-Key Related Options
+
+- Client: `--auth-key-path`, `--no-auth-key`
+- Client config: `Client.AuthKeyPath`, `Client.AuthKeyDisable`
+- Client env: `DTAIL_AUTH_KEY_PATH` (takes precedence over `DTAIL_SSH_PRIVATE_KEYFILE_PATH`)
+- Client env: `DTAIL_SSH_PRIVATE_KEYFILE_PATH` (legacy; used only when `DTAIL_AUTH_KEY_PATH` is unset)
+- Server config: `Server.AuthKeyEnabled`, `Server.AuthKeyTTLSeconds`, `Server.AuthKeyMaxPerUser`
+
+## Common Development Tasks
+
+When modifying client behavior:
+1. Check `/internal/clients/` for the specific client implementation
+2. Common functionality is in `baseClient.go`
+3. Client-specific logic is in respective files (e.g., `tail.go`, `cat.go`)
+
+When modifying server behavior:
+1. Core server logic is in `/internal/server/server.go`
+2. User authentication in `/internal/server/user/`
+3. Handler implementations in `/internal/server/handlers/`
+
+When working with MapReduce:
+1. Query parsing in `/internal/mapr/parse/`
+2. Aggregation logic in `/internal/mapr/reducer/`
+3. Log format parsing in `/internal/mapr/logformat/`
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 0000000..43c994c
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1 @@
+@AGENTS.md
diff --git a/README.md b/README.md
index 8a0ac57..dbc7d62 100644
--- a/README.md
+++ b/README.md
@@ -13,13 +13,108 @@ The DTail binary operates in either client or server mode. The DTail server must
![DTail](doc/dtail.gif "Example")
-If you like what you see [look here for more examples](doc/examples.md)! You can also read through the [DTail Mimecast Engineering Blog Post](https://medium.com/mimecast-engineering/dtail-the-distributed-log-tail-program-79b8087904bb). There is also a GitHub Page at [dtail.dev](https://dtail.dev).
+If you like what you see [look here for more examples](doc/examples.md)! You can also read through the [DTail Mimecast Engineering Blog Post](https://medium.com/mimecast-engineering/dtail-the-distributed-log-tail-program-79b8087904bb).
Installation and Usage
======================
* Check out the [DTail Documentation](doc/index.md)
+Interactive Query Reload
+========================
+
+`dtail`, `dgrep`, `dcat`, and `dmap` accept `--interactive-query` to keep the
+current run open and listen for control commands on the controlling TTY.
+
+Available control commands:
+
+* `:reload <flags>` apply a new workload by reusing the current session when the
+ active servers support it
+* `:show` print the current interactive state, including capability counts
+* `:help` print the interactive command help text
+* `:quit` stop the interactive session
+
+Reload flags are mode-specific:
+
+* `dtail` and `dgrep`: `--grep`/`--regex`, `--before`, `--after`, `--max`,
+ `--invert`, plus shared flags such as `--files`, `--plain`, `--quiet`, and
+ `--timeout`
+* `dmap`, and query-driven `dtail`: `--query` plus the shared flags above
+* `dcat`: shared flags such as `--files`, `--plain`, `--quiet`, and `--timeout`
+
+Examples:
+
+```bash
+dtail --servers app01 --files /var/log/app.log --grep ERROR --interactive-query
+# then type:
+:reload --grep WARN
+
+dgrep --servers app01 --files /var/log/app.log --grep ERROR --interactive-query
+# then type:
+:reload --grep WARN --before 2 --after 3
+
+dmap --servers app01 --files /var/log/app.log \
+ --query 'from STATS select count($line) group by hostname' \
+ --interactive-query
+# then type:
+:reload --query "from STATS select count($line),avg(latency) group by hostname"
+```
+
+Compatibility and session reuse:
+
+* On startup, an interactive client first tries `SESSION START` when the remote
+ side advertises the `query-update-v1` capability
+* If a server is older or does not advertise that capability, startup falls
+ back to the legacy command stream automatically, so mixed-version
+ client/server combinations still run the original workload normally
+* Live `:reload` updates require every active server to advertise
+ `query-update-v1`; otherwise the reload is rejected and the current workload
+ keeps running unchanged
+* On capable servers, DTail reuses the existing SSH session and sends
+ `SESSION UPDATE` messages instead of reconnecting
+* Every successful reload advances a generation boundary; late output from the
+ previous workload is dropped so stale matches do not leak into the new result
+ stream
+
+Auth-Key Fast Reconnect
+=======================
+
+DTail supports an optional SSH auth optimization for repeated reconnects.
+After a normal authenticated SSH session is established, the client can
+register a local public key with `dserver` using an `AUTHKEY` command. The
+server stores this key in memory only and checks it before `authorized_keys`
+on subsequent connections.
+
+This reduces repeated hardware-token signing (for example YubiKey-backed SSH
+agent keys) while keeping transparent fallback to normal SSH authentication.
+
+Client options:
+
+* `--auth-key-path` path to the private key to offer first and register
+ (default: `~/.ssh/id_rsa`)
+* `--no-auth-key` disable auth-key registration/fast-path and use normal SSH
+ behavior only
+
+Server configuration (`dtail.json`):
+
+```json
+{
+ "Server": {
+ "AuthKeyEnabled": true,
+ "AuthKeyTTLSeconds": 86400,
+ "AuthKeyMaxPerUser": 5
+ }
+}
+```
+
+Security notes:
+
+* Registered keys are stored in memory only (no disk persistence)
+* Registration is accepted only over an already-authenticated session
+* TTL expiry and per-user key limits bound key lifetime and memory growth
+* If fast-path auth is unavailable (restart/expiry/mismatch), DTail falls back
+ to normal SSH auth automatically
+
More
====
@@ -34,4 +129,3 @@ Credits
* Thank you [Mimecast](https://www.mimecast.com) for supporting this Open-Source project.
* Thank you to **Vlad-Marian Marian** for creating the DTail (dog) logo.
* The Gopher was generated at https://gopherize.me
-* The animated Gifs were created using `asciinema` with `asciicast2gif`. Check out [how this was done](./doc/asciinema/README.md) for more information.
diff --git a/doc/asciinema/README.md b/doc/asciinema/README.md
deleted file mode 100644
index 1eb1a2e..0000000
--- a/doc/asciinema/README.md
+++ /dev/null
@@ -1,41 +0,0 @@
-asciinema
-=========
-
-The animated Gifs you find in the DTail docs were created using:
-
-* [asciinema](https://asciinema.org)
-* [asciicast2gif](https://github.com/asciinema/asciicast2gif)
-
-On Fedora Linux 35.
-
-## Installing prerequisites
-
-On Fedora Linux 35 install `asciinema`:
-
-```shell
-% sudo dnf install -y asciinema
-```
-
-and `asciicast2gif` (for simplicity, the Docker image was used):
-
-```shell
-% docker pull asciinema/asciicast2gif
-```
-
-This of course assumes that Docker is up and running on your machine (out of scope for this documentation).
-
-## Record a shell session
-
-This is as simple as running
-
-```shell
-% asciinema rec recording.json
-```
-
-This will launch a sub-shell to be recorded. Once done, exit the sub-shell with `exit`.
-
-## Convert the recording to a gif
-
-```shell
-% docker run --rm -v $PWD:/data asciinema/asciicast2gif -t tango -s 2 recording.json recording.gif
-```
diff --git a/doc/auth-key-fast-reconnect.md b/doc/auth-key-fast-reconnect.md
new file mode 100644
index 0000000..cb9884a
--- /dev/null
+++ b/doc/auth-key-fast-reconnect.md
@@ -0,0 +1,200 @@
+# Auth-Key Fast-Reconnect for DTail
+
+## Problem
+
+When using a YubiKey for SSH authentication, each DTail connection requires a
+physical touch of the YubiKey during the SSH handshake. This is slow and becomes
+painful when connecting to many servers concurrently — the YubiKey serialises
+all signing requests, turning parallel connections into sequential ones.
+
+## Solution
+
+Allow the DTail client to register a local SSH public key with the DTail server
+over an already-authenticated SSH session. The server caches this key
+**in-memory only** (never written to disk). On subsequent connections the client
+offers that local key first — a pure in-memory RSA verify with no YubiKey
+interaction — and falls back to the original auth method if the server does not
+recognise the key.
+
+## Design Principles
+
+1. **Transparent fallback** — Go's `golang.org/x/crypto/ssh` tries each
+ `AuthMethod` in order; if the fast key is rejected the client silently falls
+ back to the SSH agent / YubiKey. No user interaction required.
+2. **Server keys are ephemeral** — the in-memory store is lost on server
+ restart. No file I/O, no persistence.
+3. **Trust chain preserved** — an auth-key can only be registered over a session
+ that was already authenticated via the normal (YubiKey) path.
+4. **Minimal protocol addition** — a single `AUTHKEY <base64-pubkey>` command
+ sent over the existing SSH session text protocol.
+
+## Architecture Overview
+
+```
+┌─────────────────────────────────────────────────────────┐
+│ DTail Client │
+│ │
+│ Auth methods (tried in order): │
+│ 1. Local private key (~/.ssh/id_rsa) ← FAST │
+│ 2. SSH Agent / YubiKey ← SLOW fallback │
+│ │
+│ After slow-path auth: │
+│ → sends AUTHKEY <~/.ssh/id_rsa.pub> to server │
+└────────────────────────┬────────────────────────────────┘
+ │ SSH
+┌────────────────────────▼────────────────────────────────┐
+│ DTail Server (dserver) │
+│ │
+│ PublicKeyCallback: │
+│ 1. Check in-memory authkeystore ← FAST │
+│ 2. Check authorized_keys file ← existing path │
+│ │
+│ AUTHKEY command handler: │
+│ → authkeystore.Add(user, pubkey) │
+│ → responds AUTHKEY OK / AUTHKEY ERR │
+│ │
+│ authkeystore (in-memory only): │
+│ map[username] → []PublicKey (with TTL, max per user) │
+└─────────────────────────────────────────────────────────┘
+```
+
+## Sequence of Events
+
+### First Connection (slow path — YubiKey)
+
+1. Client checks for local private key at `~/.ssh/id_rsa` (or `--auth-key-path`).
+2. Client builds auth methods list: `[localKey, sshAgent]`.
+3. SSH handshake begins; server's `PublicKeyCallback` is called with local key.
+4. Server checks in-memory authkeystore → not found.
+5. Server checks `authorized_keys` file → not found (this key isn't in there).
+6. Server rejects the key.
+7. Go SSH client automatically tries next auth method: SSH agent (YubiKey).
+8. YubiKey signs the challenge; server finds the YubiKey pubkey in
+ `authorized_keys` → auth succeeds.
+9. Session is established; client sends DTail commands as usual.
+10. Client reads `~/.ssh/id_rsa.pub` and sends `AUTHKEY <base64-pubkey>`.
+11. Server's handler parses the command, calls `authkeystore.Add(user, pubkey)`.
+12. Server responds `AUTHKEY OK`.
+
+### Subsequent Connections (fast path — no YubiKey)
+
+1. Client builds auth methods list: `[localKey, sshAgent]`.
+2. SSH handshake begins; server's `PublicKeyCallback` is called with local key.
+3. Server checks in-memory authkeystore → **found** → auth succeeds immediately.
+4. No YubiKey touch needed. Session is established instantly.
+
+### Fallback (server restarted, key expired)
+
+1. Client offers local key → server's authkeystore is empty → rejected.
+2. Client falls back to SSH agent → YubiKey auth succeeds.
+3. Client re-registers local pubkey via `AUTHKEY` command.
+
+## Components
+
+### 1. Server: In-Memory Auth-Key Store
+
+**New file:** `internal/ssh/server/authkeystore.go`
+
+- Thread-safe store using `sync.RWMutex`.
+- Data structure: `map[string][]authKeyEntry` where key is username.
+- Each `authKeyEntry` holds `gossh.PublicKey` + `time.Time` (registered at).
+- Methods: `Add(user, pubkey)`, `Has(user, pubkey) bool`, `Remove(user, pubkey)`.
+- Per-user max key limit (default 5, configurable via `AuthKeyMaxPerUser`).
+- TTL-based expiry (default 24h, configurable via `AuthKeyTTLSeconds`).
+- Lazy expiry: check TTL on `Has()` calls; optionally a background reaper.
+- Package-level singleton or passed via dependency injection.
+
+### 2. Server: Extend PublicKeyCallback
+
+**Modified file:** `internal/ssh/server/publickeycallback.go`
+
+- Before the existing `authorizedKeysFile` lookup, check `authkeystore.Has(user, offeredPubKey)`.
+- If found → return success immediately (fast path).
+- If not found → fall through to existing file-based logic (no behaviour change).
+
+### 3. Server: AUTHKEY Command Handler
+
+**Modified file:** `internal/server/handlers/serverhandler.go` (or relevant handler)
+
+- Parse incoming line for `AUTHKEY <base64-pubkey>` prefix.
+- Decode the base64 public key using `gossh.ParsePublicKey()`.
+- Call `authkeystore.Add(user, pubkey)`.
+- Write `AUTHKEY OK\n` or `AUTHKEY ERR <reason>\n` back to the client.
+- Guard: only accept if `AuthKeyEnabled` is true in server config.
+
+### 4. Client: Auth Method Ordering (Multi-Method Support)
+
+**Modified file:** `internal/ssh/client/authmethods.go`
+
+- Change `initKnownHostsAuthMethods` to **collect multiple auth methods**
+ instead of returning after the first successful one.
+- Order: local private key first (from `--auth-key-path`, default `~/.ssh/id_rsa`),
+ then SSH agent, then other default keys.
+- This ensures Go's SSH client tries the fast key before the YubiKey.
+
+### 5. Client: Auth-Key Registration After Slow-Path Connection
+
+**Modified file:** `internal/clients/connectors/serverconnection.go` (or handler layer)
+
+- After session is established and DTail commands are sent, determine whether
+ the connection used the fast path or slow path.
+- If slow path (YubiKey was used): read the public key file
+ (`--auth-key-path` + `.pub`), send `AUTHKEY <base64-pubkey>` command.
+- Parse `AUTHKEY OK` / `AUTHKEY ERR` response.
+- A simple heuristic: if the auth-key-path private key exists and we have a
+ corresponding `.pub` file, always send the registration — sending it again is
+ idempotent and cheap.
+
+### 6. Configuration
+
+**Modified files:** `internal/config/server.go`, `internal/config/client.go`, `internal/config/args.go`
+
+Server config (`dtail.json`):
+- `AuthKeyEnabled` (bool, default `true`)
+- `AuthKeyTTLSeconds` (int, default `86400` = 24h)
+- `AuthKeyMaxPerUser` (int, default `5`)
+
+Client config / CLI flags:
+- `--auth-key-path` (string, default `~/.ssh/id_rsa`) — path to the local
+ private key to try first and whose `.pub` counterpart is registered
+- `--no-auth-key` (bool, default `false`) — disable auth-key feature entirely
+
+### 7. Integration Tests
+
+**Modified/new files in:** `integrationtests/`
+
+- Test that auth-key registration works end-to-end.
+- Test that fast-path auth succeeds after registration.
+- Test fallback when server has no cached key (simulating restart).
+- Test TTL expiry and max-keys-per-user limits.
+- Test `--no-auth-key` disables the feature.
+
+### 8. Documentation
+
+- Update `README.md` with auth-key feature description.
+- Update `AGENTS.md` / `CLAUDE.md` with new config options and architecture notes.
+
+## Security Considerations
+
+- **No server-side disk persistence** — keys exist only in memory, lost on restart.
+- **Trust chain** — auth-keys can only be registered over an already-authenticated
+ session. An attacker cannot register a key without first proving identity.
+- **TTL expiry** — keys auto-expire (default 24h), limiting exposure window.
+- **Per-user limits** — max 5 keys per user prevents memory exhaustion.
+- **Same security model as `~/.ssh/id_rsa`** — the local key is protected by
+ filesystem perm