Commit graph

4,323 commits

Author SHA1 Message Date
Yussif Mohammed
9af14fa681 feat: Add log pattern monitoring and detection system
- Add LogPatterns module for pattern tracking and storage
- Add log patterns table and triggers for volume spike detection
- Add log pattern baseline calculation and spike detection jobs
- Restore log pattern issue creation functions in Issues module
- Update BackgroundJobs with log pattern handlers
- Update Drain module for pattern extraction improvements

Migration: 0027

Depends on: errors-feature branch

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-20 07:56:29 +00:00
Yussif Mohammed
86b5773643 feat: Add error monitoring and detection system
- Add Errors module with error fingerprinting and tracking
- Add error events table and triggers for spike detection
- Add error-related issue types and creation functions
- Add error baseline calculation and spike detection jobs
- Update Issues module with error escalation and regression tracking
- Add error notification support in Mail module

Migrations: 0026, 0028, 0030, 0032

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-20 07:53:26 +00:00
Anthony Alaribe
a7de262668
Log explorer improvements: early fetch and virtual parent placeholders (#284)
* Add virtual parent placeholders for orphaned spans in tree view

Remove automatic child span fetching and instead create virtual parent
nodes when child spans are loaded before their parents. This shows a
'Parent span pending' indicator with a dashed border in tree view.

* Replace browser preload with early JS fetch for log explorer

Browser preload used Accept: */* which returned HTML-wrapped JSON.
Early fetch uses Accept: application/json and stores promise on window
for the web component to await, eliminating duplicate request.

* Refactor: simplify code in log explorer components

- Use pattern match in toHtml for LogsGetJson to avoid repeating parameters
- Simplify worker timeout callback using && short-circuit
- Add tooltip with full parent ID on virtual parent spans
- Use nullish coalescing for cleaner startNs fallback
- Simplify orphan span grouping with spread operator

* Fix Monaco editor test mocks for jsdom environment

Add missing document.queryCommandSupported and document.execCommand mocks
for Monaco clipboard support, and add addEventListener/removeEventListener
to Worker mock.
2026-01-17 03:18:55 +01:00
Anthony Alaribe
c5c7fe087d Fix YAML editor rendering and add syntax highlighting
- Add w-full class to yaml-editor element to fix width rendering
- Register YAML language in Monaco using official language definition
- Simplify yaml-editor.ts to use global Monaco instance
2026-01-16 12:37:09 -08:00
Anthony Alaribe
eb1a04e054 Fix ManageMembersSpec test pollution
Clean up existing test members at start of test suite to avoid
interference from other tests using the same project ID.
2026-01-16 10:43:48 -08:00
Anthony Alaribe
eab26a901e Add MultilineStrings extension to doctests and hlint 2026-01-16 09:34:57 -08:00
Anthony Alaribe
cfb79e2163 Update test for division-by-zero safe SQL output
Division now uses COALESCE/NULLIF wrapper for safety.
2026-01-16 09:33:14 -08:00
Anthony Alaribe
06a994e2f0 Update Node.js to 22 for Vite 7.x compatibility
Vite 7.3.1 requires Node.js 20.19+ or 22.12+.
2026-01-16 07:53:32 -08:00
Anthony Alaribe
9fe8441c97 Update Tagify dropdown positioning config
- Add position and place settings for dropdown placement
- Comment out appendTarget function
2026-01-16 07:42:53 -08:00
Anthony Alaribe
9334e55a53 Fix overlapping IsLabel instances in GitSyncSpec
Use explicit field @"name" syntax instead of #name to avoid
conflicts between Data.Generics.Labels and Data.ProtoLens.Labels.
2026-01-16 07:34:41 -08:00
Anthony Alaribe
7f561ecc22 Fix test patterns for updated ManageMembers tuple type
- Updated patterns to match new 3-tuple (ProjectId, Vector, Text)
- Fixed ambiguous record update warnings in GitSyncSpec using lens operators
2026-01-15 16:12:45 -08:00
Anthony Alaribe
31cec273be Fix name shadowing for children variable in Widget.hs
Renamed local variable to childWidgets to avoid shadowing
the children function imported from Control.Lens.
2026-01-15 13:32:09 -08:00
Anthony Alaribe
845f6cee89
Dashboard revamp: Golden Signals, enhanced observability tabs, and infrastructure monitoring (#283)
* Revamp overview dashboard with Golden Signals, enhanced tabs, and Infra monitoring

- Add Golden Signals metrics (Traffic, P95 Latency, Error Rate, Apdex) as primary overview
- Add secondary System Overview row with service/endpoint counts
- Enhance Services table with Apdex score and improved error rate calculation
- Revamp Logs tab: timeseries for errors/warnings, error patterns table, service treemap
- Revamp Databases tab: query optimization targets, latency percentiles, operation breakdown
- Add new Infra tab: CPU/memory utilization, container metrics, Kafka/Redis monitoring
- Add WTServiceMap and WTHeatmap widget types for future visualizations
- Track dashboard YAML files as TH dependencies for automatic recompilation

* Improve group widget layout and collapse behavior

- Fix group header to use auto height instead of flex ratio
- Add CSS for collapsed state (header fills space, chevron rotates)
- Balance GridStack margins (1rem top/bottom) for better centering
- Remove h-full from grid-stack-item-content for proper margin support
- Remove paddingBtm from widgets (GridStack margins handle spacing)
- Reduce dashboard page top padding

* Auto-format code with fourmolu

* Add client-side variable interpolation for widget titles

- Add data-var-template attribute to title/subtitle elements containing {{var-*}}
- Add JS function to interpolate {{var-*}} placeholders from URL params
- Run interpolation on page load and when variables change (update-query event)
- Support both regular widget headers and group widget titles

This enables dynamic title updates without server round-trips when
dashboard variables are changed.

* Add dashboard skeleton loader and simplify widget code

- Add skeleton loader shown while GridStack initializes to prevent
  layout flash where widgets appear squished in top-left corner
- Hide grid until initialized with CSS, fade in skeleton smoothly
- Simplify Widget.hs: isFullWidth, effectiveHeight, attrs using foldMap
- Add widget descriptions to overview dashboard

* Auto-format code with fourmolu

* Refactor dashboard code and fix performance issues

- Use System.FilePath (</>) instead of custom operator
- Simplify groupRequiredHeight fold with foldl'
- Use foldMap pattern for verbose boolean conditions
- Remove orphaned comments
- Fix race condition in collapse handler using widget-scoped flags
- Increase debounce from 200ms to 500ms
- Optimize compactGrid to only batch update when items moved
- Add 5s skeleton timeout fallback
- Replace setTimeout with requestAnimationFrame

* Fix Math.max -Infinity edge case and ensure skeleton cleanup

- Add guard Math.max(1, ...) to prevent -Infinity when array is empty
- Wrap GridStack.init in try-finally to ensure skeleton timeout cleanup

* Upgrade Node.js from 18 to 22 for Vite 7 compatibility

* Update ui-tests to Node.js 22 for consistency

* Fix widget title variable interpolation on initial load

- Make interpolateVarTemplates() globally accessible via window scope
- Call interpolation after GridStack initializes widgets
- Call interpolation after HTMX swaps tab content

Variables in widget titles now render correctly on page load and tab
switches, not just after taglist changes.

* Move interpolateVarTemplates definition outside DOMContentLoaded

* Add SQL syntax highlighting and lazy loading for dashboard widgets

- Add highlight.js with sql-formatter for SQL preview syntax highlighting
- Cache URL params in interpolateVarTemplates for efficiency
- Add HTMX update-query trigger for stat/table widgets to refresh on variable changes
- Refactor stat widget rendering with lazy loading support
- Remove eager flag from overview dashboard widgets

* Auto-format code with fourmolu

* Add .playwright-mcp to gitignore

* Clean up processWidget and add JS optimizations

- Remove unused replacePlaceholders parameters from processWidget
- Add requestAnimationFrame debouncing to interpolateVarTemplates
- Add null check to compactGrid function

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-01-15 21:06:33 +01:00
Anthony Alaribe
4a8346906d Fix singular/plural in timepicker labels (1 Hour not 1 Hours) 2026-01-12 12:02:47 -08:00
dependabot[bot]
73f59c79e3
chore(deps): bump the web-components-dev group (#279)
Bumps the web-components-dev group in /web-components with 2 updates: [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) and [happy-dom](https://github.com/capricorn86/happy-dom).


Updates `@types/node` from 25.0.3 to 25.0.6
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

Updates `happy-dom` from 20.0.11 to 20.1.0
- [Release notes](https://github.com/capricorn86/happy-dom/releases)
- [Commits](https://github.com/capricorn86/happy-dom/compare/v20.0.11...v20.1.0)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-version: 25.0.6
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: web-components-dev
- dependency-name: happy-dom
  dependency-version: 20.1.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: web-components-dev
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-01-12 19:35:38 +01:00
dependabot[bot]
33ae20354b
chore(deps): bump @types/lodash (#280)
Bumps the web-components-prod group in /web-components with 1 update: [@types/lodash](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/lodash).


Updates `@types/lodash` from 4.17.21 to 4.17.23
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/lodash)

---
updated-dependencies:
- dependency-name: "@types/lodash"
  dependency-version: 4.17.23
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: web-components-prod
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-01-12 19:35:06 +01:00
dependabot[bot]
da20feb887
chore(deps): bump vite from 6.4.1 to 7.3.1 in /web-components (#281)
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 6.4.1 to 7.3.1.
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/v7.3.1/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v7.3.1/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-version: 7.3.1
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-01-12 19:34:39 +01:00
Anthony Alaribe
31ce7302de Hide ERROR badge when HTTP status >= 400 already indicates error
The ERROR badge is redundant when the HTTP status code badge (badge-4xx,
badge-5xx) already conveys the failure. This reduces visual noise and
makes actual application exceptions more prominent.

ERROR badges still appear for non-HTTP errors (database, RPC, exceptions).
2026-01-12 09:42:01 -08:00
Anthony Alaribe
d86e30ea84 Fix NULL result from KQL division when count is zero
Wrap division expressions in COALESCE(..., 0) to return 0 instead of
NULL when dividing by zero. Fixes dashboard crash when querying empty
data ranges.
2026-01-12 08:20:03 -08:00
github-actions[bot]
e6ac6a95f3 Auto-format code with fourmolu 2026-01-12 14:58:12 +00:00
Anthony Alaribe
236e7f63d7 Allow team invitations on Free plan with member disabling
- Always process invitations during onboarding regardless of plan
- On Free plan, disable non-owner members instead of blocking/deleting
- Show disabled members in UI with clear badge and warning banner
- Auto-enable all members when upgrading from Free to paid plan
- Fix queries to exclude inactive members from notifications and sessions
- Add deactivateNonOwnerMembers and activateAllMembers helpers
2026-01-12 06:57:47 -08:00
Anthony Alaribe
73f2d2cb18 make loader always available 2026-01-12 06:30:17 -08:00
Anthony Alaribe
3491574054 Add MultilineStrings extension and convert eligible quasiquotes
- Enable GHC 9.12 MultilineStrings extension in package.yaml
- Convert [text|] quasiquotes without interpolation to multiline strings
2026-01-12 06:14:03 -08:00
Anthony Alaribe
4596e05d82 Fix division by zero in KQL arithmetic expressions
Wrap divisor in NULLIF(..., 0) to return NULL instead of crashing
when count() is 0 in expressions like countif(...) / count()
2026-01-12 05:28:28 -08:00
github-actions[bot]
ca5926ad2a Auto-format code with fourmolu 2026-01-12 01:42:08 +00:00
Anthony Alaribe
ed1ab921cf Trigger facet generation for new projects on Log Explorer load
When visiting Log Explorer, if no precomputed facets exist, queue a
background job to generate them immediately instead of waiting for
the hourly job.
2026-01-11 17:41:45 -08:00
Anthony Alaribe
1b24263a01 Fix onboarding event detection not finding events
The query used resource ->> 'telemetry.sdk.language' which looks for a
top-level JSONB key, but the resource column stores nested JSON. This
always returned NULL, causing "No events found yet" even when events
existed.

Simplified to detect any events for the project regardless of SDK
language, since users may select the wrong language or the SDK might
not set this attribute.
2026-01-11 17:22:51 -08:00
Anthony Alaribe
014e0ca2af
Kql update (#276)
* Add KQL scalar functions, SQL preview, and dashboard YAML editing

- Add scalar function support: coalesce, iff, isnull, isnotnull, toint, tofloat, tostring, round
- Fix extend column resolution for GROUP BY clauses
- Separate aggregations from extended columns in query components
- Add SQL debug preview endpoint for widgets
- Add dashboard YAML get/put endpoints for editing
- Show empty constants warning on dashboard pages
- Fix ORDER BY to use GROUP BY column when timestamp not in GROUP BY
- Add yaml-editor web component

* Auto-format code with fourmolu

* Refactor Widget.hs and DashboardUtils.hs for cleaner code

- Hoist V.toList dataRows conversion in renderTableWithDataAndParams
- Simplify KQL remapping using mapMaybe in variablePresetsKQL
- Replace forM_ (zip xs [0..]) with ifor_ for indexed iteration
- Add TODO comments for rawQuery/rawSql Phase 4 removal
- Add doctests for replacePlaceholders, constantToSQLList, constantToKQLList

* Auto-format code with fourmolu

* switch list to table in dashboard

* Add KQL arithmetic expressions and fix parser issues

- Add arithmetic support in summarize: count() / 5.0, count() * 100 / sum(x)
- Fix by-clause parsing to distinguish subjects from scalar functions
- Add ByClauseItem type for proper by-clause item representation
- Fix non-bin summarize queries to use aggregations in SELECT
- Fix extend operator to append columns to defaults (not replace)
- Add extendSelect field to QueryComponents for proper extend semantics
- Forward dashboard constants via data-constants attribute in HTMX
- Use variablePresetsKQL for KQL query expansion in chart endpoint

* Fix KQL arithmetic parsing and refactor SQL generation

- Fix arithmetic operator precedence using makeExprParser
- Fix numeric literal parsing order (try pNumericOnly before aggFunctionParser)
- Add try to arithmetic operators for proper backtracking with 'by' clause
- Add NormalizedQuery type for cleaner SQL generation
- Add transformAST for AST normalization (combineWheres, reorderSections)
- Add unit test for arithmetic division with bin_auto()
- Add doctest for percentiles with by clause regression

* Auto-format code with fourmolu

* Fix hlint warnings in Parser modules

* Performance and safety improvements for KQL parser and dashboards

- Fix KQL remapping bug: filter out -kql suffix entries from output
- Add time interval bounds checking (max 1 year) to prevent DoS
- Use Map.lookup instead of list lookup in resolveExtendedColumn (O(log n))
- Use Set for flattenedOtelAttributes for O(log n) membership checks
- Pre-compute replacement maps once in mkWidgetProcessor for efficiency

* Auto-format code with fourmolu

* Fix regex recompilation and restore rawQuery for Monaco editor

- Pre-compile placeholder regex at module load for performance
- Restore rawQuery field in Widget to preserve original query with placeholders
- Use rawQuery in widget editor for Monaco to display original KQL query

* Improve dashboard widget search and test assertions

- Fix findWidgetInDashboard to recursively search into children
- Process dashboard constants concurrently with pooledForConcurrently
- Simplify variablePresetsKQL using list comprehension
- Update ParserSpec tests to compare full SQL and error messages
- Remove T.isInfixOf partial matches in favor of exact comparisons

* Fix regex type safety and add argument validation to KQL functions

- Use Text instead of String in placeholder regex for type consistency
- Add argument count validation for iff, isnull, isnotnull, isempty, isnotempty
- Fix round() decimal validation logic (was inverted)
- Update doctest expected output for percentiles with by clause

* Optimize Widget rendering and add placeholder DoS protection

- Use Vector operations directly instead of converting to lists
- Add 1MB size limit to placeholder replacement to prevent DoS
- Refactor scalar function SQL generation to use Maps
- Fix empty constants check to include Nothing case

* simplify

* Fix widget query loss and SQL preview not loading

- Fix SQL preview: use 'toggle from:closest details' trigger since toggle
  event fires on parent details element, not child divs
- Fix SQL preview: use raw_query || query (snake_case JSON field names)
- Fix query loss: add mergeWidgetPreservingQuery to preserve original query
  and rawQuery fields when updating widgets instead of replacing entirely

* Fix stat widget color and add variable defaults to constants

- Fix timeseries_stat widgets showing green instead of blue by using
  default palette color for generic column names (value, count, etc.)
- Add addVariableDefaults to ensure dashboard constants can reference
  variables like {{var-resource}} even when not in URL params

* Fix widget duplication and deletion in dashboards

- Fix widget duplication to properly initialize charts and scripts
- Use template element to extract widget HTML and re-query DOM after GridStack adds it
- Process htmx, hyperscript, and scripts on the live DOM element
- Fix widget deletion to use closest grid-stack instead of global instance
- Fix hyperscript syntax for drawer close event

* Auto-format code with fourmolu

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-01-09 23:38:28 +01:00
Anthony Alaribe
58c44925b3 Fix dark mode modal backdrop background color
Override --page-scroll-bg and --root-bg for dark theme to fix
the modal backdrop showing light mode colors in dark mode.
2026-01-08 16:11:09 +01:00
Anthony Alaribe
0af42b65d2 Fix wrong select in spec 2026-01-08 15:27:39 +01:00
Anthony Alaribe
9d4831f05e
Add KQL operators: extend, project, round, tofloat, toint, tostring (#275)
* Add KQL operators: extend, project, round, tofloat, toint, tostring

New KQL features:
- extend operator: adds computed columns to results
- project operator: selects and renames specific columns
- round(value, decimals): round to N decimal places
- tofloat/todouble: convert to float
- toint/tolong: convert to integer
- tostring: convert to text

Updated documentation with examples and usage notes.

* Fix ToQueryText for AggFunction to produce KQL instead of SQL

- ToQueryText AggFunction now produces valid KQL syntax that can be
  parsed back, fixing query round-trip for extend/project commands
- Add ToQueryText instance for SubjectExpr
- Consolidate type casting parsers (pToFloat, pToInt, pToString) with
  pTypeCast helper, reducing duplication
- Consolidate extend/project parsers with pColumnCommand helper

* Reduce parser duplication and add round() validation

- Unify pColumnAssignment and namedAggregation into pNamedExpr helper
- namedAggregation now delegates to pNamedExpr (snd <$> pNamedExpr)
- Add validation that round() decimals parameter must be numeric
- Remove outdated doctest for round with arithmetic expression

* Improve parser robustness and add error validation tests

- Add eof to parseQuery to require consuming all input
- Remove try from pCoalesce and pRound to propagate validation errors
- Add sanitizeAlias to replace dots with underscores in SQL aliases
- Add error tests for dcount accuracy, coalesce args, round decimals
- Update test expectations to match new alias output format

* Support nested aggregations in type-casting functions

Add ScalarExpr type to enable patterns like round(countif(...), 2) or
tofloat(sum(field)). Type-casting functions (round, tofloat, toint,
tostring) now accept either values or nested aggregations.

- Add ScalarExpr (SVal | SAgg) with Display/ToQueryText instances
- Add aggToSqlNoAlias for SQL generation without AS alias
- Extract baseAggParsers for reuse in nested parsing
- Add pScalarExprNested parser for nested expressions
- Add getAlias helper to extract explicit aliases

* Improve Stats parser: generic-lens, helpers, validation, tests

- Extract simpleAggSQL and percentileSQL helpers to reduce duplication
- Replace getAlias/setAlias with generic-lens typed accessors
- Allow dots in pNamedExpr names (sanitized to underscores)
- Add round() decimals validation (0-15 per PostgreSQL limit)
- Add tests for nested aggregations, project SQL, round validation

* Add integration tests for nested aggregation SQL generation

- Full SQL verification for round(countif(...), N)
- Tests for tofloat(sum()), toint(count()) nested patterns
- Tests for extend/project with nested aggregations
- Tests for named nested aggregations preserving aliases
- Minor cleanup: use {} pattern syntax in defaultAlias

* Auto-format code with fourmolu

* Support negative numbers in parser for round() validation

Use L.signed wrapper for L.float and L.decimal to parse negative
numbers like -1, enabling round() decimals validation to properly
reject negative values.

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-01-08 15:26:32 +01:00
Anthony Alaribe
5fdd12690c
Fix SQL syntax error when casting aggregations with aliases (#274)
The chart query was generating invalid SQL like `(count(*) AS count_)::float`
because the float cast wrapped the entire expression including the alias.

Fixed by adding ::float cast directly in Count/CountIf/DCount Display instances,
so the alias is correctly placed after the cast: `count(*)::float AS count_`
2026-01-08 00:13:29 +01:00
Anthony Alaribe
c64fe1efac Fix incomplete pattern match for SLTrace in SystemLogs
Add missing SLTrace case to mkSystemLog function with severity
number 1 matching OpenTelemetry specification.
2026-01-07 22:35:02 +01:00
Anthony Alaribe
d418d187be Fix incomplete pattern match for SLTrace severity level
Add missing SLTrace case to severityStyle and severityText functions
in SummaryGenerator.hs. This fixes the CI build failure caused by
-Werror=incomplete-patterns.
2026-01-07 22:15:31 +01:00
Anthony Alaribe
69b56958c4
Create KQL operators documentation (#267)
* Add comprehensive KQL reference documentation

Document all KQL operators and functions supported in Monoscope:
- Comparison, string, membership, and logical operators
- Pipe operators (where, summarize, sort, take)
- Aggregation functions including percentiles and conditional counts
- Scalar functions (strcat, coalesce, iff, case)
- Date/time functions (now, ago, bin, bin_auto)
- Field reference syntax including nested JSON and OTel attributes
- Extensive query examples for common use cases

* Add KQL-standard default column aliases for aggregations

- Generate default aliases like count_, sum_field when no explicit alias provided
- Update Display instance to include AS alias clause in generated SQL
- Document default column naming conventions in KQL reference
- Clarify matches/=~ as syntax variants for regex matching

* Improve KQL documentation clarity and completeness

- Clarify has vs contains operators with examples
- Fix bin_auto() time range table notation
- Add Limitations & Notes section covering:
  - Unsupported KQL features
  - Null handling behavior
  - Type coercion rules
  - Performance tips

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-01-07 20:02:47 +01:00
Anthony Alaribe
07fcc88d4b
Validate and normalize log severity levels on ingestion (#273)
* Validate and normalize log severity levels on ingestion

Invalid severity values (e.g., metric units like "ms", "{vacuums}") are
now stored as NULL instead of polluting log level facets. Valid levels
are normalized to uppercase, and common aliases are mapped:
- WARNING -> WARN
- INFORMATION -> INFO
- CRITICAL -> FATAL
- TRACE -> DEBUG

* Add SLTrace level and consolidate severity parsing functions

- Add TRACE as first-class severity level per OpenTelemetry spec
- Consolidate parseSeverityLevel and normalizeSeverityLevel using shared lookup table
- Reduce 24 lines of case statements to 8 lines

* Auto-format code with fourmolu

* Use Map for O(log n) severity lookup and reduce redundancy

- Replace list with Map.Map for efficient lookup
- Separate canonical levels from aliases to avoid repetition
- Add INLINE pragmas for hot path functions
- Clearer non-point-free style for readability

* Auto-format code with fourmolu

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-01-07 19:32:50 +01:00
Anthony Alaribe
20df28d320
Optimize query editor performance (#269)
* Optimize query editor performance with aggressive Monaco settings

- Add schema resolution caching (nestedCache, valueCache) to avoid
  redundant field lookups on every keystroke
- Add completion request cancellation via version counter to abandon
  stale requests when user types faster than completions resolve
- Add character-based pre-checks before running expensive regex patterns
- Disable Monaco features that add per-keystroke overhead:
  - accessibilitySupport, matchBrackets, links, contextmenu
  - hover, parameterHints, inlayHints, codeLens, lightbulb
  - occurrencesHighlight, selectionHighlight, colorDecorators
- Use requestIdleCallback in onDidChangeModelContent to defer
  non-critical work off the main thread
- Remove showSuggestions state update from keystroke path to
  reduce Lit component re-renders

* Fix query editor performance issues from code review

- Add cache invalidation to setDynamicResolver to prevent stale results
- Add fast-path includes('.') check before regex in updateSuggestions/insertCompletion
- Precompile whitespace and word boundary regexes used in hot loop
- Fix redundant mouseover re-renders by checking if selectedIndex changed
- Clean up global resize/keydown event listeners in disconnectedCallback

* Simplify filterAndSlice and fix requestIdleCallback fallback

- Revert filterAndSlice to simpler filter().slice(0,5) pattern
- Fix requestIdleCallback fallback - setTimeout doesn't accept options object
2026-01-07 19:08:25 +01:00
Anthony Alaribe
7bd351203a
Add widget-integrated alerts feature (#272)
* Add widget-integrated alerts feature

Enable creating and managing alerts directly from dashboard widget details:
- Add widget_id, dashboard_id, and recovery threshold columns to query_monitors
- Add Alerts tab to widget expand view with full configuration form
- Render threshold marklines on charts (configurable: always/on_breach/never)
- Show alert status indicator on widget headers (bell icon with colors)
- Add source column to Alerts page showing Widget vs Log Explorer origin
- Sync widget query changes to linked alerts automatically
- Delete alerts when widgets are removed from dashboards
- Support recovery thresholds (hysteresis) to prevent alert flapping
- Populate widget alert status at render time for real-time indicators

* Auto-format code with fourmolu

* Fix widget alerts: clone on duplicate, sync queries, persist status

- Clone alerts when duplicating widgets with new alert ID tied to new widget
- Sync widget query changes to associated alert's logQuery and logQueryAsSql
- Prevent direct query modification for widget-tied alerts
- Add current_status column to track alert state (migration 0026)
- Extract normalizeWidgetId, alertActiveWindow, mkMarkLine helpers
- Use stored current_status in getWidgetAlertStatuses instead of computing

* Auto-format code with fourmolu

* Fix widget alerts: add missing current_status field and lowercase status values

- Add current_status to SQL queries in getAlertsByTeamHandle, getActiveQueryMonitors,
  queryMonitorByWidgetId, queryMonitorsByDashboardId
- Fix case sensitivity: use lowercase status values to match SQL constraint
- Remove redundant pass statement, simplify wasAlerting/wasWarning with helper

* Cache current_value to avoid eval() on every dashboard load

- Add current_value column to query_monitors table
- Store evaluated value during background job instead of computing on read
- Replace eval(log_query_as_sql) with cached current_value in getWidgetAlertStatuses
- Remove unnecessary null guard from deleteMonitorsByWidgetIds
- Use foldMap for statusMap construction

* Simplify monitor status logic and extract updateTabBySlug helper

- Refactor monitorStatus to use breached/recovered predicates instead of
  duplicated comparison logic for triggerLessThan
- Use currentStatus field directly instead of time-based alerting checks
- Extract updateTabBySlug helper in Dashboards to reduce code duplication

* Auto-format code with fourmolu

* Consolidate widget alert migrations into single file

* Move showThresholdLines from monitor to widget configuration

showThresholdLines is a display setting that belongs in the widget JSON,
not the monitor database table. This change:
- Removes show_threshold_lines column from query_monitors table
- Updates widgetAlertUpsertH to save showThresholdLines to the widget
- Widget already has this field in its JSON schema

* Use DOUBLE PRECISION for threshold and metric values

Support decimal values (e.g., 0.5, 32.5°C) in monitor thresholds:
- Migration: Convert alert_threshold, warning_threshold to DOUBLE PRECISION
- Migration: New columns use DOUBLE PRECISION (recovery thresholds, current_value)
- Haskell: Update all threshold/value fields from Int to Double
- Remove fromIntegral conversions in BackgroundJobs

* Code cleanup: simplify BackgroundJobs and add NOT NULL constraints

- Simplify sum/map to list comprehension: sum [v | Only v <- results]
- Inline wasAlerting/wasWarning in monitorStatus call
- Use void consistently instead of _ <- pattern
- Simplify breached/recovered predicates in monitorStatus
- Use && instead of , in guards for clarity
- Add NOT NULL to current_status and current_value columns

* Auto-format code with fourmolu

* Fix: remove stale show_threshold_lines from SELECT queries

* Fix: rename 'first' variable to avoid shadowing Bifunctor.first

* Refactor: use _select from pg-entity instead of manual column lists

* Refactor: address code review feedback for alerts-in-widgets

- Add MonitorStatus ADT (MSNormal/MSWarning/MSAlerting) replacing string literals
- Simplify applyAlertStatus using fromMaybe/do pattern
- Add warning log when widget alert query parsing fails
- Fix race condition by deleting monitors before dashboard update
- Normalize widgetId once at function entry in dashboardWidgetPutH

* Auto-format code with fourmolu

* Fix: format threshold values with thousand separators

* Refactor: extract formatWithCommas to Utils.hs

* Refactor: extract shared alert UI helpers to Pages/Monitors.hs

- Add thresholdInput_, recoveryInput_, directionSelect_, frequencySelect_, collapsibleSection_
- Update Dashboards.hs widgetAlertConfig_ to use shared helpers
- Update Log.hs alertConfigurationForm_ to use shared helpers
- Net reduction of ~37 lines through DRY refactoring

* Auto-format code with fourmolu

* Style: use surface-raised for alert form in Log.hs

* Add integration tests and doctests for alert monitoring

- Add doctests to monitorStatus for hysteresis logic validation
- Add widget alert cascade deletion test
- Add widget alert query sync test
- Add monitor with recovery thresholds integration test
- Export checkTriggeredQueryMonitors and monitorStatus from BackgroundJobs
- Fix missing AlertUpsertForm fields in MonitorsSpec

* Refactor: extract functions and fix hlint warnings

- Extract syncWidgetAlert, normalizeWidget, updateDashboardWidgets from dashboardWidgetPutH
- Extract evaluateQueryMonitor with error handling for SQL failures
- Fix hlint warnings: use toText, one, and function composition

* Auto-format code with fourmolu

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-01-07 18:13:18 +01:00
Anthony Alaribe
91b7cf4953 Fix doctests for text casts and ambiguous fields warning
- Update doctest expected outputs to include ::text casts for text operators
  (Has, NotHas, Contains, NotContains, StartsWith, NotStartsWith, EndsWith, NotEndsWith)
- Fix ambiguous record update warning in Pages/Api.hs by using explicit record construction
2026-01-07 00:18:07 +01:00
Anthony Alaribe
5f95c341dc Fix Tagify dropdown hover styles and positioning
- Add !important to hover/active styles to override library defaults
- Change dropdown position from 'text' to 'input' for proper alignment
- Consolidate hover and active selectors
2026-01-06 23:58:56 +01:00
Anthony Alaribe
e6b4af2a66 Refactor Tagify initialization and add dropdown styling
- Use createTagify helper instead of inline Tagify instantiation
- Add CSS styles for Tagify dropdown with dark mode support
2026-01-06 23:54:49 +01:00
Anthony Alaribe
94bb50c51d Fix trace rendering span overflow and improve text legibility
- Fix span overflow bug by using actual time range (maxEndTime - minStartTime)
  instead of max duration for rootVal calculation
- Add getContrastTextColor that returns tinted text colors instead of pure
  white/black for softer, more visually pleasing appearance
- Add left padding (ml-1) to span text for better readability
- Simplify buildHierarchy function and fix serviceName type in WaterfallItem
2026-01-06 23:37:58 +01:00
Anthony Alaribe
1863d2fab1 Fix widget order being saved to wrong tab on HTMX tab switch
When switching tabs via HTMX, the widget-order-trigger form retained
its original hx-patch URL pointing to the initially loaded tab. This
caused widget reorder operations on other tabs to incorrectly update
the original tab's widget order, making it appear empty.

Added OOB swap in dashboardTabContentGetH to update the form's hx-patch
URL to the current tab whenever a tab switch occurs.
2026-01-06 23:31:36 +01:00
Anthony Alaribe
e15b13ff2a Fix text operators on JSONB columns by casting to text
When using contains/has/startswith/endswith operators on columns without
field keys (like `body contains "value"`), cast to ::text to support
JSONB columns. Previously this generated invalid SQL like
`body ILIKE '%value%'` which fails with "operator does not exist: jsonb ~~* text".

Now generates `body::text ILIKE '%value%'` which works for both text and
JSONB columns.
2026-01-06 23:09:40 +01:00
Anthony Alaribe
9afc3ab52c Add configurable legend sizes and fix widget reorder bug
- Add legendSize field to Widget (xs, sm, md, lg) with sm as default
- Fix bug where empty widget reorder patch would wipe all widgets
- Set Log.hs widgets to use xs legend size
2026-01-06 22:52:10 +01:00
Anthony Alaribe
34d649d1dc Add appendToBody to chart tooltip to prevent clipping 2026-01-06 22:33:49 +01:00
Anthony Alaribe
5a9df00d42 Improve widget legend positioning and sizing
- Add support for compound legend positions (top-right, top-left, bottom-right, bottom-left)
- Make legend items smaller: 6x6 indicator, font size 10
- Reduce chart-to-legend gap from 18% to 14%
- Add negative padding to reduce icon-to-text gap
- Update Log Explorer charts to use top-right legend position
2026-01-06 22:26:28 +01:00
Anthony Alaribe
d39e83a46a
Refactor enums to use deriving via WrappedEnumSC (#271)
* Refactor enums to use deriving via WrappedEnumSC

- Fix WrappedEnumSC FromField to use toPascal/fromSnake instead of T.toTitle
  (was breaking multi-word snake_case like "runtime_exception")
- Add FromHttpApiData instance to WrappedEnumSC
- Refactor AnomalyTypes, AnomalyActions, ConversationType, FieldCategoryEnum,
  and Permissions to derive ToField/FromField/Display via WrappedEnumSC
- Remove manual instance boilerplate (~100 lines)
- Update RequestMessages.hs to use display instead of fieldCategoryEnumToText

* Auto-format code with fourmolu

* Derive more ToField/FromField instances

- Add WrappedEnumShow wrapper for Show/Read-based enums
- Derive SDKTypes and RequestTypes via WrappedEnumShow
- Derive PGTextArray via newtype deriving
- Derive ProjectS3Bucket via Aeson

* Auto-format code with fourmolu

* Replace Unsafe.read with readMaybe for safe enum parsing

FromField instances now return ConversionFailed error with details
instead of crashing on invalid database values.

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-01-06 21:58:34 +01:00
Anthony Alaribe
7fe1dce991
System logs support. IE logs about actions monoscope performs onbehalf of the user (#270)
* system logs

* Auto-format code with fourmolu

* Simplify SystemLogs to use existing SeverityLevel type

Remove redundant SystemLogSeverity type and use SeverityLevel
(SLInfo, SLWarn, SLError) from Telemetry module directly.

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-01-06 21:20:56 +01:00
Anthony Alaribe
1108c73235 Fix log-list action rows to be clickable anywhere on the row
- Make entire row clickable for "Check for recent data", "Load more", and
  "Expand time range" actions instead of just the text link
- Fix row heights to match virtualizer's 28px item size to prevent overlaps
- Add CSS rule to prevent clicks on closed popovers
2026-01-06 21:05:09 +01:00