Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion deploy/systemd/bower.service
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@ After=network-online.target
Wants=network-online.target

[Service]
# The collector does not send sd_notify readiness, so systemd must not wait for it.
# Sends sd_notify READY=1 / WATCHDOG=1 / STOPPING=1 when NOTIFY_SOCKET is present.
Type=exec
User=bower
Group=bower
WorkingDirectory=/opt/bower
ExecStart=/opt/bower/Bower.Collector
Restart=on-failure
RestartSec=5s
WatchdogSec=60s
Environment=BOWER_LISTEN_URL=http://127.0.0.1:4319
Environment=BOWER_QUEUE_PATH=/var/lib/bower/queue.db
Environment=BOWER_POLICY_DIRECTORY=/etc/bower/policies
Expand Down
5 changes: 4 additions & 1 deletion docs/operations/fleet-and-queue-integrity.md
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,10 @@ bower queue replay --database /var/lib/bower/queue.db --code preflight- # or -
```

Replay resets the attempt count and returns events to the queue. Heartbeats report
the dead-letter count, which the console shows per collector and fleet-wide.
the dead-letter count, `oldestDeadLetterAgeSeconds` and `recovery` state, which the
console shows per collector and fleet-wide. Automatic dead-letter expiry is disabled by
default; when `BOWER_DEAD_LETTER_RETENTION_DAYS` is opted into, every purge writes a
hash-chained evidence entry in `queue_dead_letter_purges` before removing expired rows.

## Tamper-evident queue ledger

Expand Down
22 changes: 22 additions & 0 deletions docs/operations/queue-v5-durability.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,28 @@ privacy profile cache writers) older than one hour, from the queue directory and
recursively, at most 1,000 per run. The AMA spool and the archive already clean their own
temporaries when they open. No other file is touched.

## Dead-letter retention, auxiliary volumes and service watchdogs

- **Opt-in dead-letter retention.** Dead-lettered rows are kept indefinitely by default
so unresolved delivery failures cannot disappear silently. Set
`BOWER_DEAD_LETTER_RETENTION_DAYS` (`1`–`3650`) to enable automatic expiry of dead-lettered
rows older than the configured age. Before deleting any expired dead-letter row, the
retention job logs a pre-expiry warning (`EventId 1510`) for rows within 24 hours of
expiry, records a hash-chained `queue_dead_letter_purges` ledger evidence entry (count,
cutoff, failure-code summary, oldest/newest timestamps and chain hash), and logs
`EventId 1511` with metadata only.
- **Auxiliary volume health.** When `BOWER_OUTPUT=ama-spool` or `BOWER_ARCHIVE_PATH` is
configured, the collector monitors free space on the spool and archive volumes using the
same `BOWER_STORAGE_*` watermarks as the queue volume. `/v1/status` reports auxiliary
volume state under `volumes`, and a critical auxiliary volume degrades `/health` and
`/v1/status` to `degraded`.
- **Service watchdogs and crash recovery.** `deploy/systemd/bower.service` sets
`WatchdogSec=60s` alongside `Restart=always`, and the collector sends `READY=1`,
periodic `WATCHDOG=1` heartbeats (at half `WATCHDOG_USEC`), and `STOPPING=1` over
`NOTIFY_SOCKET` without external native dependencies. The Windows MSI configures three
automatic service-recovery restart actions. Heartbeats carry `recovery` (from unclean
shutdown detection) and `oldestDeadLetterAgeSeconds` alongside dead-letter counts.

## SQL Server timestamp cursor v3 and allocation bounds

Timestamp cursor v3 keeps forward `(eventTime, sequence)` progress separate from a
Expand Down
45 changes: 39 additions & 6 deletions src/Bower.Collector/CollectorApplication.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,28 @@ public static WebApplication Build(
settings.StorageWatermarks,
services.GetService<IDiskSpaceProbe>(),
services.GetRequiredService<TimeProvider>()));
builder.Services.AddSingleton(services =>
{
IDiskSpaceProbe? probe = services.GetService<IDiskSpaceProbe>();
TimeProvider clock = services.GetRequiredService<TimeProvider>();
List<(string Name, StorageGuard Guard)> extra = [];
if (string.Equals(settings.OutputType, "ama-spool", StringComparison.Ordinal)
&& !string.IsNullOrWhiteSpace(settings.AmaSpoolPath))
{
extra.Add(("spool", new StorageGuard(Path.Combine(settings.AmaSpoolPath, ".volume"), settings.StorageWatermarks, probe, clock)));
}

if (!string.IsNullOrWhiteSpace(settings.ArchivePath))
{
extra.Add(("archive", new StorageGuard(Path.Combine(settings.ArchivePath, ".volume"), settings.StorageWatermarks, probe, clock)));
}

return new MonitoredVolumes(extra);
});
builder.Services.AddSingleton(_ => SystemdWatchdogOptions.FromEnvironment());
builder.Services.AddSingleton<ISystemdNotifier>(services =>
new UnixSystemdNotifier(services.GetRequiredService<SystemdWatchdogOptions>().NotifySocket));
builder.Services.AddHostedService<SystemdWatchdogService>();
builder.Services.AddSingleton<QueueStoragePressure>();
builder.Services.AddSingleton<IDurableEventStore>(services =>
new SqliteEventStore(
Expand Down Expand Up @@ -573,12 +595,12 @@ result.PolicyDecision is null
// Readiness and status for probes: status only, no queue metadata without a token.
app.MapGet(
"/health",
async (IDurableEventStore eventQueue, SourceHealth sources, StorageGuard storage, HttpContext context, CancellationToken cancellationToken) =>
async (IDurableEventStore eventQueue, SourceHealth sources, StorageGuard storage, MonitoredVolumes volumes, HttpContext context, CancellationToken cancellationToken) =>
{
QueueSnapshot snapshot = await eventQueue.GetSnapshotAsync(cancellationToken);
bool wecSilent = context.RequestServices.GetService<WindowsEventLogSource>()?.HasSilentSubscriptions() == true;
return Results.Json(
new HealthResponse(Status(snapshot, sources.Evaluate(), storage.Evaluate().State, wecSilent)),
new HealthResponse(Status(snapshot, sources.Evaluate(), storage.Evaluate().State, wecSilent, volumes.AnyCritical())),
CollectorJsonContext.Default.HealthResponse);
});

Expand All @@ -594,6 +616,7 @@ result.PolicyDecision is null
PipelineTelemetry telemetry,
SourceHealth sourceHealth,
StorageGuard storage,
MonitoredVolumes volumes,
QueueStoragePressure pressure,
TimeProvider clock,
HttpContext context,
Expand All @@ -609,7 +632,7 @@ result.PolicyDecision is null
WindowsEventLogSource? windowsEventLog = context.RequestServices.GetService<WindowsEventLogSource>();
IReadOnlyList<WecSubscriptionRuntimeStatus>? wecRuntime = context.RequestServices.GetService<WecRuntimeStatusTracker>()?.Snapshot();
StatusResponse status = new(
Status(snapshot, sources, storage.Evaluate().State, windowsEventLog?.HasSilentSubscriptions() == true),
Status(snapshot, sources, storage.Evaluate().State, windowsEventLog?.HasSilentSubscriptions() == true, volumes.AnyCritical()),
settings.Version,
new StatusPolicyResponse(
bundle.Hash,
Expand Down Expand Up @@ -658,7 +681,8 @@ [.. pack.Parsers.Select(parser => parser.Runtime is null ? "inactive-preview-onl
activity.LastSuccessfulDeliveryAt, lastFailure?.Code, lastFailure?.At),
Storage = await QueueStorageStatus.TryCaptureAsync(
eventQueue, snapshot, pressure, telemetry, clock.GetUtcNow(), pages, cancellationToken),
Recovery = context.RequestServices.GetRequiredService<CrashRecoveryState>().Last
Recovery = context.RequestServices.GetRequiredService<CrashRecoveryState>().Last,
Volumes = volumes.HasVolumes ? volumes.Evaluate() : null
};
return Results.Json(status, CollectorJsonContext.Default.StatusResponse);
})
Expand Down Expand Up @@ -711,8 +735,17 @@ healthy with
}
}

private static string Status(QueueSnapshot snapshot, IReadOnlyList<SourceSilenceStatus> sources, StorageState storage, bool subscriptionSilent = false) =>
snapshot.DeadLettered > 0 || sources.Any(source => source.IsOverdue) || storage == StorageState.Critical || subscriptionSilent
private static string Status(
QueueSnapshot snapshot,
IReadOnlyList<SourceSilenceStatus> sources,
StorageState storage,
bool subscriptionSilent = false,
bool auxiliaryVolumeCritical = false) =>
snapshot.DeadLettered > 0
|| sources.Any(source => source.IsOverdue)
|| storage == StorageState.Critical
|| subscriptionSilent
|| auxiliaryVolumeCritical
? "degraded"
: "healthy";

Expand Down
12 changes: 12 additions & 0 deletions src/Bower.Collector/CollectorJson.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,10 @@ internal sealed record StatusResponse(
/// <summary>Unclean-shutdown check and temporary-file cleanup at the last start. Metadata only.</summary>
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public CrashRecoveryStatus? Recovery { get; init; }

/// <summary>Free-space health for configured spool and archive volumes. Metadata only.</summary>
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public IReadOnlyList<VolumeHealthStatus>? Volumes { get; init; }
}

/// <summary>First server-sent event of a tap session: its effective filters and caps.</summary>
Expand Down Expand Up @@ -231,6 +235,14 @@ internal sealed record CollectorHeartbeat(
/// <summary>WEC runtime status per configured WEC subscription (additive). Metadata only.</summary>
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public IReadOnlyList<Bower.Source.WindowsEventLog.WecSubscriptionRuntimeStatus>? WecRuntime { get; init; }

/// <summary>Age in seconds of the oldest dead-lettered event, if any (additive). Metadata only.</summary>
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public long? OldestDeadLetterAgeSeconds { get; init; }

/// <summary>Last start's unclean-shutdown and recovery check (additive). Metadata only.</summary>
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public CrashRecoveryStatus? Recovery { get; init; }
}

/// <summary>
Expand Down
33 changes: 33 additions & 0 deletions src/Bower.Collector/CollectorSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ public sealed record CollectorSettings
/// <summary>How long acknowledged events stay in the queue for duplicate detection.</summary>
public TimeSpan DeliveredRetention { get; init; } = TimeSpan.FromDays(7);

/// <summary>Opt-in dead-letter retention (BOWER_DEAD_LETTER_RETENTION_DAYS, 1–3650). Null disables dead-letter purging.</summary>
public TimeSpan? DeadLetterRetention { get; init; }

/// <summary>
/// Acknowledged events younger than this are kept even under storage pressure
/// (BOWER_QUEUE_PRESSURE_RETENTION_MINUTES, default 60, at most the retention). Older
Expand Down Expand Up @@ -346,6 +349,7 @@ public static CollectorSettings FromEnvironment(Func<string, string?>? read = nu
PressureRetentionFloor = TimeSpan.FromMinutes(ReadInt64(read, "BOWER_QUEUE_PRESSURE_RETENTION_MINUTES", 60)),
DeliveredRetention = TimeSpan.FromHours(
ReadInt64(read, "BOWER_QUEUE_RETENTION_HOURS", 7 * 24)),
DeadLetterRetention = ReadOptionalDays(read, "BOWER_DEAD_LETTER_RETENTION_DAYS"),
IngestToken = string.IsNullOrWhiteSpace(token) ? null : token,
IngestTokensFile = Blank(read("BOWER_INGEST_TOKENS_FILE")),
ProducerScopesFile = Blank(read("BOWER_PRODUCER_SCOPES_FILE")),
Expand Down Expand Up @@ -500,6 +504,13 @@ public void Validate()
"BOWER_QUEUE_RETENTION_HOURS must be between 1 and 2160.");
}

if (DeadLetterRetention is { } dlqRetention
&& (dlqRetention < TimeSpan.FromDays(1) || dlqRetention > TimeSpan.FromDays(3650)))
{
throw new InvalidOperationException(
"BOWER_DEAD_LETTER_RETENTION_DAYS must be between 1 and 3650.");
}

if (PressureRetentionFloor < TimeSpan.FromMinutes(1) || PressureRetentionFloor > DeliveredRetention)
{
throw new InvalidOperationException(
Expand Down Expand Up @@ -915,6 +926,12 @@ public string ConfigurationHash()
+ PressureRetentionFloor.TotalMinutes.ToString(CultureInfo.InvariantCulture);
}

if (DeadLetterRetention is { } dlqRetention)
{
material += '\u001f' + "dead-letter-retention-days:"
+ dlqRetention.TotalDays.ToString(CultureInfo.InvariantCulture);
}

if (StorageWatermarks != new Bower.Persistence.StorageWatermarkOptions())
{
material += '\u001f' + "storage-watermarks:"
Expand Down Expand Up @@ -1105,6 +1122,22 @@ private static int ReadInt32(Func<string, string?> read, string name, int fallba
: throw new InvalidOperationException($"{name} must be an integer between {int.MinValue} and {int.MaxValue}.");
}

private static TimeSpan? ReadOptionalDays(Func<string, string?> read, string name)
{
string? raw = Blank(read(name));
if (raw is null)
{
return null;
}

if (!long.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out long days))
{
throw new InvalidOperationException($"{name} must be an integer number of days.");
}

return days == 0 ? null : TimeSpan.FromDays(days);
}

private static long ReadInt64(Func<string, string?> read, string name, long fallback)
{
string? value = read(name);
Expand Down
16 changes: 14 additions & 2 deletions src/Bower.Collector/Jobs/ManagementHeartbeatJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ public sealed partial class ManagementHeartbeatJob(
PipelineTelemetry? telemetry = null,
QueueStoragePressure? storagePressure = null,
WindowsEventLogSource? windowsEventLog = null,
WecRuntimeStatusTracker? wecRuntime = null)
WecRuntimeStatusTracker? wecRuntime = null,
CrashRecoveryState? crashRecovery = null)
{
public const string Id = "management-heartbeat";
public const string HttpClientName = "bower-management";
Expand Down Expand Up @@ -89,6 +90,15 @@ private async Task ReportAsync(CancellationToken cancellationToken)
Bower.Persistence.QueuePageUsage? pages = await QueueStorageStatus.TryReadPagesAsync(eventStore, cancellationToken);
QueueStorageStatus? storage = await QueueStorageStatus.TryCaptureAsync(
eventStore, snapshot, storagePressure, telemetry, now, pages, cancellationToken);
long? oldestDeadLetterAge = null;
if (snapshot.DeadLettered > 0 && eventStore is Bower.Persistence.SqliteEventStore sqliteStore)
{
Bower.Persistence.DeadLetterHealth dlqHealth = await sqliteStore.GetDeadLetterHealthAsync(cancellationToken);
if (dlqHealth.OldestReceivedAt is { } oldestDlq)
{
oldestDeadLetterAge = Math.Max(0, (long)(now - oldestDlq).TotalSeconds);
}
}
string deliveryStatus = DeliveryHealth.Evaluate(settings.OutputType, snapshot,
settings.MaximumQueueBytes, now, storage?.IntakePaused ?? false, pages?.UsedPercent);
// Finished command results stay pending until management acknowledges them.
Expand Down Expand Up @@ -178,7 +188,9 @@ private async Task ReportAsync(CancellationToken cancellationToken)
CommandResults = results,
Redactions = telemetry?.RedactionSnapshot(),
Storage = storage,
WecRuntime = wecSnapshots.Count > 0 ? wecSnapshots : null
WecRuntime = wecSnapshots.Count > 0 ? wecSnapshots : null,
OldestDeadLetterAgeSeconds = oldestDeadLetterAge,
Recovery = crashRecovery?.Last
},
CollectorJsonContext.Default.CollectorHeartbeat));
// One budget for the whole exchange, body included: a stalled body cannot hold the
Expand Down
46 changes: 46 additions & 0 deletions src/Bower.Collector/Jobs/QueueRetentionJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ public async Task RunAsync(CancellationToken cancellationToken)

if (queue is SqliteEventStore store)
{
// Opt-in dead-letter retention: warn before expiry and write a ledger evidence record before purge.
await HandleDeadLetterRetentionAsync(store, now, cancellationToken);

// Unverified archive coverage purges nothing, but pages already free still go back.
if (total >= 0)
{
Expand All @@ -75,6 +78,37 @@ public async Task RunAsync(CancellationToken cancellationToken)
}
}

private async Task HandleDeadLetterRetentionAsync(SqliteEventStore store, DateTimeOffset now, CancellationToken cancellationToken)
{
if (settings.DeadLetterRetention is not { } retention)
{
return;
}

DeadLetterHealth health = await store.GetDeadLetterHealthAsync(cancellationToken);
if (health.Count == 0 || health.OldestReceivedAt is null)
{
return;
}

TimeSpan lead = TimeSpan.FromHours(Math.Min(24, Math.Max(1, retention.TotalHours * 0.25)));
DateTimeOffset expiresAt = health.OldestReceivedAt.Value + retention;
if (expiresAt > now && expiresAt - now <= lead)
{
LogDeadLettersApproachingExpiry(logger, health.Count, (long)Math.Max(0, (expiresAt - now).TotalMinutes));
}

DeadLetterPurgeEvidence? evidence = await store.PurgeExpiredDeadLettersAsync(
now - retention,
BatchSize,
now,
cancellationToken);
if (evidence is not null)
{
LogDeadLettersPurged(logger, evidence.PurgedCount, evidence.LedgerSequence);
}
}

/// <summary>Pages returned to the file system per step (8 MiB at 4 KiB pages), so the WAL stays small.</summary>
public const int ReleaseStepPages = 2_048;

Expand Down Expand Up @@ -290,4 +324,16 @@ private static partial void LogPressurePurged(
Level = LogLevel.Warning,
Message = "Queue retention stopped before purging: archive coverage is not verified ({Reason}; first {FirstSequence}, through {ThroughSequence}).")]
private static partial void LogCoverageRefused(ILogger logger, string? reason, long firstSequence, long throughSequence);

[LoggerMessage(
EventId = 1510,
Level = LogLevel.Warning,
Message = "Dead-lettered events ({Count}) are approaching retention expiry; oldest expires in {RemainingMinutes} minute(s). Inspect with 'bower queue dead-letters' or replay before expiry.")]
private static partial void LogDeadLettersApproachingExpiry(ILogger logger, long count, long remainingMinutes);

[LoggerMessage(
EventId = 1511,
Level = LogLevel.Warning,
Message = "Opt-in dead-letter retention purged {Count} expired dead-lettered event(s); evidence recorded at queue ledger sequence {LedgerSequence}.")]
private static partial void LogDeadLettersPurged(ILogger logger, int count, long ledgerSequence);
}
Loading
Loading