diff --git a/src/Jiaowu.Api/Controllers/ClickHouseAnalyticsController.cs b/src/Jiaowu.Api/Controllers/ClickHouseAnalyticsController.cs
index ab82825..24696e3 100644
--- a/src/Jiaowu.Api/Controllers/ClickHouseAnalyticsController.cs
+++ b/src/Jiaowu.Api/Controllers/ClickHouseAnalyticsController.cs
@@ -71,7 +71,20 @@ public sealed class ClickHouseAnalyticsController(
sum(studentCount) AS totalStudentCount,
sum(averageScore * studentCount) AS totalWeightedScore,
sum(passedCount) AS totalPassedCount
- FROM {options.Database}.gradeStatistics FINAL
+ FROM
+ (
+ SELECT gradeSheetId,
+ latest.1 AS academicTermId, latest.2 AS academicTermName,
+ latest.3 AS collegeId, latest.4 AS studentCount,
+ latest.5 AS averageScore, latest.6 AS passedCount
+ FROM
+ (
+ SELECT gradeSheetId,
+ argMax(tuple(academicTermId, academicTermName, collegeId, studentCount, averageScore, passedCount), projectedAt) AS latest
+ FROM {options.Database}.gradeStatistics
+ GROUP BY gradeSheetId
+ )
+ )
WHERE 1 = 1{collegeFilter}
GROUP BY academicTermId
) AS gradeTotals
diff --git a/src/Jiaowu.Api/Infrastructure/Analytics/ClickHouseAnalyticsClient.cs b/src/Jiaowu.Api/Infrastructure/Analytics/ClickHouseAnalyticsClient.cs
index 3d9440d..c55e8e3 100644
--- a/src/Jiaowu.Api/Infrastructure/Analytics/ClickHouseAnalyticsClient.cs
+++ b/src/Jiaowu.Api/Infrastructure/Analytics/ClickHouseAnalyticsClient.cs
@@ -78,8 +78,36 @@ public sealed class ClickHouseAnalyticsClient(
{
if (rows.Count == 0) return;
var payload = JsonSerializer.Serialize(rows, JsonOptions);
+ // Compare against ClickHouse itself, rather than a process-local cache. A
+ // failed insert, application restart, or a rebuilt analytics database is
+ // therefore retried naturally on the next projection pass.
+ var (schema, columns, keys) = table switch
+ {
+ "auditEvents" => (
+ "id UUID, occurredAt DateTime64(3, 'UTC'), userId Nullable(UUID), method String, path String, statusCode UInt16, ipAddress Nullable(String), projectedAt DateTime64(3, 'UTC')",
+ "id,occurredAt,userId,method,path,statusCode,ipAddress", "id"),
+ "attendanceRecords" => (
+ "attendanceSheetId UUID, studentId UUID, attendanceDate Date, teachingTaskId UUID, academicTermId UUID, collegeId UUID, status UInt8, checkInAt Nullable(DateTime64(3, 'UTC')), checkedInMethod Nullable(UInt8), appealStatus UInt8, projectedAt DateTime64(3, 'UTC')",
+ "attendanceSheetId,studentId,attendanceDate,teachingTaskId,academicTermId,collegeId,status,checkInAt,checkedInMethod,appealStatus", "attendanceSheetId,studentId"),
+ "gradeStatistics" => (
+ "gradeSheetId UUID, teachingTaskId UUID, courseId UUID, academicTermId UUID, collegeId UUID, academicTermName String, studentCount UInt32, passedCount UInt32, excellentCount UInt32, averageScore Decimal(8,2), passRate Decimal(8,4), excellentRate Decimal(8,4), calculatedAt DateTime64(3, 'UTC'), projectedAt DateTime64(3, 'UTC')",
+ "gradeSheetId,teachingTaskId,courseId,academicTermId,collegeId,academicTermName,studentCount,passedCount,excellentCount,averageScore,passRate,excellentRate,calculatedAt", "gradeSheetId"),
+ _ => throw new ArgumentOutOfRangeException(nameof(table))
+ };
+ var fields = columns.Split(',');
+ var join = string.Join(" AND ", keys.Split(',').Select(key => $"incoming.{key} = existing.{key}"));
+ var projectedFields = string.Join(",", fields.Select(field => $"incoming.{field}"));
await ExecuteAsync(
- $"INSERT INTO {options.Database}.{table} FORMAT JSONEachRow\n{ToJsonLines(payload)}",
+ $"""
+ INSERT INTO {options.Database}.{table} ({columns},projectedAt)
+ SELECT {projectedFields},incoming.projectedAt
+ FROM (SELECT *, cityHash64(tuple({columns})) AS fingerprint FROM input('{schema.Replace("'", "\\'")}')) AS incoming
+ LEFT ANTI JOIN
+ (SELECT {keys}, cityHash64(argMax(tuple({columns}), projectedAt)) AS fingerprint FROM {options.Database}.{table} GROUP BY {keys}) AS existing
+ ON {join} AND incoming.fingerprint = existing.fingerprint
+ FORMAT JSONEachRow
+ {ToJsonLines(payload)}
+ """,
cancellationToken);
}
@@ -94,6 +122,20 @@ public sealed class ClickHouseAnalyticsClient(
.EnumerateArray().Select(x => x.Clone()).ToArray();
}
+ public Task DeleteMissingAsync(string table, IReadOnlyCollection<(Guid First, Guid Second)> keys,
+ DateTime cutoff, CancellationToken cancellationToken)
+ {
+ if (keys.Count == 0) return Task.CompletedTask;
+ var predicate = table switch
+ {
+ "auditEvents" => $"id IN ({string.Join(',', keys.Select(x => $"toUUID('{x.First:D}')"))})",
+ "gradeStatistics" => $"gradeSheetId IN ({string.Join(',', keys.Select(x => $"toUUID('{x.First:D}')"))})",
+ "attendanceRecords" => $"(attendanceSheetId, studentId) IN ({string.Join(',', keys.Select(x => $"(toUUID('{x.First:D}'),toUUID('{x.Second:D}'))"))})",
+ _ => throw new ArgumentOutOfRangeException(nameof(table))
+ };
+ return ExecuteAsync($"ALTER TABLE {options.Database}.{table} DELETE WHERE ({predicate}) AND projectedAt < toDateTime64('{cutoff:yyyy-MM-dd HH:mm:ss.fff}', 3, 'UTC') SETTINGS mutations_sync = 1", cancellationToken);
+ }
+
private async Task ExecuteAsync(string sql, CancellationToken cancellationToken)
{
using var response = await SendAsync(sql, cancellationToken);
diff --git a/src/Jiaowu.Api/Infrastructure/Analytics/ClickHouseAnalyticsProjectionWorker.cs b/src/Jiaowu.Api/Infrastructure/Analytics/ClickHouseAnalyticsProjectionWorker.cs
index 4ac839f..cbb9101 100644
--- a/src/Jiaowu.Api/Infrastructure/Analytics/ClickHouseAnalyticsProjectionWorker.cs
+++ b/src/Jiaowu.Api/Infrastructure/Analytics/ClickHouseAnalyticsProjectionWorker.cs
@@ -7,7 +7,7 @@ namespace Jiaowu.Api.Infrastructure.Analytics;
///
/// Projects MySQL facts to ClickHouse. The projection is deliberately
/// best-effort: business writes never depend on an analytics database.
-/// ReplacingMergeTree plus FINAL reads make repeated lookback batches safe.
+/// Each batch is compared with the latest stored values before insertion.
///
public sealed class ClickHouseAnalyticsProjectionWorker(
IServiceScopeFactory scopeFactory,
@@ -52,11 +52,51 @@ public sealed class ClickHouseAnalyticsProjectionWorker(
var auditCount = await ProjectAuditsAsync(db, from, projectedAt, cancellationToken);
var attendanceCount = await ProjectAttendanceAsync(db, from.Date, projectedAt, cancellationToken);
var gradeCount = await ProjectGradesAsync(db, projectedAt, cancellationToken);
+ foreach (var table in new[] { "auditEvents", "attendanceRecords", "gradeStatistics" })
+ await ReconcileDeletesAsync(db, table, projectedAt, cancellationToken);
logger.LogInformation(
"ClickHouse 分析投影完成:审计 {AuditCount},考勤 {AttendanceCount},成绩 {GradeCount}。",
auditCount, attendanceCount, gradeCount);
}
+ private async Task ReconcileDeletesAsync(AppDbContext db, string table, DateTime cutoff, CancellationToken token)
+ {
+ var firstColumn = table switch { "auditEvents" => "id", "attendanceRecords" => "attendanceSheetId", "gradeStatistics" => "gradeSheetId", _ => throw new ArgumentOutOfRangeException(nameof(table)) };
+ var pair = table == "attendanceRecords";
+ var columns = pair ? $"{firstColumn},studentId" : firstColumn;
+ (Guid First, Guid Second)? cursor = null;
+ while (true)
+ {
+ var where = cursor is null ? "" : pair
+ ? $"WHERE ({firstColumn},studentId) > (toUUID('{cursor.Value.First:D}'),toUUID('{cursor.Value.Second:D}'))"
+ : $"WHERE {firstColumn} > toUUID('{cursor.Value.First:D}')";
+ var second = pair ? ", toString(studentId) AS second" : "";
+ var rows = await client.QueryAsync($"SELECT toString({firstColumn}) AS first{second} FROM {options.Database}.{table} {where} GROUP BY {columns} ORDER BY {columns} LIMIT {options.BatchSize}", token);
+ if (rows.Length == 0) return;
+ var keys = rows.Select(row => (First: Guid.Parse(row.GetProperty("first").GetString()!), Second: pair ? Guid.Parse(row.GetProperty("second").GetString()!) : Guid.Empty)).ToArray();
+ var ids = keys.Select(x => x.First).Distinct().ToArray();
+ HashSet<(Guid First, Guid Second)> existing;
+ if (pair)
+ {
+ var students = keys.Select(x => x.Second).Distinct().ToArray();
+ var found = await db.AttendanceRecords.AsNoTracking().Where(x => ids.Contains(x.AttendanceSheetId) && students.Contains(x.StudentId)).Select(x => new { x.AttendanceSheetId, x.StudentId }).ToListAsync(token);
+ existing = found.Select(x => (x.AttendanceSheetId, x.StudentId)).ToHashSet();
+ }
+ else if (table == "auditEvents")
+ {
+ var found = await db.AuditLogs.AsNoTracking().Where(x => ids.Contains(x.Id)).Select(x => x.Id).ToListAsync(token);
+ existing = found.Select(x => (x, Guid.Empty)).ToHashSet();
+ }
+ else
+ {
+ var found = await db.TeachingTaskGradeStatistics.AsNoTracking().Where(x => ids.Contains(x.GradeSheetId)).Select(x => x.GradeSheetId).ToListAsync(token);
+ existing = found.Select(x => (x, Guid.Empty)).ToHashSet();
+ }
+ await client.DeleteMissingAsync(table, keys.Where(key => !existing.Contains(key)).ToArray(), cutoff, token);
+ cursor = keys[^1];
+ }
+ }
+
private async Task ProjectAuditsAsync(AppDbContext db, DateTime from, DateTime projectedAt, CancellationToken cancellationToken)
{
var cursorAt = from;
diff --git a/src/Jiaowu.Api/Infrastructure/Grades/CourseGradeStatisticsService.cs b/src/Jiaowu.Api/Infrastructure/Grades/CourseGradeStatisticsService.cs
index 54e25fb..7929ca9 100644
--- a/src/Jiaowu.Api/Infrastructure/Grades/CourseGradeStatisticsService.cs
+++ b/src/Jiaowu.Api/Infrastructure/Grades/CourseGradeStatisticsService.cs
@@ -61,6 +61,12 @@ public sealed class CourseGradeStatisticsRefreshJobProcessor(
x.Student.AdministrativeClass.Major!.CollegeId))
.ToListAsync(cancellationToken);
+ await db.ExecuteInRetriableTransactionAsync(async transaction =>
+ {
+ // A retry must not reuse entities accepted by a failed SaveChanges.
+ db.ChangeTracker.Clear();
+ var currentJob = await db.CourseGradeStatisticsRefreshJobs
+ .FirstAsync(x => x.Id == jobId, cancellationToken);
var now = DateTime.UtcNow;
var rebuilt = new List();
AddStatistics(CourseGradeStatisticScope.AdministrativeClass,
@@ -106,9 +112,11 @@ public sealed class CourseGradeStatisticsRefreshJobProcessor(
if (rebuiltTeachingTasks.Count > 0)
db.TeachingTaskGradeStatistics.AddRange(rebuiltTeachingTasks);
- job.Status = CourseGradeStatisticsRefreshJobStatus.Succeeded;
- job.CompletedAt = now;
+ currentJob.Status = CourseGradeStatisticsRefreshJobStatus.Succeeded;
+ currentJob.CompletedAt = now;
await db.SaveChangesAsync(cancellationToken);
+ await transaction.CommitAsync(cancellationToken);
+ }, cancellationToken);
await cache.RemoveByTagAsync(AppCacheTags.CourseGradeStatistics,
cancellationToken);
await studentAcademicStatistics.RefreshForGradeSheetAsync(
@@ -117,8 +125,11 @@ public sealed class CourseGradeStatisticsRefreshJobProcessor(
}
catch (Exception exception)
{
- job.Status = CourseGradeStatisticsRefreshJobStatus.Failed;
- job.ErrorMessage = exception.GetBaseException().Message[..Math.Min(2000,
+ db.ChangeTracker.Clear();
+ var failedJob = await db.CourseGradeStatisticsRefreshJobs
+ .FirstAsync(x => x.Id == jobId, CancellationToken.None);
+ failedJob.Status = CourseGradeStatisticsRefreshJobStatus.Failed;
+ failedJob.ErrorMessage = exception.GetBaseException().Message[..Math.Min(2000,
exception.GetBaseException().Message.Length)];
await db.SaveChangesAsync(CancellationToken.None);
logger.LogError(exception, "Course grade statistics refresh {JobId} failed.", jobId);