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
26 changes: 26 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions docs/FEATURE_MATRIX.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
41 changes: 41 additions & 0 deletions docs/server/REST_API.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).



---

Expand Down
43 changes: 43 additions & 0 deletions src/SharpCoreDB.Server.Core/DatabaseService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
{
Expand Down Expand Up @@ -639,6 +653,13 @@ public override async Task<BeginTxResponse> 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));
}
Expand Down Expand Up @@ -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.
/// </summary>
/// <summary>
/// Finds the session that holds the database's storage transaction, so a recorded conflict can name it
/// (issue #573). Returns <c>null</c> 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.
/// </summary>
/// <param name="blocked">The session that was refused.</param>
/// <returns>The holding session's id, or <c>null</c>.</returns>
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,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
// <copyright file="ManagementActivityRegistry.cs" company="MPCoreDeveloper">
// 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.
// </copyright>

namespace SharpCoreDB.Server.Core.Observability;

using System;
using System.Collections.Generic;
using System.Diagnostics;

/// <summary>One query that is running right now (issue #573).</summary>
/// <param name="SessionId">The session that issued it.</param>
/// <param name="Database">The database it runs against.</param>
/// <param name="User">The authenticated user, when the session has one.</param>
/// <param name="SqlPreview">A bounded preview of the statement (never the whole text).</param>
/// <param name="StartedUtc">When it started.</param>
/// <param name="ElapsedMs">How long it has been running, measured at snapshot time.</param>
public sealed record ActiveQueryEntry(
string SessionId,
string Database,
string User,
string SqlPreview,
DateTimeOffset StartedUtc,
double ElapsedMs);

/// <summary>
/// A session that asked to <c>BeginTransaction</c> 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.
/// </summary>
/// <param name="SessionId">The session that was refused.</param>
/// <param name="Database">The database it asked for.</param>
/// <param name="User">The authenticated user, when the session has one.</param>
/// <param name="BlockedBySession">The session that holds the transaction, when it is known.</param>
/// <param name="AtUtc">When the refusal happened.</param>
public sealed record TransactionConflict(
string SessionId,
string Database,
string User,
string BlockedBySession,
DateTimeOffset AtUtc);

/// <summary>The activity snapshot an Operate view renders (issue #573).</summary>
/// <param name="Timestamp">When the snapshot was taken.</param>
/// <param name="ActiveSessionCount">Sessions the <c>SessionManager</c> currently holds.</param>
/// <param name="ActiveQueries">The queries executing right now, oldest first.</param>
/// <param name="TransactionConflicts">The most recent refusals, oldest first (bounded).</param>
public sealed record ManagementActivity(
DateTimeOffset Timestamp,
int ActiveSessionCount,
IReadOnlyList<ActiveQueryEntry> ActiveQueries,
IReadOnlyList<TransactionConflict> TransactionConflicts);

/// <summary>
/// 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).
/// <para>
/// 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 <see cref="MaxConflicts"/>. Nothing here is durable —
/// that is the audit stream's job (#576).
/// </para>
/// <para>
/// Truthfulness rules: an entry exists only while a call is genuinely executing (the scope is disposed in a
/// <c>finally</c>), the SQL preview is truncated to <see cref="PreviewLength"/> characters, and the only "wait" this
/// engine can produce is a transaction conflict — reported as one, never as a generic "lock wait".
/// </para>
/// </summary>
public static class ManagementActivityRegistry
{
/// <summary>How many characters of a statement a snapshot carries.</summary>
public const int PreviewLength = 160;

/// <summary>How many active entries are kept (a flood drops the newest rather than growing).</summary>
public const int MaxActiveQueries = 256;

/// <summary>How many transaction conflicts are kept.</summary>
public const int MaxConflicts = 50;

private static readonly Lock Gate = new();
private static readonly Dictionary<long, InFlight> Running = [];
private static readonly Queue<TransactionConflict> Conflicts = new();
private static long _sequence;

/// <summary>
/// Marks a query as running until the returned scope is disposed. Always dispose it in a <c>finally</c>.
/// </summary>
/// <param name="sessionId">The session issuing the query.</param>
/// <param name="database">The database it runs against.</param>
/// <param name="user">The authenticated user, when known.</param>
/// <param name="sql">The statement (truncated in the entry).</param>
/// <returns>A scope that removes the entry when disposed.</returns>
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);
}

/// <summary>
/// Records that a session was refused a transaction because another one holds it.
/// </summary>
/// <param name="sessionId">The refused session.</param>
/// <param name="database">The database it asked for.</param>
/// <param name="user">The authenticated user, when known.</param>
/// <param name="blockedBySession">The session holding the transaction, when known.</param>
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();
}
}
}

/// <summary>
/// Takes a snapshot of the current activity.
/// </summary>
/// <param name="activeSessionCount">The session count the caller read from the <c>SessionManager</c>.</param>
/// <returns>The snapshot; both lists are copies.</returns>
public static ManagementActivity Snapshot(int activeSessionCount)
{
var timestamp = Stopwatch.GetTimestamp();

lock (Gate)
{
List<ActiveQueryEntry> 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]);
}
}

/// <summary>Clears the registry. Test-only entry point.</summary>
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);
}
}
}
}
Loading
Loading