lib/Database/BI/Insights.pm

Structural Coverage (Approximate)

TER1 (Statement): 100.00%
TER2 (Branch): 95.45%
TER3 (LCSAJ): 100.0% (16/16)
Approximate LCSAJ segments: 155

LCSAJ Legend

● Covered — this LCSAJ path was executed during testing.

● Not covered — this LCSAJ path was never executed. These are the paths to focus on.

Multiple dots on a line indicate that multiple control-flow paths begin at that line. Hovering over any dot shows:

        start → end → jump
        

Uncovered paths show [NOT COVERED] in the tooltip.

Mutant Testing Legend

Survived (tests missed this) Killed (tests detected this) No mutation
    1: package Database::BI::Insights;
    2: 
    3: use strict;
    4: use warnings;
    5: 
    6: our $VERSION = '0.025.0';
    7: 
    8: use Database::BI::Util  qw(urlencode);
    9: use List::Util          qw(sum min max);
   10: use Scalar::Util        qw(looks_like_number);
   11: use Readonly;
   12: 
   13: # ---------------------------------------------------------------------------
   14: # Constants
   15: # ---------------------------------------------------------------------------
   16: 
   17: # IQR fence multiplier (Tukey, 1977).
   18: Readonly my $IQR_FENCE => 1.5;
   19: 
   20: # Minimum distinct periods required for period-over-period and seasonality.
   21: Readonly my $MIN_PERIODS_POP   => 2;
   22: Readonly my $MIN_PERIODS_SEASON => 8;
   23: 
   24: # Minimum rows in a group to attempt outlier detection.
   25: Readonly my $MIN_ROWS_OUTLIER => 4;
   26: 
   27: # Autocorrelation threshold above which we call a pattern "seasonal".
   28: Readonly my $SEASON_R_THRESHOLD => 0.6;
   29: 
   30: # Maximum outliers reported per column (keeps the panel readable).
   31: Readonly my $MAX_OUTLIERS_PER_COL => 5;
   32: 
   33: # Maximum top-mover rows reported.
   34: Readonly my $MAX_TOP_MOVERS => 5;
   35: 
   36: # ---------------------------------------------------------------------------
   37: # Public API
   38: # ---------------------------------------------------------------------------
   39: 
   40: # compute( records => \@rows, columns => \@cols, spec_key => $l, base_url => $url )
   41: #   -> \@insights
   42: #
   43: # Each insight hashref has:
   44: #   kind      -- 'outlier' | 'top_mover' | 'period_delta' | 'seasonality'
   45: #   headline  -- one short sentence
   46: #   detail    -- one sentence giving the numbers
   47: #   view_url  -- absolute-path URL (without host) linking to the view that shows it
   48: #                (always present; the spec says "an insight you cannot click through is a bug")
   49: #   method    -- key into %METHOD_NOTES documenting the algorithm used
   50: #
   51: # Arguments:
   52: #   records  -- arrayref of row hashrefs (pre-filtered, post-calc)
   53: #   columns  -- arrayref of column names in order
   54: #   spec_key -- the l= value (e.g. "table:sales" or "path:/data/x.csv")
   55: #   base_url -- base request URL to build view_url from (e.g. "/stats?l=table:sales")
   56: #
   57: # NOTE: This sub is pure arithmetic -- no LLM, no external calls.
   58: sub compute {
●59 → 71 → 84   59: 	my (%args) = @_;
   60: 	my $records  = $args{records}  // [];
   61: 	my $columns  = $args{columns}  // [];
   62: 	my $spec_key = $args{spec_key} // '';
   63: 	my $base_url = $args{base_url} // "/insights?l=$spec_key";
   64: 
   65: 	return [] unless @$records && @$columns;
   66: 
   67: 	my @insights;
   68: 
   69: 	# Identify date columns (ISO-8601 YYYY-MM-DD) and numeric columns.
   70: 	my (@date_cols, @numeric_cols);
   71: 	for my $col (@$columns) {
   72: 		my @vals = grep { defined $_ && length $_ } map { $_->{$col} } @$records;
   73: 		next unless @vals;

Mutants (Total: 1, Killed: 1, Survived: 0)

74: if (_is_date_col(\@vals)) { 75: push @date_cols, $col; 76: } elsif (_is_numeric_col(\@vals)) { 77: push @numeric_cols, $col; 78: } 79: } 80: 81: # Outlier detection: for each numeric column scan all distinct category 82: # groups formed by each non-numeric, non-date column. When the dataset 83: # has no categorical column, treat all rows as one group. ●84 → 89 → 96 84: my @cat_cols = grep { 85: my $c = $_; 86: !grep { $_ eq $c } (@date_cols, @numeric_cols) 87: } @$columns; 88: 89: for my $num_col (@numeric_cols) { 90: my @found = _find_outliers($records, $num_col, \@cat_cols, $spec_key, $base_url); 91: push @insights, @found; 92: } 93: 94: # Period-over-period and top movers: need a date column + at least one 95: # numeric column.

Mutants (Total: 1, Killed: 1, Survived: 0)

●96 → 96 → 108 96: if (@date_cols && @numeric_cols) { 97: my $date_col = $date_cols[0]; # use the first date column found 98: for my $num_col (@numeric_cols) { 99: push @insights, 100: _period_over_period($records, $date_col, $num_col, $spec_key, $base_url); 101: push @insights, 102: _top_movers($records, $date_col, $num_col, \@cat_cols, $spec_key, $base_url); 103: push @insights, 104: _seasonality($records, $date_col, $num_col, $spec_key, $base_url); 105: } 106: } 107:

Mutants (Total: 2, Killed: 2, Survived: 0)

108: return \@insights; 109: } 110: 111: # method_note($method_key) -> $string 112: # 113: # Returns a one-sentence human-readable description of the algorithm behind 114: # a given insight method key. Used by the template's tooltip/footnote. 115: sub method_note { 116: my $key = shift; 117: my %notes = ( 118: iqr_fence => 'Outlier: value beyond 1.5 x IQR from Q1 or Q3 (Tukey fence).', 119: pop_delta => 'Period-over-period: sum for the most-recent period vs. the prior period.', 120: top_mover => 'Top mover: dimension member with the largest period-over-period absolute change.', 121: autocorr => 'Seasonality: lag-1 autocorrelation on period sums; r >= 0.6 flagged.', 122: );

Mutants (Total: 2, Killed: 2, Survived: 0)

123: return $notes{$key} // $key; 124: } 125: 126: # --------------------------------------------------------------------------- 127: # Private helpers 128: # --------------------------------------------------------------------------- 129: 130: # _looks_like_date($v) -> bool 131: # 132: # Returns true when $v matches any common date format. Checked BEFORE numeric 133: # classification so that slash-dates (e.g. 12/22/2025 from US bank exports), 134: # EU slash-dates (22/12/2025), and dash-Mon dates (22-Oct-2026) are never 135: # stripped of their punctuation and misread as large integers like 12222025. 136: sub _looks_like_date { 137: my $v = shift;

Mutants (Total: 2, Killed: 0, Survived: 2)
138: return 0 unless defined $v && length $v;

Mutants (Total: 2, Killed: 2, Survived: 0)

139: return 1 if $v =~ /\A\d{4}-\d{2}-\d{2}\z/; # ISO-8601

Mutants (Total: 2, Killed: 2, Survived: 0)

140: return 1 if $v =~ /\A\d{1,2}\/\d{1,2}\/\d{4}\z/; # M/D/YYYY or D/M/YYYY

Mutants (Total: 2, Killed: 0, Survived: 2)
141: return 1 if $v =~ /\A\d{1,2}-[A-Za-z]{3}-\d{4}\z/; # DD-Mon-YYYY

Mutants (Total: 2, Killed: 2, Survived: 0)

142: return 0; 143: } 144: 145: sub _is_date_col { ●146 → 149 → 153 146: my $vals = shift;

Mutants (Total: 3, Killed: 0, Survived: 3)
147: my $n = @$vals > 20 ? 20 : scalar @$vals; 148: my $ok = 0; 149: for my $v (@{$vals}[0 .. $n - 1]) {

Mutants (Total: 2, Killed: 2, Survived: 0)

150: return 0 unless _looks_like_date($v); 151: $ok++; 152: }

Mutants (Total: 2, Killed: 2, Survived: 0)

153: return $ok ? 1 : 0; 154: } 155: 156: sub _is_numeric_col { ●157 → 161 → 167 157: my $vals = shift;

Mutants (Total: 2, Killed: 0, Survived: 2)
158: return 0 unless @$vals; 159: my $ok = 0;
Mutants (Total: 3, Killed: 0, Survived: 3)
160: my $n = @$vals > 20 ? 20 : scalar @$vals; 161: for my $v (@{$vals}[0 .. $n - 1]) {
Mutants (Total: 2, Killed: 0, Survived: 2)
162: return 0 if _looks_like_date($v); # date values are not numeric measures 163: my $num = _to_num($v);

Mutants (Total: 2, Killed: 2, Survived: 0)

164: return 0 unless defined $num; 165: $ok++; 166: }

Mutants (Total: 2, Killed: 2, Survived: 0)

167: return $ok ? 1 : 0; 168: } 169: 170: sub _to_num { 171: return Database::BI::Util::parse_number($_[0]);

Mutants (Total: 2, Killed: 0, Survived: 2)
172: } 173: 174: # _quartiles(\@sorted_nums) -> ($q1, $median, $q3) 175: #

Mutants (Total: 2, Killed: 2, Survived: 0)

176: # Uses the "inclusive" method: for n values, Q1 is the median of the lower

Mutants (Total: 2, Killed: 2, Survived: 0)

177: # half (not including the overall median when n is odd), Q3 the median of the 178: # upper half. This matches R's type=2 and Excel's QUARTILE.INC. 179: sub _quartiles { 180: my $s = shift; # already sorted 181: my $n = scalar @$s; 182: return (undef, undef, undef) unless $n >= 4; 183: 184: my $mid = int($n / 2); 185: my @lo = @{$s}[0 .. $mid - 1]; 186: my @hi = @{$s}[($n % 2 ? $mid + 1 : $mid) .. $n - 1]; 187:

Mutants (Total: 3, Killed: 0, Survived: 3)
188: my $q1 = _median(\@lo); 189: my $q2 = _median($s); 190: my $q3 = _median(\@hi); 191: return ($q1, $q2, $q3); 192: } 193: 194: sub _median { 195: my $s = shift; 196: my $n = scalar @$s; 197: return undef unless $n; 198: my $m = int($n / 2); 199: return $n % 2 ? $s->[$m] : ($s->[$m - 1] + $s->[$m]) / 2; 200: } 201: 202: # _find_outliers($records, $num_col, \@cat_cols, $spec_key, $base_url) -> @insights
Mutants (Total: 2, Killed: 0, Survived: 2)
203: # 204: # For each categorical group (or all rows when @cat_cols is empty), apply the

Mutants (Total: 2, Killed: 2, Survived: 0)

205: # Tukey IQR fence to the numeric column. Report up to MAX_OUTLIERS_PER_COL 206: # values that fall outside [Q1 - 1.5*IQR, Q3 + 1.5*IQR]. 207: sub _find_outliers { ●208 → 214 → 221 208: my ($records, $num_col, $cat_cols, $spec_key, $base_url) = @_; 209: 210: my @insights; 211: 212: # Group records by category key (empty string when no cat_cols). 213: my (%groups, %group_example); 214: for my $row (@$records) { 215: my $key = join("\x00", map { $row->{$_} // '' } @$cat_cols); 216: my $val = _to_num($row->{$num_col}); 217: push @{ $groups{$key} }, $val if defined $val; 218: $group_example{$key} //= $row; 219: } 220: ●221 → 221 → 325 221: for my $key (sort keys %groups) { 222: my @nums = @{ $groups{$key} }; 223: next if @nums < $MIN_ROWS_OUTLIER; 224: 225: my @sorted = sort { $a <=> $b } @nums; 226: my ($q1, undef, $q3) = _quartiles(\@sorted); 227: next unless defined $q1 && defined $q3; 228:

Mutants (Total: 3, Killed: 3, Survived: 0)

229: my $iqr = $q3 - $q1; 230: my $lo_fence = $q1 - $IQR_FENCE * $iqr; 231: my $hi_fence = $q3 + $IQR_FENCE * $iqr; 232: 233: # Find outlier rows. 234: my @outlier_rows; 235: for my $row (@$records) { 236: my $gkey = join("\x00", map { $row->{$_} // '' } @$cat_cols); 237: next unless $gkey eq $key; 238: my $val = _to_num($row->{$num_col}); 239: next unless defined $val; 240: next unless $val < $lo_fence || $val > $hi_fence; 241: push @outlier_rows, { val => $val, row => $row }; 242: } 243: next unless @outlier_rows; 244: 245: # Sort by distance from nearest fence, descending.

Mutants (Total: 6, Killed: 6, Survived: 0)

246: @outlier_rows = sort { 247: _fence_distance($b->{val}, $lo_fence, $hi_fence) <=> 248: _fence_distance($a->{val}, $lo_fence, $hi_fence) 249: } @outlier_rows; 250: 251: splice @outlier_rows, $MAX_OUTLIERS_PER_COL if @outlier_rows > $MAX_OUTLIERS_PER_COL; 252: 253: # Build one insight per outlier. 254: for my $o (@outlier_rows) { 255: my $val = $o->{val}; 256: my $row = $o->{row};

Mutants (Total: 3, Killed: 0, Survived: 3)
257: 258: # Build a human-readable group label. 259: my $group_label = ''; 260: if (@$cat_cols) { 261: my @parts; 262: for my $c (@$cat_cols) { 263: push @parts, "$c=" . ($row->{$c} // ''); 264: } 265: $group_label = join(', ', @parts);
Mutants (Total: 1, Killed: 0, Survived: 1)
266: } 267: 268: my $dir = $val > $hi_fence ? 'high' : 'low'; 269: my $headline = $group_label 270: ? "Unusual $num_col in $group_label: " . _fmt_num($val) . " is unusually $dir" 271: : "Unusual $num_col value: " . _fmt_num($val) . " is unusually $dir"; 272: 273: my $detail = sprintf(
Mutants (Total: 3, Killed: 0, Survived: 3)
274: "Expected range %s \x{2013} %s (IQR fence on %d values)", 275: _fmt_num($lo_fence), _fmt_num($hi_fence), scalar @nums 276: ); 277: 278: # Build view_url: link to /bar for cat_cols, /stats otherwise. 279: my $view_url; 280: if (@$cat_cols) { 281: my $cat = urlencode($cat_cols->[0]); 282: my $val_enc = urlencode($num_col); 283: $view_url = "/bar?l=${\urlencode($spec_key)}&cat=$cat&val=$val_enc&sort=value"; 284: } else { 285: $view_url = "/stats?l=" . urlencode($spec_key);
Mutants (Total: 1, Killed: 0, Survived: 1)
286: } 287: 288: # Build drill_url: data table filtered to category group so the 289: # outlier row is visible in context of its peers. The hl_col / 290: # hl_op / hl_val params tell dashboard.html.tt to highlight and 291: # scroll to the specific outlier row(s) within those 75+ peers. 292: my $drill_url; 293: if (@$cat_cols) { 294: my $base = _spec_to_data_url($spec_key); 295: if ($base) { 296: my $cat_enc = urlencode($cat_cols->[0]); 297: my $gval = (split /\x00/, $key)[0] // ''; 298: my $gv_enc = urlencode($gval);

Mutants (Total: 1, Killed: 1, Survived: 0)

299: my $sep = ($base =~ /\?/) ? '&' : '?'; 300: $drill_url = $base . $sep . 'f=' . $cat_enc . ':eq:' . $gv_enc;

Mutants (Total: 1, Killed: 1, Survived: 0)

301: # Highlight the outlier row(s): beyond the IQR fence. 302: my $hl_op = ($val > $hi_fence) ? 'gt' : 'lt'; 303: my $hl_fence = ($val > $hi_fence) ? $hi_fence : $lo_fence; 304: $drill_url .= '&hl_col=' . urlencode($num_col) 305: . '&hl_op=' . $hl_op 306: . '&hl_val=' . urlencode(sprintf('%.10g', $hl_fence)); 307: if ($base_url) {

Mutants (Total: 3, Killed: 0, Survived: 3)
308: $drill_url .= '&back2=' . urlencode($base_url)
Mutants (Total: 3, Killed: 0, Survived: 3)
309: . '&back2_label=Back+to+insights'; 310: } 311: } 312: }

Mutants (Total: 1, Killed: 1, Survived: 0)

313: 314: push @insights, { 315: kind => 'outlier', 316: headline => $headline, 317: detail => $detail, 318: view_url => $view_url, 319: ($drill_url ? (drill_url => $drill_url) : ()), 320: method => 'iqr_fence', 321: }; 322: } 323: } 324: 325: return @insights; 326: } 327: 328: sub _fence_distance { 329: my ($val, $lo, $hi) = @_; 330: return $val > $hi ? $val - $hi

Mutants (Total: 2, Killed: 2, Survived: 0)

331: : $val < $lo ? $lo - $val 332: : 0; 333: } 334: 335: # _period_over_period($records, $date_col, $num_col, $spec_key, $base_url) -> @insights

Mutants (Total: 5, Killed: 0, Survived: 5)
336: #
Mutants (Total: 3, Killed: 0, Survived: 3)
337: # Aggregates $num_col by year-month period, then reports the delta between the 338: # most recent two periods. 339: sub _period_over_period { ●340 → 343 → 352 340: my ($records, $date_col, $num_col, $spec_key, $base_url) = @_; 341: 342: my %period_totals; 343: for my $row (@$records) { 344: my $date = $row->{$date_col} // ''; 345: next unless $date =~ /\A(\d{4}-\d{2})/; 346: my $period = $1; 347: my $val = _to_num($row->{$num_col}); 348: next unless defined $val; 349: $period_totals{$period} += $val; 350: } 351: ●352 → 384 → 394 352: my @periods = sort keys %period_totals; 353: return () unless @periods >= $MIN_PERIODS_POP; 354: 355: my $cur = $periods[-1]; 356: my $prev = $periods[-2]; 357: my $cur_val = $period_totals{$cur}; 358: my $prev_val = $period_totals{$prev};
Mutants (Total: 3, Killed: 0, Survived: 3)
359: 360: my $delta = $cur_val - $prev_val; 361: my $pct = $prev_val != 0 ? $delta / abs($prev_val) * 100 : undef; 362: 363: my $dir = $delta >= 0 ? 'up' : 'down'; 364: my $sign = $delta >= 0 ? '+' : ''; 365: 366: my $headline = sprintf('%s is %s %s vs prior period (%s)',
Mutants (Total: 1, Killed: 0, Survived: 1)
367: $num_col, $dir, _fmt_num(abs($delta)), $prev); 368:
Mutants (Total: 3, Killed: 0, Survived: 3)
369: my $detail = defined $pct
Mutants (Total: 3, Killed: 0, Survived: 3)
370: ? sprintf('%s: %s %s: %s (%s%s%%)', 371: $prev, _fmt_num($prev_val), $cur, _fmt_num($cur_val), 372: $sign, sprintf('%.1f', $pct)) 373: : sprintf('%s: %s %s: %s', 374: $prev, _fmt_num($prev_val), $cur, _fmt_num($cur_val)); 375: 376: my $enc_spec = urlencode($spec_key); 377: my $enc_date = urlencode($date_col); 378: my $enc_num = urlencode($num_col); 379: my $view_url = "/graph?l=$enc_spec&x=$enc_date&y=$enc_num"; 380: 381: # Drill into the data table filtered to the current period. 382: my $drill_url; 383: my $base = _spec_to_data_url($spec_key); 384: if ($base) { 385: my $sep = ($base =~ /\?/) ? '&' : '?'; 386: $drill_url = $base . $sep 387: . 'f=' . $enc_date . ':starts:' . urlencode($cur); 388: if ($base_url) { 389: $drill_url .= '&back2=' . urlencode($base_url)

Mutants (Total: 1, Killed: 1, Survived: 0)

390: . '&back2_label=Back+to+insights'; 391: } 392: } 393:

Mutants (Total: 1, Killed: 1, Survived: 0)

394: return ({ 395: kind => 'period_delta', 396: headline => $headline, 397: detail => $detail, 398: view_url => $view_url, 399: ($drill_url ? (drill_url => $drill_url) : ()), 400: method => 'pop_delta', 401: }); 402: } 403: 404: # _top_movers($records, $date_col, $num_col, \@cat_cols, $spec_key, $base_url) -> @insights 405: # 406: # For each categorical group, compute period-over-period delta between the two 407: # most recent periods, and report the top MAX_TOP_MOVERS movers. 408: sub _top_movers { ●409 → 415 → 427 409: my ($records, $date_col, $num_col, $cat_cols, $spec_key, $base_url) = @_; 410: return () unless @$cat_cols; 411: 412: # Collect totals keyed by (period, group_key). 413: my (%totals, %group_labels); 414: my %all_periods; 415: for my $row (@$records) { 416: my $date = $row->{$date_col} // ''; 417: next unless $date =~ /\A(\d{4}-\d{2})/; 418: my $period = $1; 419: $all_periods{$period}++; 420: my $gkey = join("\x00", map { $row->{$_} // '' } @$cat_cols); 421: my $val = _to_num($row->{$num_col}); 422: next unless defined $val; 423: $totals{$period}{$gkey} += $val; 424: $group_labels{$gkey} //= join(', ', map { $row->{$_} // '' } @$cat_cols); 425: } 426: ●427 → 434 → 442 427: my @periods = sort keys %all_periods; 428: return () unless @periods >= $MIN_PERIODS_POP; 429: 430: my $cur = $periods[-1]; 431: my $prev = $periods[-2]; 432: 433: my (@movers);

Mutants (Total: 3, Killed: 0, Survived: 3)
434: for my $gkey (keys %group_labels) { 435: my $cur_val = $totals{$cur}{$gkey} // 0; 436: my $prev_val = $totals{$prev}{$gkey} // 0; 437: my $delta = $cur_val - $prev_val; 438: push @movers, { gkey => $gkey, label => $group_labels{$gkey}, 439: delta => $delta, cur => $cur_val, prev => $prev_val }; 440: } 441: ●442 → 455 → 492 442: return () unless @movers; 443: 444: # Sort by absolute delta descending. 445: @movers = sort { abs($b->{delta}) <=> abs($a->{delta}) } @movers; 446: splice @movers, $MAX_TOP_MOVERS if @movers > $MAX_TOP_MOVERS; 447: 448: my $cat_col = $cat_cols->[0]; 449: my $enc_spec = urlencode($spec_key); 450: my $enc_date = urlencode($date_col); 451: my $enc_num = urlencode($num_col);
Mutants (Total: 3, Killed: 0, Survived: 3)
452: my $enc_cat = urlencode($cat_col); 453: 454: my @insights; 455: for my $m (@movers) { 456: my $dir = $m->{delta} >= 0 ? 'up' : 'down'; 457: my $sign = $m->{delta} >= 0 ? '+' : ''; 458: my $headline = sprintf('%s %s %s by %s from %s to %s', 459: $m->{label}, $num_col, $dir, _fmt_num(abs($m->{delta})), $prev, $cur); 460: my $detail = sprintf('%s: %s %s: %s', 461: $prev, _fmt_num($m->{prev}), $cur, _fmt_num($m->{cur}));
Mutants (Total: 3, Killed: 0, Survived: 3)
462:
Mutants (Total: 3, Killed: 0, Survived: 3)
463: # Encode the group value for the filter. 464: my $gval_enc = urlencode((split /\x00/, $m->{gkey})[0] // ''); 465: my $view_url = "/graph?l=$enc_spec&x=$enc_date&y=$enc_num" 466: . "&f=$enc_cat:eq:$gval_enc"; 467: 468: # Drill into data table filtered to category + current period. 469: my $drill_url; 470: my $base = _spec_to_data_url($spec_key); 471: if ($base) { 472: my $sep = ($base =~ /\?/) ? '&' : '?'; 473: $drill_url = $base . $sep 474: . 'f=' . $enc_date . ':starts:' . urlencode($cur) 475: . '&f=' . $enc_cat . ':eq:' . $gval_enc; 476: if ($base_url) {

Mutants (Total: 1, Killed: 1, Survived: 0)

477: $drill_url .= '&back2=' . urlencode($base_url) 478: . '&back2_label=Back+to+insights'; 479: } 480: } 481:

Mutants (Total: 1, Killed: 1, Survived: 0)

482: push @insights, { 483: kind => 'top_mover', 484: headline => $headline, 485: detail => $detail, 486: view_url => $view_url, 487: ($drill_url ? (drill_url => $drill_url) : ()), 488: method => 'top_mover', 489: }; 490: } 491: 492: return @insights; 493: } 494: 495: # _seasonality($records, $date_col, $num_col, $spec_key, $base_url) -> @insights 496: # 497: # Computes period sums (year-month), then calculates the lag-1 autocorrelation

Mutants (Total: 2, Killed: 2, Survived: 0)

498: # coefficient on the sequence of sums. A coefficient >= SEASON_R_THRESHOLD 499: # is flagged as seasonal. 500: # 501: # Autocorrelation formula: 502: # r(1) = sum_{t=1}^{n-1}[(x_t - xbar)(x_{t+1} - xbar)] / sum_{t=0}^{n-1}[(x_t - xbar)^2] 503: # 504: # This is the Pearson correlation between the series and itself shifted by one 505: # period. For a regular, evenly-spaced time series this is the lag-1 Moran 506: # coefficient. With uneven spacing it is an approximation, but adequate for 507: # detecting year-over-year periodicity in monthly business data. 508: sub _seasonality { ●509 → 512 → 521 509: my ($records, $date_col, $num_col, $spec_key, $base_url) = @_; 510: 511: my %period_totals; 512: for my $row (@$records) { 513: my $date = $row->{$date_col} // ''; 514: next unless $date =~ /\A(\d{4}-\d{2})/; 515: my $period = $1; 516: my $val = _to_num($row->{$num_col}); 517: next unless defined $val; 518: $period_totals{$period} += $val; 519: } 520: ●521 → 530 → 536 521: my @periods = sort keys %period_totals; 522: return () unless @periods >= $MIN_PERIODS_SEASON; 523: 524: my @y = map { $period_totals{$_} } @periods; 525: my $n = scalar @y; 526: my $ybar = (sum(@y)) / $n; 527:

Mutants (Total: 3, Killed: 0, Survived: 3)
528: my $num = 0; 529: my $denom = 0; 530: for my $i (0 .. $n - 1) { 531: my $dev = $y[$i] - $ybar; 532: $denom += $dev * $dev; 533: $num += $dev * ($y[$i + 1] - $ybar) if $i < $n - 1; 534: } 535: 536: return () unless $denom > 0; 537: my $r = $num / $denom; 538:
Mutants (Total: 3, Killed: 0, Survived: 3)
539: return () unless $r >= $SEASON_R_THRESHOLD; 540: 541: my $headline = sprintf('%s shows a repeating period-over-period pattern (r=%.2f)',
Mutants (Total: 3, Killed: 0, Survived: 3)
542: $num_col, $r); 543: my $detail = sprintf( 544: 'Lag-1 autocorrelation %.2f across %d periods (%s to %s)',
Mutants (Total: 3, Killed: 0, Survived: 3)
545: $r, $n, $periods[0], $periods[-1] 546: ); 547: 548: my $enc_spec = urlencode($spec_key); 549: my $enc_date = urlencode($date_col); 550: my $enc_num = urlencode($num_col); 551: my $view_url = "/graph?l=$enc_spec&x=$enc_date&y=$enc_num"; 552: 553: return ({ 554: kind => 'seasonality', 555: headline => $headline, 556: detail => $detail, 557: view_url => $view_url, 558: method => 'autocorr', 559: }); 560: } 561: 562: # _fmt_num($n) -> $string 563: # Format a number to 4 significant figures, stripping trailing zeros. 564: sub _fmt_num { 565: my $n = shift; 566: return 'N/A' unless defined $n; 567: return sprintf('%s', $n) if $n == int($n) && abs($n) < 1e12; 568: return sprintf('%s', 0 + sprintf('%.4g', $n)); 569: } 570: 571:
Mutants (Total: 2, Killed: 0, Survived: 2)
572: # _spec_to_data_url($spec_key) -> $url_or_undef
Mutants (Total: 6, Killed: 2, Survived: 4)
573: #
Mutants (Total: 2, Killed: 0, Survived: 2)
574: # Converts a l= spec key to the root-relative URL of the data table page. 575: # table:sales -> /view/sales 576: # path:/abs/path/f.csv -> /open?path=%2Fabs%2Fpath%2Ff.csv 577: # Returns undef for unrecognised spec forms. 578: sub _spec_to_data_url { ●579 → 580 → 583 579: my $spec = shift // ''; 580: if ($spec =~ /\Atable:(.+)\z/) { 581: return '/view/' . urlencode($1);

Mutants (Total: 2, Killed: 2, Survived: 0)

582: } ●583 → 583 → 588 583: if ($spec =~ /\Apath:(.+)\z/) { 584: require Database::BI::Model::DataSource; 585: my ($file, $internal) = Database::BI::Model::DataSource::split_path($1); 586: return '/open?path=' . urlencode($file) . (defined $internal ? '&it=' . urlencode($internal) : ''); 587: } 588: return undef; 589: } 590: 591: 1; 592:

Mutants (Total: 1, Killed: 1, Survived: 0)

593: __END__

Mutants (Total: 2, Killed: 2, Survived: 0)

594: 595: =head1 NAME

Mutants (Total: 1, Killed: 1, Survived: 0)

596:

Mutants (Total: 2, Killed: 2, Survived: 0)

597: Database::BI::Insights - Automatic statistical insights for Database::BI (Phase 5.2) 598:

Mutants (Total: 2, Killed: 0, Survived: 2)
599: =head1 SYNOPSIS 600: 601: use Database::BI::Insights; 602: 603: my $insights = Database::BI::Insights::compute( 604: records => \@rows, 605: columns => \@cols, 606: spec_key => 'table:sales', 607: base_url => '/insights?l=table:sales', 608: ); 609: 610: =head1 DESCRIPTION 611: 612: Pure-arithmetic insight detection. No LLM, no external service calls. 613: Detects four classes of insight: 614: 615: =over 616: 617: =item outlier 618: 619: A value beyond the Tukey IQR fence (Q1 - 1.5*IQR or Q3 + 1.5*IQR). 620: 621: =item period_delta 622: 623: Overall period-over-period delta between the most recent two month-periods 624: visible in a date column. 625: 626: =item top_mover 627: 628: The dimension member with the largest period-over-period absolute change. 629: Requires at least one categorical column and one date column. 630: 631: =item seasonality 632: 633: Detected via lag-1 autocorrelation on monthly totals. A coefficient >= 0.6 634: is flagged. Requires at least 8 distinct month-periods. 635: 636: =back 637: 638: Every insight includes a C<view_url> that links to the chart or stats view 639: showing the underlying data. An insight without a clickable view_url is a bug. 640: 641: =head1 FUNCTIONS 642: 643: =head2 compute(%args) 644: 645: my $insights = Database::BI::Insights::compute( 646: records => \@rows, # arrayref of row hashrefs 647: columns => \@cols, # arrayref of column names 648: spec_key => $l, # l= spec string 649: base_url => $url, # request URL, used only as a fallback 650: ); 651: 652: Returns an arrayref of insight hashrefs. Each hashref has: 653: 654: kind -- 'outlier' | 'top_mover' | 'period_delta' | 'seasonality' 655: headline -- one short sentence 656: detail -- numbers that substantiate the headline 657: view_url -- URL to the view showing the data 658: method -- key for method_note() 659: 660: =head3 API SPECIFICATION 661: 662: =head4 INPUT 663: 664: { 665: records => 'arrayref', # row hashrefs, already filtered and with calculated fields 666: columns => 'arrayref', # column names, in order 667: spec_key => 'string', # optional; the l= spec (default '') 668: base_url => 'string', # optional; default "/insights?l=<spec_key>" 669: } 670: 671: =head4 OUTPUT 672: 673: [ { kind => 'string', headline => 'string', detail => 'string', 674: view_url => 'string', method => 'string' }, ... ] 675: 676: No rows or no columns returns C<[]>. Outliers need a numeric column. 677: Period-over-period, top movers and seasonality also need an ISO 678: C<YYYY-MM-DD> date column; only the first one found is used. Every insight 679: has a C<view_url>. The function is pure arithmetic: it makes no network 680: call and does not croak. 681: 682: =head2 method_note($key) 683: 684: Returns a one-sentence description of the algorithm behind C<$key>. 685: 686: =head3 API SPECIFICATION 687: 688: =head4 INPUT 689: 690: $key # 'iqr_fence' | 'pop_delta' | 'top_mover' | 'autocorr' 691: 692: =head4 OUTPUT 693: 694: 'string' # the note; an unknown key is returned unchanged 695: 696: =head1 ALGORITHM NOTES 697: 698: =head3 Outliers 699: 700: Tukey IQR fence: Q1 - 1.5*IQR and Q3 + 1.5*IQR. Requires at least 4 values 701: per group. Results are sorted by distance from the nearest fence; up to 5 702: outliers are reported per column. 703: 704: =head3 Period-over-period 705: 706: Year-month (YYYY-MM) buckets from ISO-8601 date columns. Requires at least 707: 2 distinct periods. 708: 709: =head3 Seasonality 710: 711: Lag-1 autocorrelation r(1) on the sequence of period sums. 712: Formula: r(1) = cov(y[t], y[t+1]) / var(y[t]). 713: Threshold: r >= 0.6. Requires at least 8 distinct month-periods. 714: 715: =head1 AUTHOR 716: 717: Nigel Horne C<< <njh@nigelhorne.com> >> 718: 719: =head1 LICENCE AND COPYRIGHT 720: 721: Copyright 2026 Nigel Horne. 722: 723: Usage is subject to the GPL2 licence terms. 724: 725: =cut