Compare commits

...
Author SHA1 Message Date
CI 47bd0289f5 Bump version to 0.1.0-RC.10 [skip ci] 2026-11-28 00:21:30 +00:00
james.maes 933e9644cd Merge develop into release/0.1 (promote QQQ 4.1.0-RC.40)
maven / build (push) Successful in 8m23s
build / maven (push) Successful in 8m23s
2026-11-27 18:12:22 -06:00
james.maes 93a603546c Merge pull request 'chore: update to qbit-build-parent 2.3.0-RC.1 and QQQ 4.1.0-RC.40' (#44) from chore/qqq-4.1.0-rc40 into develop
maven / build (push) Successful in 4m48s
build / maven (push) Successful in 4m48s
2026-11-27 23:47:48 +00:00
james.maesandClaude Sonnet 5.5 ec7220de37 chore: update to qbit-build-parent 2.3.0-RC.1 and QQQ 4.1.0-RC.40
maven / build (push) Successful in 3m21s
build / maven (push) Successful in 3m20s
- qbit-build-parent 2.2.1 -> 2.3.0-RC.1
- qqq 4.1.0-RC.26 -> 4.1.0-RC.40

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 17:38:55 -06:00
james.maes 6b8bae4d94 Merge pull request 'fix: per-unit N+1 findings, readable numbers, fallback attribution (#13 #14 #15)' (#43) from fix/issues-13-14-15-stored-rules-attribution into develop
maven / build (push) Successful in 8m6s
build / maven (push) Successful in 27m46s
2026-11-27 01:44:26 +00:00
james.maesandClaude Sonnet 5.5 b71d1cc43f fix: per-unit N+1 findings, readable numbers and fallback attribution
maven / build (push) Successful in 5m50s
build / maven (push) Successful in 5m57s
- N_PLUS_ONE groups repeat patterns by (unitKind, unitName), dedupes on
  rule + unit and lists the top 5 repeated statement shapes as evidence (#13)
- NumberText: grouping / K,M,B suffixes, one-decimal percentages, no
  scientific notation in rule summaries and evidence; MISSING_INDEX names
  its candidate columns (#14)
- AttributionListener names statements without a UnitOfWork by reported
  process, outermost process on the action stack, then thread-name pattern
  instead of one anonymous (none) bucket (#15)

Fixes #13
Fixes #14
Fixes #15

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 18:53:44 -06:00
CI 10944ef4d1 Bump version to 0.1.0-RC.9 [skip ci] 2026-11-20 16:02:27 +00:00
james.maes 6877cff128 Merge pull request 'feat: createDate and modifyDate on every table (0.1)' (#42) from feat/table-standard-dates-0.1 into release/0.1
maven / build (push) Successful in 4m44s
build / maven (push) Successful in 4m44s
2026-11-20 15:58:04 +00:00
james.maes 30d9a7c536 Merge pull request 'feat: createDate and modifyDate on every table' (#41) from feat/table-standard-dates into develop
maven / build (push) Successful in 4m49s
build / maven (push) Successful in 4m49s
2026-11-20 15:58:02 +00:00
james.maesandClaude Fable 5.2 94e3562c34 feat: createDate and modifyDate on every table
maven / build (push) Successful in 5m10s
build / maven (push) Successful in 5m9s
All 17 tables declare both dates (date-time, not editable, QQQ create-date and
modify-date behaviors). Changesets 35 to 51 add the missing columns, nullable
with a default of the current time so a previous release keeps working during
a rolling deployment, and fill existing rows. Upgrade notes carry the host DDL.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 08:40:50 -06:00
CI ef1a4777c9 Bump version to 0.1.0-RC.8 [skip ci] 2026-11-07 18:43:07 +00:00
james.maes 817e061db5 Merge pull request 'Merge develop into release/0.1 (Gitea-aligned RC)' (#40) from align/develop-into-release-0.1 into release/0.1
maven / build (push) Successful in 3m43s
build / maven (push) Successful in 3m42s
2026-11-07 18:37:47 +00:00
james.maesandClaude Opus 5.5 6f37d96a72 Merge develop into release/0.1 (Gitea-aligned RC)
maven / build (push) Canceled after 0s
build / maven (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 12:37:27 -06:00
james.maesandCodex a600ddc604 ci: centralize release branch verification and workflows (#25)
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 13:27:17 -05:00
CircleCI f452f13850 Bump version to 0.1.0-RC.7 [skip ci] 2026-10-16 21:04:46 +00:00
james.maesandClaude Opus 5.5 a48aaf0346 Merge develop into release/0.1 for 0.1.0-RC.7 (#17 bounded spikes)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 15:59:25 -05:00
CircleCI 5499041383 Bump version to 0.1.0-RC.6 [skip ci] 2026-10-16 20:24:46 +00:00
james.maesandClaude Opus 5.5 6116aa6804 Merge develop into release/0.1 for 0.1.0-RC.6 (#16 bounded attribution reads, fixes the hourly dbPerfAnalyze OOM)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 15:20:11 -05:00
CircleCI ffee1b833f Bump version to 0.1.0-RC.5 [skip ci] 2026-10-15 23:06:11 +00:00
james.maesandClaude Opus 5.5 c250196ab0 Merge develop into release/0.1 for 0.1.0-RC.5 (#12 collector fix)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 18:02:48 -05:00
CircleCI f18abcb97a Bump version to 0.1.0-RC.4 [skip ci] 2026-10-15 22:18:15 +00:00
james.maesandClaude Opus 5.5 b849e2ed91 Merge develop into release/0.1 for 0.1.0-RC.4 (#11 one active attribution runtime per JVM)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 17:14:44 -05:00
CircleCI f865f87dee Bump version to 0.1.0-RC.3 [skip ci] 2026-10-15 19:18:07 +00:00
github-actions[bot] 57d22da621 Merge develop into release/0.1 for the next 0.1.0 RC 2026-10-15 19:15:46 +00:00
CircleCI f9b717ac73 Bump version to 0.1.0-RC.2 [skip ci] 2026-10-15 18:27:46 +00:00
github-actions[bot] 045629fd0d Merge develop into release/0.1 for the next 0.1.0 RC 2026-10-15 18:25:13 +00:00
CircleCI 73495c3fc0 Bump version to 0.1.0-RC.1 [skip ci] 2026-10-15 17:58:56 +00:00
10 changed files with 541 additions and 35 deletions

No files matched your search

+4
View File
@@ -16,6 +16,10 @@ All notable changes are documented here. This project follows Keep a Changelog a
- The previous-snapshot baseline no longer depends on a PostgreSQL-only counter (it uses the database size every supported provider records).
### Fixed
- N+1 findings are one per unit of work, not one per statement shape (#13). The kof22 production run produced 81 findings, 40 for one scheduled job. `N_PLUS_ONE` now groups repeat patterns by unit kind and name, aggregates pods and windows per shape before applying the thresholds, dedupes on rule + unit, and lists the five worst repeated shapes (table, repeats, normalized SQL) in the evidence. Existing per-shape findings close as "No longer detected" on the next analysis and are replaced by the per-unit finding.
- Finding summaries and evidence read as people write numbers (#14): grouping up to 99,999, K/M/B suffixes above, percentages to one decimal, megabytes with one decimal, never scientific notation (`1.77403392E7 sequential tuples/day; 100.0% sequential scans` is now `17.7M sequential tuples/day; 100.0% sequential scans; candidate columns: status`). `MISSING_INDEX` names its candidate columns in the summary. The formatting lives in `NumberText` and applies to every rule's evidence table.
- Statements without a core unit of work are no longer one anonymous `OTHER` / `(none)` bucket (#15; 334k of 430k attributed statements on kof22). Attribution names them by the process the statement reports, else by the outermost process or backend step on the QQQ action stack (`process:<name>`), else by the thread name with its numbers collapsed (`thread:alerts-worker-#`), and only then `(none)`. The unit kind stays `OTHER`; names are bounded so the key limit still holds. Opening real units in core for durable job chunks, health runner and alerts workers remains a core change.
- Query-spike alerts no longer hold seven days of query snapshots as records on every snapshot evaluation (~230,000 rows at kof22's rate). `SnapshotEvaluator` reads the window in 1,000-row keyset pages and keeps only each statement's current interval time, latest capture time and earlier interval times as primitive doubles; the spike rule (twelve prior samples, median, absence after an hour) is unchanged.
- The Attribution home panel no longer loads a day of attribution detail into the heap. It sums statements and time per unit and table in the database (at most 5,000 groups), so a render holds about a thousand aggregate rows instead of the roughly 570,000 detail rows (540 MB in PostgreSQL) that ran the kof22 web pod out of memory on 2026-10-16. The daily attribution rollup reads the day in 1,000-row keyset pages (`DbPerfStore.forEachPage`), so worker memory is bounded by distinct dimension keys, not by the day's row count. The hourly analysis (`dbPerfAnalyze`) reads attribution the same way: `RuleContext.window("attribution", ...)` returns database sums per unit, table and operation instead of every detail row (it filled the kof22 worker heap to ~1.8 GB every hour).
- Collection no longer stops at RUNNING on large production statement sets: list folding in the SQL normalizer is a linear token scan (the nested-repetition regular expressions overflowed the stack on 60 KB statements with long IN/VALUES lists). Any failure, including an `Error`, now closes the run as FAILED with the exception class, logs it at ERROR (class and frame only, never SQL text) and raises the collection alert; runs left RUNNING by a crash are closed as FAILED after three intervals.
+4 -1
View File
@@ -25,7 +25,10 @@ still refreshes settings so administrators can re-enable it.
Units are sampled once and buffered until completion, allowing HTTP route names
to be finalized. A completed unit belongs to the window in which it ends; an
abandoned unit is merged when that worker sees a different unit. No-unit work is
sampled per statement and counted as one unit per statement. Sampling transitions
sampled per statement and counted as one unit per statement. It is named by the
process the statement reports, else the outermost process or backend step on the
action stack (`process:<name>`), else the thread name with digit runs collapsed
(`thread:pool-#-thread-#`), else `(none)`; its kind is `OTHER`. Sampling transitions
retain separate aggregates for each effective rate. Values are observed counts,
not extrapolated estimates. Daily rollups sum those counts across windows and
pods and take the maximum duration.
+1 -1
View File
@@ -156,7 +156,7 @@ automatically unless a person IGNORED it; an IGNORED finding stays ignored.
| `MISSING_INDEX` | tables with heavy sequential scans and statements filtering on unindexed columns | seq vs idx scans, tuples read, statement predicates | **ready-to-commit Liquibase changeset** (`CREATE INDEX CONCURRENTLY IF NOT EXISTS ...`, `runInTransaction:false`) |
| `UNUSED_INDEX` | non-unique, non-primary indexes with zero scans since stats reset (minimum age) | size, write cost | Liquibase `DROP INDEX CONCURRENTLY IF EXISTS` snippet |
| `DUPLICATE_INDEX` | identical or prefix-redundant indexes on the same table | both definitions, sizes | drop snippet for the redundant one |
| `N_PLUS_ONE` | repeated statement shapes in one unit of work | unit, statement, max/total repeats | batch the lookups (one query with `IN`) |
| `N_PLUS_ONE` | repeated statement shapes in one unit of work; one finding per unit, however many shapes repeat | unit, worst repeated statements, max/total repeats | batch the lookups (one query with `IN`) |
| `HOT_JOB` | scheduled jobs and processes with the most database time | attribution totals | review schedule or batching |
| `OVER_AUDITED` | QQQ audit tables with high write volume relative to their source tables | inserts per day, size | lower audit level on noisy tables |
| `BLOAT` | tables with high dead-tuple ratio | n_dead/n_live, size | autovacuum settings per table |
+4 -4
View File
@@ -18,8 +18,8 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<properties>
<qqq.version>4.1.0-RC.26</qqq.version> <!-- feeds qbit-build-parent's qqq-bom-pom import -->
<revision>0.1.0-SNAPSHOT</revision>
<qqq.version>4.1.0-RC.40</qqq.version> <!-- feeds qbit-build-parent's qqq-bom-pom import -->
<revision>0.1.0-RC.10</revision>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<jacoco.version>0.8.15</jacoco.version>
@@ -29,7 +29,7 @@
<parent>
<groupId>com.kingsrook</groupId>
<artifactId>qbit-build-parent</artifactId>
<version>2.2.1</version>
<version>2.3.0-RC.1</version>
</parent>
<groupId>com.kingsrook.qbits</groupId>
@@ -249,7 +249,7 @@
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<qqq.snapshot.version>4.1.0-RC.26</qqq.snapshot.version>
<qqq.snapshot.version>4.1.0-RC.40</qqq.snapshot.version>
</properties>
<dependencyManagement>
<dependencies>
@@ -0,0 +1,138 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2026. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.dbperformance.analyze;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
/*******************************************************************************
** Human-readable numbers for finding summaries and evidence. Counts never use
** scientific notation: small values are grouped ("12,345"), large values get a
** K, M or B suffix ("17.7M"). Percentages always carry one decimal ("100.0%").
*******************************************************************************/
public final class NumberText
{
private static final double SUFFIX_FROM = 100_000;
private static final String NOT_AVAILABLE = "n/a";
/*******************************************************************************
** Utility class.
*******************************************************************************/
private NumberText()
{
}
/*******************************************************************************
** Format a count or measurement: grouping up to 99,999.9, then K/M/B with one
** decimal. Fractions keep at most one decimal; whole values keep none.
*******************************************************************************/
public static String number(double value)
{
if(Double.isNaN(value) || Double.isInfinite(value))
{
return (NOT_AVAILABLE);
}
double magnitude = Math.abs(value);
if(magnitude < SUFFIX_FROM)
{
return (grouped(value, "#,##0.#"));
}
String suffix = "K";
double scaled = value / 1_000;
if(magnitude >= 999_950_000)
{
suffix = "B";
scaled = value / 1_000_000_000;
}
else if(magnitude >= 999_950)
{
suffix = "M";
scaled = value / 1_000_000;
}
return (grouped(scaled, "#,##0.#") + suffix);
}
/*******************************************************************************
** Format a percentage already expressed in percent units, to one decimal.
*******************************************************************************/
public static String percent(double value)
{
if(Double.isNaN(value) || Double.isInfinite(value))
{
return (NOT_AVAILABLE);
}
return (grouped(value, "#,##0.0") + "%");
}
/*******************************************************************************
** Format a size already expressed in megabytes, grouping from 1,000 MB.
*******************************************************************************/
public static String megabytes(double value)
{
if(Double.isNaN(value) || Double.isInfinite(value))
{
return (NOT_AVAILABLE);
}
return (grouped(value, "#,##0.0") + " MB");
}
/*******************************************************************************
** Format any evidence cell. Any number uses {@link #number(double)};
** everything else is its plain text.
*******************************************************************************/
public static String text(Object value)
{
if(value instanceof Number number)
{
return (number(number.doubleValue()));
}
return (String.valueOf(value));
}
/*******************************************************************************
** Round half up with a fixed Latin grouping style, independent of the JVM
** locale so that findings read the same on every host.
*******************************************************************************/
private static String grouped(double value, String pattern)
{
DecimalFormat format = new DecimalFormat(pattern, DecimalFormatSymbols.getInstance(Locale.ROOT));
format.setRoundingMode(RoundingMode.HALF_UP);
format.setGroupingSize(3);
String result = format.format(value);
return (result.equals("-0") || result.equals("-0.0") ? result.substring(1) : result);
}
}
@@ -50,6 +50,9 @@ public enum StoredRule implements DbPerfRule
OVER_AUDITED, BLOAT, VACUUM_STALE, POOL_SIZING, IDLE_IN_TRANSACTION,
CACHE_HIT_LOW, TEMP_SPILL, DEADLOCKS;
/** Most repeated statement shapes an N+1 finding lists as evidence. */
private static final int TOP_REPEATED_SHAPES = 5;
/*******************************************************************************
** Seed identity.
@@ -128,7 +131,7 @@ public enum StoredRule implements DbPerfRule
String recommendation = "Open the [Query plan action](/record/db_perf_statement/" + row.getValueInteger("id")
+ ") to inspect this query, or [Explain in SQL Workbench](" + ctx.runtime.getConfig().getSqlWorkbenchRunnerPath() + "?sql=" + sql + "). Review scan and join costs before changing indexes.";
findings.add(draft(ctx, row.getValueString("id"), share / 100, "High query execution cost over 24 hours",
evidence("Calls", n(row, "calls24h"), "Mean ms", n(row, "meanMs24h"), "Total ms", n(row, "totalMs24h"), "DB time %", share), recommendation, null, row, "statement", null));
evidence("Calls", n(row, "calls24h"), "Mean ms", n(row, "meanMs24h"), "Total ms", n(row, "totalMs24h"), "Share of DB time", NumberText.percent(share)), recommendation, null, row, "statement", null));
}
}
return (findings);
@@ -170,18 +173,18 @@ public enum StoredRule implements DbPerfRule
}
if(!columns.isEmpty())
{
String reason = reads + " sequential tuples/day; " + n(table, "seqScanShare") + "% sequential scans";
String reason = NumberText.number(reads) + " sequential tuples/day; " + NumberText.percent(n(table, "seqScanShare")) + " sequential scans; candidate columns: " + String.join(", ", columns);
findings.add(draft(ctx, subject, n(table, "seqScanShare") / 100, reason,
evidence("Sequential scan %", n(table, "seqScanShare"), "Tuples/day", reads, "Candidate columns", String.join(", ", columns)),
evidence("Sequential scans", NumberText.percent(n(table, "seqScanShare")), "Tuples read per day", reads, "Candidate columns", String.join(", ", columns)),
"Check Query plan and selectivity for " + String.join(", ", columns) + ". Review the suggested column order and migration before committing it.",
MigrationSnippets.create(ctx.now, table, List.copyOf(columns), reason), table, "table", null));
}
}
else if(this == BLOAT && n(table, "deadRatio") >= ctx.threshold(1) && n(table, "nDeadTup") >= ctx.threshold(2))
{
String reason = n(table, "nDeadTup") + " dead tuples (" + n(table, "deadRatio") + "%)";
String reason = NumberText.number(n(table, "nDeadTup")) + " dead tuples (" + NumberText.percent(n(table, "deadRatio")) + " of the table)";
findings.add(draft(ctx, subject, n(table, "deadRatio") / 100, reason,
evidence("Dead tuples", n(table, "nDeadTup"), "Live tuples", n(table, "nLiveTup"), "Dead %", n(table, "deadRatio")),
evidence("Dead tuples", n(table, "nDeadTup"), "Live tuples", n(table, "nLiveTup"), "Dead share", NumberText.percent(n(table, "deadRatio"))),
"Review long transactions and autovacuum capacity. Consider a lower per-table vacuum scale factor; the optional rollback resets it to the server default.",
MigrationSnippets.vacuum(ctx.now, table, reason), table, "table", null));
}
@@ -216,7 +219,7 @@ public enum StoredRule implements DbPerfRule
}
}
String contributors = units.entrySet().stream().sorted(Map.Entry.<String, Double>comparingByValue().reversed()).limit(5)
.map(e -> e.getKey() + " (" + e.getValue() + " inserts)").collect(Collectors.joining(", "));
.map(e -> e.getKey() + " (" + NumberText.number(e.getValue()) + " inserts)").collect(Collectors.joining(", "));
Map<String, Double> sources = new LinkedHashMap<>();
for(QRecord row : ctx.window("attribution", 1))
{
@@ -228,7 +231,7 @@ public enum StoredRule implements DbPerfRule
}
}
String sourceTables = sources.entrySet().stream().sorted(Map.Entry.<String, Double>comparingByValue().reversed()).limit(5)
.map(e -> e.getKey() + " (" + e.getValue() + " writes)").collect(Collectors.joining(", "));
.map(e -> e.getKey() + " (" + NumberText.number(e.getValue()) + " writes)").collect(Collectors.joining(", "));
findings.add(draft(ctx, subject, Math.min(1, inserts / Math.max(1, ctx.threshold(1) * 10)), "High audit insert volume",
evidence("Audit inserts/day", inserts, "Attributed units", contributors.isEmpty() ? "Unavailable" : contributors),
"Lower AuditLevel on noisy source tables after reviewing audit requirements. " + (contributors.isEmpty() ? "Source-table attribution is unavailable." : "Largest audit-producing units: " + contributors + ".")
@@ -259,7 +262,7 @@ public enum StoredRule implements DbPerfRule
String reason = null;
if(this == UNUSED_INDEX && n(index, "idxScan") == 0 && ctx.statsAgeDays() >= ctx.threshold(1) && n(index, "sizeBytes") / 1048576 >= ctx.threshold(2))
{
reason = "Zero scans over " + ctx.statsAgeDays() + " days; " + n(index, "sizeBytes") / 1048576 + " MB";
reason = "Zero scans over " + NumberText.number(ctx.statsAgeDays()) + " days; " + NumberText.megabytes(n(index, "sizeBytes") / 1048576);
}
if(this == DUPLICATE_INDEX && plainIndex(index))
{
@@ -311,29 +314,84 @@ public enum StoredRule implements DbPerfRule
/*******************************************************************************
** Aggregate pods/windows before applying the minimum affected-unit threshold.
** One finding per unit of work (kind and name), however many statement shapes
** repeat in it: a scheduled job that repeats forty different lookups is one
** problem, not forty findings. Pods and windows are aggregated per shape before
** the thresholds apply; the unit's finding lists its worst shapes as evidence
** and dedupes on rule + unit.
*******************************************************************************/
private List<FindingDraft> repeats(RuleContext ctx) throws Exception
{
Map<String, List<QRecord>> groups = group(ctx.window("repeat_pattern", 1), "unitKind", "unitName", "fingerprint");
List<FindingDraft> findings = new ArrayList<>();
for(var entry : groups.entrySet())
for(var unitEntry : group(ctx.window("repeat_pattern", 1), "unitKind", "unitName").entrySet())
{
List<QRecord> rows = entry.getValue();
double max = rows.stream().mapToDouble(r -> n(r, "maxRepeats")).max().orElse(0);
double units = rows.stream().mapToDouble(r -> n(r, "unitsAffected")).sum();
if(max >= ctx.threshold(1) && units >= ctx.threshold(2))
List<RepeatedShape> shapes = new ArrayList<>();
for(List<QRecord> rows : group(unitEntry.getValue(), "fingerprint").values())
{
QRecord row = rows.getFirst();
findings.add(draft(ctx, entry.getKey(), Math.min(1, max / Math.max(1, ctx.threshold(1) * 10)), "Repeated queries in " + row.getValueString("unitKind") + " " + row.getValueString("unitName"),
evidence("Max repeats", max, "Units affected", units, "Total repeats", rows.stream().mapToDouble(r -> n(r, "totalRepeats")).sum()),
"Batch lookups on " + row.getValueString("tableName") + " in " + row.getValueString("unitName") + " into one query with IN (...), a QQQ QueryJoin, or a record pre-fetch.", null, row, "unit", row.getValueString("unitName")));
RepeatedShape shape = new RepeatedShape(rows.getFirst(), rows.stream().mapToDouble(r -> n(r, "maxRepeats")).max().orElse(0),
rows.stream().mapToDouble(r -> n(r, "unitsAffected")).sum(), rows.stream().mapToDouble(r -> n(r, "totalRepeats")).sum());
if(shape.max() >= ctx.threshold(1) && shape.units() >= ctx.threshold(2))
{
shapes.add(shape);
}
}
if(shapes.isEmpty())
{
continue;
}
shapes.sort(Comparator.comparingDouble(RepeatedShape::max).reversed().thenComparing(Comparator.comparingDouble(RepeatedShape::total).reversed())
.thenComparing(shape -> String.valueOf(shape.row().getValueString("fingerprint"))));
QRecord worst = shapes.getFirst().row();
String unitKind = worst.getValueString("unitKind");
String unitName = worst.getValueString("unitName");
double max = shapes.getFirst().max();
List<Object> cells = new ArrayList<>(List.of("Repeated statement shapes", shapes.size(), "Max repeats", max,
"Units affected", shapes.stream().mapToDouble(RepeatedShape::units).max().orElse(0), "Total repeats", shapes.stream().mapToDouble(RepeatedShape::total).sum()));
Set<String> tables = new LinkedHashSet<>();
int rank = 0;
for(RepeatedShape shape : shapes.stream().limit(TOP_REPEATED_SHAPES).toList())
{
rank++;
String table = shape.row().getValueString("tableName");
if(table != null && !table.isBlank())
{
tables.add(table);
}
String statement = shape.row().getValueString("sqlText");
if(statement == null || statement.isBlank())
{
String fingerprint = String.valueOf(shape.row().getValueString("fingerprint"));
statement = "fingerprint " + fingerprint.substring(0, Math.min(12, fingerprint.length()));
}
cells.add("Repeated statement #" + rank);
cells.add((table == null ? "(unknown table)" : table) + ": up to " + NumberText.number(shape.max()) + " repeats per unit, " + NumberText.number(shape.total())
+ " in total; " + statement.substring(0, Math.min(160, statement.length())) + (statement.length() > 160 ? "..." : ""));
}
if(shapes.size() > TOP_REPEATED_SHAPES)
{
cells.add("Other repeated statement shapes");
cells.add(shapes.size() - TOP_REPEATED_SHAPES);
}
String shapeText = shapes.size() == 1 ? "" : " (" + shapes.size() + " repeated statement shapes)";
String onTables = tables.isEmpty() ? "" : " on " + String.join(", ", tables);
findings.add(draft(ctx, unitEntry.getKey(), Math.min(1, max / Math.max(1, ctx.threshold(1) * 10)), "Repeated queries in " + unitKind + " " + unitName + shapeText,
evidence(cells.toArray()),
"Batch the repeated lookups" + onTables + " in " + unitName + " into one query with IN (...), a QQQ QueryJoin, or a record pre-fetch."
+ (shapes.size() > 1 ? " Start with the statements listed in the evidence, worst first." : ""), null, worst, "unit", unitName));
}
return (findings);
}
/*******************************************************************************
** One repeated statement shape of a unit, aggregated across pods and windows.
*******************************************************************************/
private record RepeatedShape(QRecord row, double max, double units, double total)
{
}
/*******************************************************************************
** Share is relative to all attributed work, including HTTP routes.
*******************************************************************************/
@@ -350,7 +408,7 @@ public enum StoredRule implements DbPerfRule
if(List.of("SCHEDULED_JOB", "PROCESS").contains(row.getValueString("unitKind")) && total > 0 && share * 100 >= ctx.threshold(1))
{
findings.add(draft(ctx, entry.getKey(), share, "Expensive " + row.getValueString("unitKind") + " " + row.getValueString("unitName"),
evidence("Total ms", time, "Attributed time %", share * 100), "Review the schedule and batch database operations in " + row.getValueString("unitName") + ".", null, row, "unit", row.getValueString("unitName")));
evidence("Total ms", time, "Attributed time", NumberText.percent(share * 100)), "Review the schedule and batch database operations in " + row.getValueString("unitName") + ".", null, row, "unit", row.getValueString("unitName")));
}
}
return (findings);
@@ -395,7 +453,7 @@ public enum StoredRule implements DbPerfRule
+ " across replicas (peak active " + e.getValue().intValue() + ")").collect(Collectors.joining("; "));
String applications = peaks.entrySet().stream().map(e -> e.getKey() + ": peak " + e.getValue().intValue()).collect(Collectors.joining("; "));
return (List.of(draft(ctx, "database", Math.max(peak, idle) / 100, "Review connection pool sizes",
evidence("Peak used %", peak, "Peak idle %", idle, "Max connections", maxConnections, "Application peaks", applications),
evidence("Peak used", NumberText.percent(peak), "Peak idle", NumberText.percent(idle), "Max connections", maxConnections, "Application peaks", applications),
"Starting pool sizes from observed active demand: " + sizes + ". Validate under representative load and divide combined caps across replicas; reserve capacity for administration and other applications. Observed application peaks: " + applications,
null, null, "database", null)));
}
@@ -435,7 +493,7 @@ public enum StoredRule implements DbPerfRule
var average = snapshots.stream().filter(r -> r.getValue("cacheHitRatio") != null).mapToDouble(r -> n(r, "cacheHitRatio")).average();
if(average.isPresent() && average.getAsDouble() < ctx.threshold(1))
{
findings.add(draft(ctx, "database", 1 - average.getAsDouble() / 100, "Low average database cache hit ratio", evidence("Average hit %", average.getAsDouble(), "OK snapshots", snapshots.size()),
findings.add(draft(ctx, "database", 1 - average.getAsDouble() / 100, "Low average database cache hit ratio", evidence("Average hit ratio", NumberText.percent(average.getAsDouble()), "OK snapshots", snapshots.size()),
"Review query scans and the working set before increasing database memory.", null, null, "database", null));
}
}
@@ -459,13 +517,13 @@ public enum StoredRule implements DbPerfRule
{
QRecord statement = statements.get(entry.getValue().getFirst().getValueInteger("statementId"));
findings.add(draft(ctx, entry.getKey(), mb / Math.max(1, databaseMb), "Query spilled temporary data to disk",
evidence("Query temp MB", mb, "Database temp MB", databaseMb), "Inspect sorts and hash joins in Query plan. Tune the query and review work_mem per operation, accounting for concurrent queries.", null, statement, "statement", null));
evidence("Query temp", NumberText.megabytes(mb), "Database temp", NumberText.megabytes(databaseMb)), "Inspect sorts and hash joins in Query plan. Tune the query and review work_mem per operation, accounting for concurrent queries.", null, statement, "statement", null));
}
}
if(databaseMb >= ctx.threshold(1))
{
findings.add(draft(ctx, "database", Math.min(1, databaseMb / Math.max(1, ctx.threshold(1) * 10)), "Database temporary disk spill",
evidence("Database temp MB in 24h", databaseMb), "Review spilling queries, including those outside the stored top-N. Size work_mem with concurrency in mind.", null, null, "database", null));
evidence("Database temp in 24h", NumberText.megabytes(databaseMb)), "Review spilling queries, including those outside the stored top-N. Size work_mem with concurrency in mind.", null, null, "database", null));
}
}
return (findings);
@@ -513,7 +571,7 @@ public enum StoredRule implements DbPerfRule
StringBuilder text = new StringBuilder("| Measurement | Value |\n| --- | --- |\n");
for(int i = 0; i < cells.length; i += 2)
{
text.append("| ").append(cells[i]).append(" | ").append(String.valueOf(cells[i + 1]).replace("|", "\\|").replace("\n", " ")).append(" |\n");
text.append("| ").append(cells[i]).append(" | ").append(NumberText.text(cells[i + 1]).replace("|", "\\|").replace("\n", " ")).append(" |\n");
}
return (text.toString());
}
@@ -26,10 +26,12 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import java.util.regex.Pattern;
import com.kingsrook.qbits.dbperformance.DbPerfQBitConfig;
import com.kingsrook.qbits.dbperformance.DbPerfRuntime;
import com.kingsrook.qbits.dbperformance.normalize.SqlNormalizer;
@@ -37,6 +39,9 @@ import com.kingsrook.qqq.backend.core.context.QContext;
import com.kingsrook.qqq.backend.core.instrumentation.StatementExecution;
import com.kingsrook.qqq.backend.core.instrumentation.StatementExecutionListener;
import com.kingsrook.qqq.backend.core.instrumentation.UnitOfWork;
import com.kingsrook.qqq.backend.core.model.actions.AbstractActionInput;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunProcessInput;
import com.kingsrook.qqq.backend.core.model.data.QRecord;
@@ -48,6 +53,7 @@ public class AttributionListener implements StatementExecutionListener
{
private static final String OTHER = "(other)";
private static final Key OVERFLOW = new Key("OTHER", OTHER, OTHER, OTHER, "OTHER", SqlNormalizer.fingerprint(OTHER), -1);
private static final Pattern THREAD_NUMBERS = Pattern.compile("[0-9]+");
private static final ThreadLocal<Boolean> SUPPRESSED = ThreadLocal.withInitial(() -> false);
private final DbPerfRuntime runtime;
private final ConcurrentHashMap<String, Shape> shapes = new ConcurrentHashMap<>();
@@ -97,7 +103,7 @@ public class AttributionListener implements StatementExecutionListener
return;
}
Shape shape = shape(execution.sql());
Key key = new Key(unit == null ? "OTHER" : unit.getKind().name(), unit == null ? name(execution.processName()) : "",
Key key = new Key(unit == null ? "OTHER" : unit.getKind().name(), unit == null ? fallbackName(execution) : "",
execution.processName(), execution.tableName(), execution.operation() == null ? "OTHER" : execution.operation().name(), shape.fingerprint(), buffer == null ? copy.sampleRate() : buffer.settings.sampleRate());
if(buffer == null)
{
@@ -232,6 +238,73 @@ public class AttributionListener implements StatementExecutionListener
}
/*******************************************************************************
** Name work that runs outside any unit of work (alert, health and ESB workers,
** durable job chunks, executor threads). In order: the process the statement
** reports; the outermost process or step on the action stack; the thread name
** with its numbers collapsed (pool-3-thread-7 becomes thread:pool-#-thread-#);
** a stable "(none)". Bounded cardinality: no ids, no timestamps.
*******************************************************************************/
static String fallbackName(StatementExecution execution)
{
String process = execution.processName();
if(process != null && !process.isBlank())
{
return (process);
}
String action = outermostProcess();
if(action != null)
{
return (action);
}
return (threadPattern(Thread.currentThread().getName()));
}
/*******************************************************************************
** The outermost process (or backend step) running on this thread's action
** stack, as "process:<name>"; null when none is running.
*******************************************************************************/
private static String outermostProcess()
{
try
{
Stack<AbstractActionInput> stack = QContext.getActionStack();
if(stack != null)
{
for(AbstractActionInput input : stack)
{
String processName = input instanceof RunProcessInput process ? process.getProcessName()
: input instanceof RunBackendStepInput step ? step.getProcessName() : null;
if(processName != null && !processName.isBlank())
{
return ("process:" + processName);
}
}
}
}
catch(RuntimeException e)
{
return (null); // the stack is advisory; attribution must never break a statement
}
return (null);
}
/*******************************************************************************
** Collapse digit runs so that worker pools share one name, as "thread:...".
*******************************************************************************/
static String threadPattern(String threadName)
{
if(threadName == null || threadName.isBlank())
{
return (name(null));
}
String pattern = THREAD_NUMBERS.matcher(threadName.trim()).replaceAll("#");
return ("thread:" + pattern.substring(0, Math.min(100, pattern.length())));
}
/*******************************************************************************
** Use a stable label for units without a name.
*******************************************************************************/
@@ -28,6 +28,7 @@ import com.kingsrook.qbits.dbperformance.analyze.AnalyzeService;
import com.kingsrook.qbits.dbperformance.analyze.DbPerfRule;
import com.kingsrook.qbits.dbperformance.analyze.FindingDraft;
import com.kingsrook.qbits.dbperformance.analyze.FindingService;
import com.kingsrook.qbits.dbperformance.analyze.NumberText;
import com.kingsrook.qbits.dbperformance.analyze.RuleContext;
import com.kingsrook.qbits.dbperformance.analyze.StoredRule;
import com.kingsrook.qbits.dbperformance.collect.DbPerfStore;
@@ -211,6 +212,87 @@ class StoredRuleTest
}
/*******************************************************************************
** Forty repeated statement shapes in one scheduled job are one finding for that
** unit, deduped on rule + unit and listing only the worst few shapes.
*******************************************************************************/
@Test
void repeatsGroupByUnitNotByStatementShape() throws Exception
{
B1Fixture f = new B1Fixture();
for(int i = 0; i < 7; i++)
{
repeat("SCHEDULED_JOB", "alertsEscalateAndRemind", "alert_table_" + i, String.valueOf(i).repeat(64), 20 + i, 6L, "select * from alert_table_" + i + " where id = ?");
}
repeat("SCHEDULED_JOB", "alertsEscalateAndRemind", "quiet_table", "f".repeat(64), 3, 6L, "select 1");
repeat("SCHEDULED_JOB", "alertsEvaluateMonitors", "monitor", "e".repeat(64), 12, 5L, null);
repeat("SCHEDULED_JOB", "tooFewUnits", "orders", "d".repeat(64), 50, 1L, "select 1");
List<FindingDraft> drafts = StoredRule.N_PLUS_ONE.evaluate(f.context(StoredRule.N_PLUS_ONE));
assertThat(drafts).extracting(FindingDraft::unitName).containsExactlyInAnyOrder("shipOrders", "alertsEscalateAndRemind", "alertsEvaluateMonitors");
assertThat(drafts).extracting(FindingDraft::dedupeKey).doesNotHaveDuplicates();
FindingDraft job = drafts.stream().filter(d -> "alertsEscalateAndRemind".equals(d.unitName())).findFirst().orElseThrow();
assertThat(job.summary()).isEqualTo("Repeated queries in SCHEDULED_JOB alertsEscalateAndRemind (7 repeated statement shapes)");
assertThat(job.dedupeKey()).startsWith("N_PLUS_ONE:").doesNotContain("0".repeat(64));
assertThat(job.evidence()).contains("| Repeated statement shapes | 7 |", "| Max repeats | 26 |", "| Units affected | 6 |", "| Total repeats | 966 |", "| Other repeated statement shapes | 2 |");
assertThat(job.evidence()).contains("| Repeated statement #1 | alert_table_6: up to 26 repeats per unit", "select * from alert_table_6 where id = ?", "| Repeated statement #5 | alert_table_2:")
.doesNotContain("Repeated statement #6", "alert_table_1:", "quiet_table");
assertThat(job.recommendation()).contains("alert_table_6", "worst first");
FindingDraft single = drafts.stream().filter(d -> "alertsEvaluateMonitors".equals(d.unitName())).findFirst().orElseThrow();
assertThat(single.summary()).isEqualTo("Repeated queries in SCHEDULED_JOB alertsEvaluateMonitors");
assertThat(single.evidence()).contains("| Repeated statement #1 | monitor: up to 12 repeats per unit, 60 in total; fingerprint eeeeeeeeeeee |");
FindingService service = new FindingService(f.runtime, B1Fixture.CLOCK);
assertThat(service.apply(f.backend, "N_PLUS_ONE", drafts).created()).isEqualTo(3);
assertThat(service.apply(f.backend, "N_PLUS_ONE", StoredRule.N_PLUS_ONE.evaluate(f.context(StoredRule.N_PLUS_ONE))).updated()).isEqualTo(3);
assertThat(RuleContext.read("db_perf_finding", new QQueryFilter())).hasSize(3);
}
/*******************************************************************************
** Counts and percentages read as people write them, never as 1.77403392E7.
*******************************************************************************/
@Test
void summariesAreHumanReadable() throws Exception
{
B1Fixture f = new B1Fixture();
DbPerfStore.update("db_perf_table_snapshot", List.of(new QRecord().withValue("id", RuleContext.read("db_perf_table_snapshot", new QQueryFilter()).getFirst().getValueInteger("id"))
.withValue("seqTupRead", 17_740_339L).withValue("nTupIns", 1_234_567L)));
DbPerfStore.update("db_perf_table_stat", List.of(new QRecord().withValue("id", f.table.getValueInteger("id")).withValue("seqScanShare", 100).withValue("nDeadTup", 1_234_567L).withValue("deadRatio", new BigDecimal("30.25"))));
FindingDraft missing = StoredRule.MISSING_INDEX.evaluate(f.context(StoredRule.MISSING_INDEX)).getFirst();
String perDay = NumberText.number(f.context(StoredRule.MISSING_INDEX).perDay(f.table, "seqTupRead"));
assertThat(perDay).matches("[0-9,.]+[KMB]?").isNotEqualTo("0");
assertThat(missing.summary()).isEqualTo(perDay + " sequential tuples/day; 100.0% sequential scans; candidate columns: status");
assertThat(missing.evidence()).contains("| Sequential scans | 100.0% |", "| Tuples read per day | " + perDay + " |", "| Candidate columns | status |");
FindingDraft bloat = StoredRule.BLOAT.evaluate(f.context(StoredRule.BLOAT)).getFirst();
assertThat(bloat.summary()).isEqualTo("1.2M dead tuples (30.3% of the table)");
assertThat(bloat.evidence()).contains("| Dead tuples | 1.2M |", "| Dead share | 30.3% |");
for(StoredRule rule : StoredRule.values())
{
for(FindingDraft draft : rule.evaluate(f.context(rule)))
{
assertThat(draft.summary() + " " + draft.evidence() + " " + draft.recommendation()).as(rule.code()).doesNotContainPattern("[0-9][Ee][+-]?[0-9]");
}
}
}
/*******************************************************************************
** One repeat_pattern row for a unit and statement shape.
*******************************************************************************/
private static void repeat(String kind, String unit, String table, String fingerprint, int max, long units, String sql) throws Exception
{
B1Fixture.insert("repeat_pattern", new QRecord().withValue("windowStart", B1Fixture.NOW.minusSeconds(60)).withValue("windowEnd", B1Fixture.NOW)
.withValue("unitKind", kind).withValue("unitName", unit).withValue("tableName", table).withValue("fingerprint", fingerprint).withValue("sqlText", sql)
.withValue("maxRepeats", max).withValue("unitsAffected", units).withValue("totalRepeats", max * units));
}
/*******************************************************************************
** Reload lifecycle state after each transaction.
*******************************************************************************/
@@ -0,0 +1,88 @@
/*
* QQQ - Low-code Application Framework for Engineers.
* Copyright (C) 2021-2026. Kingsrook, LLC
* 651 N Broad St Ste 205 # 6917 | Middletown DE 19709 | United States
* contact@kingsrook.com
* https://github.com/Kingsrook/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kingsrook.qbits.dbperformance.analyze;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/*******************************************************************************
** Human-readable numbers: grouping, K/M/B suffixes, one-decimal percentages and
** no scientific notation.
*******************************************************************************/
class NumberTextTest
{
/*******************************************************************************
** Small values group, large ones take a suffix; the prod value that read as
** 1.77403392E7 now reads 17.7M.
*******************************************************************************/
@Test
void numbers()
{
assertThat(NumberText.number(0)).isEqualTo("0");
assertThat(NumberText.number(2.25)).isEqualTo("2.3");
assertThat(NumberText.number(999)).isEqualTo("999");
assertThat(NumberText.number(12_345)).isEqualTo("12,345");
assertThat(NumberText.number(99_999.9)).isEqualTo("99,999.9");
assertThat(NumberText.number(100_000)).isEqualTo("100K");
assertThat(NumberText.number(123_456)).isEqualTo("123.5K");
assertThat(NumberText.number(999_999)).isEqualTo("1M");
assertThat(NumberText.number(1.77403392E7)).isEqualTo("17.7M");
assertThat(NumberText.number(2_500_000_000L)).isEqualTo("2.5B");
assertThat(NumberText.number(-1.5E6)).isEqualTo("-1.5M");
assertThat(NumberText.number(-0.04)).isEqualTo("0");
assertThat(NumberText.number(Double.NaN)).isEqualTo("n/a");
assertThat(NumberText.number(Double.POSITIVE_INFINITY)).isEqualTo("n/a");
}
/*******************************************************************************
** Percentages always carry exactly one decimal.
*******************************************************************************/
@Test
void percentsAndSizes()
{
assertThat(NumberText.percent(100)).isEqualTo("100.0%");
assertThat(NumberText.percent(30.25)).isEqualTo("30.3%");
assertThat(NumberText.percent(0.04)).isEqualTo("0.0%");
assertThat(NumberText.percent(Double.NaN)).isEqualTo("n/a");
assertThat(NumberText.megabytes(2)).isEqualTo("2.0 MB");
assertThat(NumberText.megabytes(12_345.678)).isEqualTo("12,345.7 MB");
assertThat(NumberText.megabytes(Double.NaN)).isEqualTo("n/a");
}
/*******************************************************************************
** Evidence cells: any number is humanized, text passes through.
*******************************************************************************/
@Test
void evidenceCells()
{
assertThat(NumberText.text(1.77403392E7)).isEqualTo("17.7M");
assertThat(NumberText.text(1234567L)).isEqualTo("1.2M");
assertThat(NumberText.text(42)).isEqualTo("42");
assertThat(NumberText.text(new BigDecimal("1234.56"))).isEqualTo("1,234.6");
assertThat(NumberText.text("status, customer_id")).isEqualTo("status, customer_id");
assertThat(NumberText.text(null)).isEqualTo("null");
}
}
@@ -48,6 +48,7 @@ import com.kingsrook.qqq.backend.core.instrumentation.StatementOperation;
import com.kingsrook.qqq.backend.core.instrumentation.UnitOfWork;
import com.kingsrook.qqq.backend.core.instrumentation.UnitOfWorkKind;
import com.kingsrook.qqq.backend.core.instrumentation.UnitsOfWork;
import com.kingsrook.qqq.backend.core.model.actions.processes.RunProcessInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
@@ -135,7 +136,7 @@ class AttributionTest
flusher.flushNow();
List<QRecord> rows = rows("db_perf_attribution");
assertThat(rows).hasSize(3);
assertThat(rows).extracting(row -> row.getValueString("unitName")).containsExactlyInAnyOrder("job", "GET /things/{id}", "(none)");
assertThat(rows).extracting(row -> row.getValueString("unitName")).containsExactlyInAnyOrder("job", "GET /things/{id}", mainThreadUnit());
QRecord job = named(rows, "job");
assertThat(job.getValueString("unitKind")).isEqualTo("SCHEDULED_JOB");
assertThat(job.getValueLong("units")).isEqualTo(1);
@@ -144,7 +145,7 @@ class AttributionTest
assertThat(job.getValueString("operation")).isEqualTo("QUERY");
assertThat(job.getValueString("tableName")).isEqualTo("business");
assertThat(job.getValueString("fingerprint")).isEqualTo(SqlNormalizer.fingerprint(job.getValueString("sqlText")));
assertThat(named(rows, "(none)").getValueString("unitKind")).isEqualTo("OTHER");
assertThat(named(rows, mainThreadUnit()).getValueString("unitKind")).isEqualTo("OTHER");
}
@@ -283,7 +284,7 @@ class AttributionTest
listener.onStatement(new StatementExecution(runtime.getConfig().getBackendName(), null, null, null, 10, null, true, null, "process"));
flusher.flushNow();
List<QRecord> rows = rows("db_perf_attribution");
QRecord row = named(rows, "(none)");
QRecord row = named(rows, mainThreadUnit());
assertThat(row.getValueBigDecimal("totalMs")).isEqualByComparingTo("7");
assertThat(row.getValueBigDecimal("maxMs")).isEqualByComparingTo("5");
assertThat(row.getValueLong("errors")).isEqualTo(1);
@@ -296,6 +297,56 @@ class AttributionTest
}
/*******************************************************************************
** Statements without a unit of work are named, in order, by their reported
** process, the outermost process on the action stack, then the thread-name
** pattern, so that background work is not one anonymous (none) bucket.
*******************************************************************************/
@Test
void fallbackNamesStatementsWithoutAUnitOfWork() throws Exception
{
synthetic("select ?", 1, true, null);
listener.onStatement(new StatementExecution(runtime.getConfig().getBackendName(), "business", StatementOperation.QUERY, "select ?", 1, 1, true, null, "reportedProcess"));
QContext.pushAction(new RunProcessInput().withProcessName("stackProcess"));
QContext.pushAction(new QueryInput("business"));
try
{
synthetic("select ?", 1, true, null);
}
finally
{
QContext.popAction();
QContext.popAction();
}
for(String threadName : List.of("alerts-worker-3", "alerts-worker-17"))
{
Thread thread = new Thread(() -> synthetic("select ?", 1, true, null), threadName);
thread.start();
thread.join();
}
flusher.flushNow();
List<QRecord> rows = rows("db_perf_attribution");
assertThat(rows).extracting(row -> row.getValueString("unitName"))
.containsExactlyInAnyOrder(mainThreadUnit(), "reportedProcess", "process:stackProcess", "thread:alerts-worker-#");
assertThat(named(rows, "thread:alerts-worker-#").getValueLong("statements")).isEqualTo(2);
assertThat(rows).allSatisfy(row -> assertThat(row.getValueString("unitKind")).isEqualTo("OTHER"));
}
/*******************************************************************************
** Thread names collapse numbers, stay bounded and never come out empty.
*******************************************************************************/
@Test
void threadPatterns()
{
assertThat(AttributionListener.threadPattern("pool-3-thread-7")).isEqualTo("thread:pool-#-thread-#");
assertThat(AttributionListener.threadPattern(" worker-2024 ")).isEqualTo("thread:worker-#");
assertThat(AttributionListener.threadPattern("x".repeat(500))).hasSize("thread:".length() + 100);
assertThat(AttributionListener.threadPattern(null)).isEqualTo("(none)");
assertThat(AttributionListener.threadPattern(" ")).isEqualTo("(none)");
}
/*******************************************************************************
** An abandoned unit is merged when another unit arrives on that worker.
*******************************************************************************/
@@ -588,6 +639,15 @@ class AttributionTest
/*******************************************************************************
** The fallback unit name of statements issued from this (test) thread.
*******************************************************************************/
private static String mainThreadUnit()
{
return (AttributionListener.threadPattern(Thread.currentThread().getName()));
}
/*******************************************************************************
** Deliver a statement with exact counter values.
*******************************************************************************/