diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index ce5b3331..9e14cf17 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -7,6 +7,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +> **Issue #573 — Operate can see what the server is doing.** The server exposed health and Prometheus counters, not the +> queries in flight or which session is blocked on a transaction. This is the **first slice**: a bounded in-memory +> activity registry, the gRPC query path feeding it, the transaction-conflict path recording it, and the admin REST +> endpoint. The gRPC RPC for the same data is not in this slice. + +### Added (Operate, #573) +- **`ManagementActivityRegistry`** (`SharpCoreDB.Server.Core.Observability`) — a bounded, lossy, in-memory record of + active queries (session, database, user, 160-character single-line SQL preview, start + elapsed) and of transaction + conflicts (a session refused `BeginTransaction` because another holds the database's storage transaction, with the + holder named when it can be identified). An entry exists only while the call is genuinely executing; the conflict + queue keeps the last 50. +- **`GET /api/v1/management/activity`** — administrator only (the payload names sessions, users and SQL text). + Documented in `docs/server/REST_API.md` › *Management: live activity*. +- **Recorded on the real paths** — `DatabaseService.ExecuteQuery` and `ExecuteNonQuery` mark a statement while the + engine executes it (the scope is disposed with the call, so an idle server reports nothing), the REST `/query` and + `/execute` endpoints do the same, and the `BeginTransaction` `FailedPrecondition` branch records the conflict. +- `ManagementActivityTests` — 6 cases (live entry for the whole scope, truncation, single-line flattening, conflict with + holder, bounded queue, empty-but-well-formed snapshot). Server suite 307/0. + +### Not in this slice (#573 stays open) +- **No gRPC RPC** for the activity snapshot: adding one is a proto change plus a capability-contract entry, and the + `GrpcCapabilityContract` would then have to advertise it. +- No durable history and no per-query plan/lock introspection — the engine has exactly one storage transaction per + database, so a "lock wait" *is* a transaction conflict; nothing here invents queue positions. + + > **Issue #574 — foreign keys and CHECK constraints reach every metadata route, and a table can be scripted > again.** SCDMS could not offer a table designer, an ER diagram or a schema compare: the client metadata route > exposed a constraint's *kind* but not what a foreign key referenced, the ADO.NET provider exposed no constraint diff --git a/docs/FEATURE_MATRIX.md b/docs/FEATURE_MATRIX.md index 289320f6..000c3ab8 100644 --- a/docs/FEATURE_MATRIX.md +++ b/docs/FEATURE_MATRIX.md @@ -110,6 +110,7 @@ | ADO.NET `GetSchema` | Collections `Tables`, `Columns` (with the key identity flags), `Constraints`, `ForeignKeys`, `CheckConstraints` and `TableScripts`; each accepts a table-name restriction. | | Views | A view is listed by `GetTables` with `Type = VIEW`, its columns are derived statically from its projection (never by executing it) and `information_schema.columns` answers the same list; `IMetadataProvider.GetViews()` carries the definition and the `MATERIALIZED` flag. Views are in-memory only (not persisted across a reopen). | | gRPC capability contract | `GrpcCapabilityContract` lists every RPC the proto declares with its state and every optional package with `overGrpc`/`overSql`; `supported_features` is generated from it, so the server cannot advertise a feature whose RPC answers `UNIMPLEMENTED`. Matrix: `docs/server/GRPC_CAPABILITY_MATRIX.md`; pinned by `GrpcCapabilityContractTests`. | +| Live activity (Operate, #573) | `GET /api/v1/management/activity` (admin) reports the queries in flight (session, database, user, bounded SQL preview, elapsed) and the transaction conflicts — a session refused `BeginTransaction` because another holds the database's storage transaction, with the holder named when it can be identified. In-memory and bounded (last 50 conflicts); no gRPC counterpart yet. Pinned by `ManagementActivityTests`. | | PostgreSQL wire | `pg_constraint`, `pg_index`, `pg_indexes` and the five `information_schema` constraint views are answered by executing the engine's views, so no protocol describes a table differently. | | DDL | `CREATE TABLE … DEFAULT` (constants, folded constants, `CURRENT_TIMESTAMP`/`GETDATE`/`GETUTCDATE`/`NEWID`/`NEWSEQUENTIALID`) parsed, enforced and persisted on both layouts; column-level `REFERENCES`; `ALTER TABLE` ADD/DROP/RENAME COLUMN and `RENAME TO` persisted on both layouts, with existing rows rewritten under the new column set. | | Paging and ordering | `LIMIT n`, `LIMIT n OFFSET m`, `LIMIT m, n`, `LIMIT -1 OFFSET m`, `LIMIT 0`; a bare `OFFSET` is rejected (SQLite's syntax error) rather than ignored; `ORDER BY` reads the whole list — direction, expressions, aliases, ordinals, `COLLATE`, `NULLS FIRST|LAST`, quoted identifiers; clause keywords are matched case-insensitively. | diff --git a/docs/server/REST_API.md b/docs/server/REST_API.md index 637f1700..bd89e8ae 100644 --- a/docs/server/REST_API.md +++ b/docs/server/REST_API.md @@ -402,6 +402,47 @@ curl -fsk -X POST https://localhost:8443/api/v1/query \ curl -fsk "https://localhost:8443/api/v1/schema?database=appdb" \ -H "Authorization: Bearer $TOKEN" ``` +--- + +## Management: live activity (issue #573) + +### GET `/api/v1/management/activity` — administrator only + +What the server is executing **right now**: the queries in flight and the sessions that were refused a transaction +because another session holds the database's storage transaction. The payload names sessions, users and a SQL preview, +which is why it is `admin` only. + +```json +{ + "timestamp": "2026-12-06T08:15:00Z", + "activeSessionCount": 3, + "activeQueries": [ + { + "sessionId": "s-1", + "database": "appdb", + "user": "alice", + "sqlPreview": "SELECT * FROM orders WHERE total > 100", + "startedUtc": "2026-12-06T08:14:59Z", + "elapsedMs": 812.4 + } + ], + "transactionConflicts": [ + { "sessionId": "s-2", "database": "appdb", "user": "bob", "blockedBySession": "s-1", "atUtc": "2026-12-06T08:14:58Z" } + ] +} +``` + +- `activeQueries` is **live**: an entry exists only while the call is executing (recorded around the engine call, removed + when it returns), so an idle server returns an empty list. +- `sqlPreview` is truncated to 160 characters and flattened to one line — never the whole statement. +- `transactionConflicts` is this engine's only "lock wait": one storage transaction per database (#560), so a second + `BeginTransaction` is **refused** rather than queued. The list keeps the last 50 refusals, in memory only — a durable + trail is the audit stream (#576). +- `blockedBySession` is filled only when the holder can be identified; it is empty rather than guessed. +- Covered by `ManagementActivityTests`. There is **no gRPC counterpart yet**; every RPC that exists is listed in + [`GRPC_CAPABILITY_MATRIX.md`](GRPC_CAPABILITY_MATRIX.md). + + --- diff --git a/src/SharpCoreDB.Server.Core/DatabaseService.cs b/src/SharpCoreDB.Server.Core/DatabaseService.cs index c730d7a5..ff7001e1 100644 --- a/src/SharpCoreDB.Server.Core/DatabaseService.cs +++ b/src/SharpCoreDB.Server.Core/DatabaseService.cs @@ -319,6 +319,13 @@ await _tenantQuotaEnforcementService // Issue #556: bound the (synchronous) engine call with the request timeout and the call // cancellation token, so a client that cancels / times out gets a prompt status instead of pinning // a worker until the query finishes. + // Issue #573: advertise the statement while it runs, so Operate can show active queries. + using var activity = ManagementActivityRegistry.Begin( + session.SessionId, + session.DatabaseInstance.Configuration.Name, + session.UserName, + sql); + result = await ExecuteWithTimeoutAsync( () => connection.Database.ExecuteQuery(sql, parameters), request.TimeoutMs, @@ -482,6 +489,13 @@ await _tenantQuotaEnforcementService var sql = request.Sql; var parameters = ToParameterDictionary(request.Parameters); + // Issue #573: a write is work the server is executing too, so it belongs in the activity snapshot. + using var activity = ManagementActivityRegistry.Begin( + session.SessionId, + session.DatabaseInstance.Configuration.Name, + session.UserName, + sql); + // Row-level policy: validate writes against tenant discriminator if (_rowLevelPolicyEngine is not null) { @@ -639,6 +653,13 @@ public override async Task BeginTransaction(BeginTxRequest requ catch (InvalidOperationException ex) { // Only one storage transaction may be open per database; surface the conflict as a precondition failure. + // Issue #573: record it, so Operate can show which session is blocked and who holds the transaction. + ManagementActivityRegistry.RecordTransactionConflict( + session.SessionId, + session.DatabaseInstance.Configuration.Name, + session.UserName, + FindTransactionHolder(session)); + _logger.LogWarning(ex, "Begin transaction rejected for session {SessionId}", request.SessionId); throw new RpcException(new Status(StatusCode.FailedPrecondition, ex.Message)); } @@ -868,6 +889,28 @@ private static MetricData BuildMetric( /// not implement in 2.3.x (issue #555). The message distinguishes "not built yet" from a wrong call; before this, /// every such RPC answered with an empty status detail. /// + /// + /// Finds the session that holds the database's storage transaction, so a recorded conflict can name it + /// (issue #573). Returns null when no other session on the same database holds one — the engine refused + /// for another reason, and guessing a holder would be worse than saying nothing. + /// + /// The session that was refused. + /// The holding session's id, or null. + private string? FindTransactionHolder(ClientSession blocked) + { + foreach (var candidate in _sessionManager.GetActiveSessions()) + { + if (!candidate.SessionId.Equals(blocked.SessionId, StringComparison.Ordinal) && + candidate.HasActiveTransaction && + ReferenceEquals(candidate.DatabaseInstance, blocked.DatabaseInstance)) + { + return candidate.SessionId; + } + } + + return null; + } + private static RpcException NotImplemented(string method) => new(new Status( StatusCode.Unimplemented, diff --git a/src/SharpCoreDB.Server.Core/Observability/ManagementActivityRegistry.cs b/src/SharpCoreDB.Server.Core/Observability/ManagementActivityRegistry.cs new file mode 100644 index 00000000..d5d4ba17 --- /dev/null +++ b/src/SharpCoreDB.Server.Core/Observability/ManagementActivityRegistry.cs @@ -0,0 +1,211 @@ +// +// Copyright (c) 2026 MPCoreDeveloper and GitHub Copilot. All rights reserved. +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// + +namespace SharpCoreDB.Server.Core.Observability; + +using System; +using System.Collections.Generic; +using System.Diagnostics; + +/// One query that is running right now (issue #573). +/// The session that issued it. +/// The database it runs against. +/// The authenticated user, when the session has one. +/// A bounded preview of the statement (never the whole text). +/// When it started. +/// How long it has been running, measured at snapshot time. +public sealed record ActiveQueryEntry( + string SessionId, + string Database, + string User, + string SqlPreview, + DateTimeOffset StartedUtc, + double ElapsedMs); + +/// +/// A session that asked to BeginTransaction while another one already holds the database's storage +/// transaction. That is the only "lock wait" this engine has: one storage transaction per database (#560), so the +/// second caller is refused rather than queued — the refusal is what a monitor has to show. +/// +/// The session that was refused. +/// The database it asked for. +/// The authenticated user, when the session has one. +/// The session that holds the transaction, when it is known. +/// When the refusal happened. +public sealed record TransactionConflict( + string SessionId, + string Database, + string User, + string BlockedBySession, + DateTimeOffset AtUtc); + +/// The activity snapshot an Operate view renders (issue #573). +/// When the snapshot was taken. +/// Sessions the SessionManager currently holds. +/// The queries executing right now, oldest first. +/// The most recent refusals, oldest first (bounded). +public sealed record ManagementActivity( + DateTimeOffset Timestamp, + int ActiveSessionCount, + IReadOnlyList ActiveQueries, + IReadOnlyList TransactionConflicts); + +/// +/// A bounded, process-wide record of what the server is executing right now (issue #573: the server exposed health +/// and Prometheus counters only — no active queries, no blocked sessions, no lock waits). +/// +/// Deliberately in memory and lossy: a monitor must not grow without bound, so an in-flight entry is removed by the +/// scope that created it and the conflict queue keeps the last . Nothing here is durable — +/// that is the audit stream's job (#576). +/// +/// +/// Truthfulness rules: an entry exists only while a call is genuinely executing (the scope is disposed in a +/// finally), the SQL preview is truncated to characters, and the only "wait" this +/// engine can produce is a transaction conflict — reported as one, never as a generic "lock wait". +/// +/// +public static class ManagementActivityRegistry +{ + /// How many characters of a statement a snapshot carries. + public const int PreviewLength = 160; + + /// How many active entries are kept (a flood drops the newest rather than growing). + public const int MaxActiveQueries = 256; + + /// How many transaction conflicts are kept. + public const int MaxConflicts = 50; + + private static readonly Lock Gate = new(); + private static readonly Dictionary Running = []; + private static readonly Queue Conflicts = new(); + private static long _sequence; + + /// + /// Marks a query as running until the returned scope is disposed. Always dispose it in a finally. + /// + /// The session issuing the query. + /// The database it runs against. + /// The authenticated user, when known. + /// The statement (truncated in the entry). + /// A scope that removes the entry when disposed. + public static IDisposable Begin(string sessionId, string database, string? user, string sql) + { + var id = Interlocked.Increment(ref _sequence); + var entry = new InFlight( + sessionId ?? string.Empty, + database ?? string.Empty, + user ?? string.Empty, + Preview(sql), + DateTimeOffset.UtcNow, + Stopwatch.GetTimestamp()); + + lock (Gate) + { + if (Running.Count < MaxActiveQueries) + { + Running[id] = entry; + } + } + + return new Scope(id); + } + + /// + /// Records that a session was refused a transaction because another one holds it. + /// + /// The refused session. + /// The database it asked for. + /// The authenticated user, when known. + /// The session holding the transaction, when known. + public static void RecordTransactionConflict(string sessionId, string database, string? user, string? blockedBySession) + { + var conflict = new TransactionConflict( + sessionId ?? string.Empty, + database ?? string.Empty, + user ?? string.Empty, + blockedBySession ?? string.Empty, + DateTimeOffset.UtcNow); + + lock (Gate) + { + Conflicts.Enqueue(conflict); + while (Conflicts.Count > MaxConflicts) + { + Conflicts.Dequeue(); + } + } + } + + /// + /// Takes a snapshot of the current activity. + /// + /// The session count the caller read from the SessionManager. + /// The snapshot; both lists are copies. + public static ManagementActivity Snapshot(int activeSessionCount) + { + var timestamp = Stopwatch.GetTimestamp(); + + lock (Gate) + { + List queries = new(Running.Count); + foreach (var entry in Running.Values) + { + queries.Add(new ActiveQueryEntry( + entry.SessionId, + entry.Database, + entry.User, + entry.SqlPreview, + entry.StartedUtc, + Stopwatch.GetElapsedTime(entry.StartedTimestamp, timestamp).TotalMilliseconds)); + } + + queries.Sort(static (left, right) => left.StartedUtc.CompareTo(right.StartedUtc)); + return new ManagementActivity(DateTimeOffset.UtcNow, activeSessionCount, queries, [.. Conflicts]); + } + } + + /// Clears the registry. Test-only entry point. + public static void Reset() + { + lock (Gate) + { + Running.Clear(); + Conflicts.Clear(); + } + } + + private static string Preview(string sql) + { + var text = (sql ?? string.Empty).Trim().ReplaceLineEndings(" "); + return text.Length <= PreviewLength ? text : text[..PreviewLength] + "…"; + } + + private sealed record InFlight( + string SessionId, + string Database, + string User, + string SqlPreview, + DateTimeOffset StartedUtc, + long StartedTimestamp); + + private sealed class Scope(long id) : IDisposable + { + private bool _disposed; + + public void Dispose() + { + if (_disposed) + { + return; + } + + _disposed = true; + lock (Gate) + { + Running.Remove(id); + } + } + } +} diff --git a/src/SharpCoreDB.Server/DatabaseController.cs b/src/SharpCoreDB.Server/DatabaseController.cs index a7053d41..118a51f7 100644 --- a/src/SharpCoreDB.Server/DatabaseController.cs +++ b/src/SharpCoreDB.Server/DatabaseController.cs @@ -67,6 +67,14 @@ await tenantQuotaEnforcementService .ConfigureAwait(false); await using var connection = await db.GetConnectionAsync(cancellationToken); + + // Issue #573: a REST query is work the server is executing too, so it belongs in the activity snapshot. + using var activity = ManagementActivityRegistry.Begin( + session.SessionId, + db.Configuration.Name, + session.UserName, + request.Sql); + var result = connection.Database.ExecuteQuery(request.Sql, request.Parameters ?? []); var columns = Array.Empty(); @@ -147,6 +155,14 @@ await tenantQuotaEnforcementService .ConfigureAwait(false); await using var connection = await db.GetConnectionAsync(cancellationToken); + + // Issue #573: a REST write is work the server is executing too, so it belongs in the activity snapshot. + using var activity = ManagementActivityRegistry.Begin( + session.SessionId, + db.Configuration.Name, + session.UserName, + request.Sql); + connection.Database.ExecuteSQL(request.Sql); var elapsed = Stopwatch.GetElapsedTime(start); @@ -478,6 +494,17 @@ public IActionResult GetMetrics() }); } + /// + /// Gets what the server is executing right now — the queries in flight and the transaction conflicts — for the + /// Operate view (issue #573). Administrator only: the payload names sessions, users and a SQL preview. + /// + /// The current activity snapshot. + [HttpGet("management/activity")] + [Authorize(Roles = "admin")] + [ProducesResponseType(typeof(ManagementActivity), 200)] + public IActionResult GetManagementActivity() => + Ok(ManagementActivityRegistry.Snapshot(sessionManager.ActiveSessionCount)); + /// /// Gets recent tenant access authorization audit events. /// diff --git a/tests/SharpCoreDB.Server.IntegrationTests/ManagementActivityTests.cs b/tests/SharpCoreDB.Server.IntegrationTests/ManagementActivityTests.cs new file mode 100644 index 00000000..eea44e22 --- /dev/null +++ b/tests/SharpCoreDB.Server.IntegrationTests/ManagementActivityTests.cs @@ -0,0 +1,101 @@ +// +// Copyright (c) 2026 MPCoreDeveloper and GitHub Copilot. All rights reserved. +// Licensed under the MIT License. See LICENSE file in the project root for full license information. +// + +using SharpCoreDB.Server.Core.Observability; +using Xunit; + +namespace SharpCoreDB.Server.IntegrationTests; + +/// +/// Issue #573: the server exposed health and Prometheus counters only, so Operate could not show what is executing, +/// which session is blocked, or what holds the transaction. is the record the +/// REST endpoint GET /api/v1/management/activity renders; these cases pin what it may and may not say. +/// +public sealed class ManagementActivityTests +{ + public ManagementActivityTests() => ManagementActivityRegistry.Reset(); + + [Fact] + public void Snapshot_WhileAQueryRuns_ListsItForTheWholeScope() + { + using (ManagementActivityRegistry.Begin("session-1", "testdb", "admin", "SELECT * FROM users")) + { + var activity = ManagementActivityRegistry.Snapshot(activeSessionCount: 3); + + var entry = Assert.Single(activity.ActiveQueries); + Assert.Equal("session-1", entry.SessionId); + Assert.Equal("testdb", entry.Database); + Assert.Equal("admin", entry.User); + Assert.Equal("SELECT * FROM users", entry.SqlPreview); + Assert.Equal(3, activity.ActiveSessionCount); + Assert.True(entry.ElapsedMs >= 0); + } + + // The scope is what removes the entry: an idle server reports nothing. + Assert.Empty(ManagementActivityRegistry.Snapshot(0).ActiveQueries); + } + + [Fact] + public void Snapshot_TruncatesALongStatement() + { + var sql = "SELECT " + new string('x', 500) + " FROM users"; + + using (ManagementActivityRegistry.Begin("session-1", "testdb", "admin", sql)) + { + var preview = Assert.Single(ManagementActivityRegistry.Snapshot(0).ActiveQueries).SqlPreview; + + Assert.Equal(ManagementActivityRegistry.PreviewLength + 1, preview.Length); // + the ellipsis + Assert.EndsWith("…", preview, StringComparison.Ordinal); + } + } + + [Fact] + public void Snapshot_FlattensAStatementToASingleLine() + { + using (ManagementActivityRegistry.Begin("session-1", "testdb", "admin", "SELECT *\r\nFROM users")) + { + Assert.Equal("SELECT * FROM users", Assert.Single(ManagementActivityRegistry.Snapshot(0).ActiveQueries).SqlPreview); + } + } + + [Fact] + public void Snapshot_ReportsATransactionConflictWithItsHolder() + { + ManagementActivityRegistry.RecordTransactionConflict("blocked-session", "testdb", "writer", "holder-session"); + + var conflict = Assert.Single(ManagementActivityRegistry.Snapshot(0).TransactionConflicts); + + Assert.Equal("blocked-session", conflict.SessionId); + Assert.Equal("holder-session", conflict.BlockedBySession); + Assert.Equal("testdb", conflict.Database); + } + + [Fact] + public void Snapshot_KeepsTheConflictQueueBounded() + { + for (int i = 0; i < ManagementActivityRegistry.MaxConflicts + 10; i++) + { + ManagementActivityRegistry.RecordTransactionConflict($"session-{i}", "testdb", "writer", "holder"); + } + + var conflicts = ManagementActivityRegistry.Snapshot(0).TransactionConflicts; + + Assert.Equal(ManagementActivityRegistry.MaxConflicts, conflicts.Count); + // The newest are kept, the oldest are dropped. + Assert.Equal($"session-{ManagementActivityRegistry.MaxConflicts + 9}", conflicts[^1].SessionId); + Assert.DoesNotContain(conflicts, conflict => conflict.SessionId == "session-0"); + } + + [Fact] + public void Snapshot_WithNoActivity_IsEmptyButWellFormed() + { + var activity = ManagementActivityRegistry.Snapshot(activeSessionCount: 2); + + Assert.Equal(2, activity.ActiveSessionCount); + Assert.Empty(activity.ActiveQueries); + Assert.Empty(activity.TransactionConflicts); + Assert.NotEqual(default, activity.Timestamp); + } +}