Detecting Problems
Detection is the application-specific process that searches for unhealthy data and reports each occurrence to Data Health with found().
Contents
Section titled “Contents”- Establish the application rule
- When to implement detection
- The CanDetect contract
- Write a focused detection query
- Report problems with found
- Pass context to a finding
- Return a useful result
- Design detection to be repeatable
- What repeat detection does
- Detection does not resolve missing results
- Run detection manually
- Test detection behavior
Establish the application rule
Section titled “Establish the application rule”Before implementing a finding, establish a concrete invariant from application code and requirements. A column name, nullable field, or missing relationship alone does not prove that a record is unhealthy.
For each candidate, identify:
| Decision | Evidence to collect |
|---|---|
| Invariant and scope | The rule and records it applies to, supported by domain actions, services, validation, queries, tests, or documented requirements. |
| Legitimate exceptions | Historical states, imports, optional relationships, tenant boundaries, and other valid cases. |
| Occurrence identity | The affected model and stable context needed to distinguish and recheck one occurrence. |
| Correction | An existing application action that can safely restore the invariant, or the business judgment still required. |
For example, a missing email address is a finding only if the application requires email for that customer category. Imported accounts, anonymized customers, or records created before a policy change may be legitimate exceptions. Exclude exceptions based on application evidence rather than inventing cutoffs or inferring policy from a field name.
If the evidence is insufficient, explain the candidate and missing business decision
before implementing it. Start with a class extending Finding directly and keep its
lifecycle together. Reuse existing domain services when they own the logic; introduce
new shared abstractions or schema-wide reflection only for demonstrated needs.
Assess resolution for every finding. Implement it when the application establishes a
deterministic, safe correction. Otherwise explain the judgment required and omit
CanResolve. Implementing it exposes an action; automatic execution is a separate opt-in.
When to implement detection
Section titled “When to implement detection”Implement detection when Data Health can search for every current occurrence of a problem. Typical detection sources include:
- an Eloquent query that selects invalid model states;
- calculated values that disagree with stored values;
- missing or conflicting relationships;
- results returned by another service; and
- rules that require inspecting several fields or records together.
See What You Can Check for a complete finding class and focused detection code for each of these patterns.
Detection is optional. If application code already knows exactly when a problem occurs, it can report the finding directly:
PaidOrderMarkedPending::found($order);For example, an import pipeline may report malformed source data at the point it is encountered, while a periodic reconciliation check is better represented by detect().
Use detection when the rule can be rerun safely and should find the same current problems each time.
The CanDetect contract
Section titled “The CanDetect contract”A detectable finding implements DataHealth\Contracts\CanDetect and defines a static detect() method:
use DataHealth\Contracts\CanDetect;use DataHealth\Finding;
class PaidOrderMarkedPending extends Finding implements CanDetect{ public static function detect(): null { // Search for problems and report each one.
return null; }}The method is static because detection searches for occurrences before a particular affected model or finding object exists.
Implementing CanDetect also makes the finding eligible for health:detect, scheduled detection, manual execution from Data Health Filament, and other integrations that operate on detectable finding classes.
Write a focused detection query
Section titled “Write a focused detection query”Filter unhealthy records in the database whenever the rule can be expressed as a query. This avoids loading healthy models only to discard them in PHP.
The finding from the Quick Start detects paid orders that are still pending:
use App\Models\Order;
Order::query() ->whereNotNull('paid_at') ->where('status', 'pending');Process the result in a memory-safe way and report each occurrence:
public static function detect(): null{ Order::query() ->whereNotNull('paid_at') ->where('status', 'pending') ->eachById(function (Order $order): void { self::found($order); });
return null;}eachById() avoids loading the entire result set into memory. For checks that should intentionally inspect only a limited portion of a table per run, use the persistent cursor described in Large Datasets.
Report problems with found
Section titled “Report problems with found”Call the finding class’s inherited found() method for every occurrence:
$record = PaidOrderMarkedPending::found($order);found() constructs the finding and asks Data Health to create or refresh the corresponding FindingRecord. It returns that record if detection code needs to inspect or act on it.
Every reported finding must belong to a persisted model with a stable primary key. Save newly created models before passing them to found().
Pass context to a finding
Section titled “Pass context to a finding”Pass context as the second argument when the same finding can occur more than once for one model. A customer missing two required document types, for example, can have one record for each type:
MissingRequiredDocument::found($customer, [ 'document_type' => 'tax-certificate',]);The context becomes part of finding identity, so each document type produces a separate record. See Context for choosing stable values and using context during verification and resolution.
Return a useful result
Section titled “Return a useful result”Use inline detect(): null for ordinary findings. The full CanDetect contract also permits integers, callables, and Detector class strings for advanced integrations.
Return null by default to keep detection focused on reporting findings:
public static function detect(): null{ // Search for problems and report each one with self::found().
return null;}An integer count is optional and does not create finding records. Core command, scheduled, and queued detection discard counts; their progress measures finding classes. Filament manual detection displays a returned integer in its success notification, and direct application callers can consume it. Count occurrences reported, rather than candidate models scanned.
A callable allows a supporting caller to invoke deferred detection through Laravel’s container. It should return an integer or null:
public static function detect(): callable{ return function (OrderReconciler $reconciler): null { $reconciler->detectProblems();
return null; };}Core manual, scheduled, and queued detection invoke returned callables through Laravel’s container and resolve classes implementing Detector, including constructor dependencies. A dedicated detector implements detect(): ?int and still reports occurrences with the finding’s found() method. See Contracts and delegation for an example.
Filament manual detection invokes callables but currently does not resolve Detector class strings or honor Async routing. Direct PHP callers must evaluate returned callables or handlers themselves. Add Async only to detect() to queue core package-managed detection; direct calls remain synchronous.
Design detection to be repeatable
Section titled “Design detection to be repeatable”Production detection should be safe to run more than once. A repeatable detector:
- reports the same identity for the same occurrence;
- leaves business-data corrections to resolution (explicit
AutoResolvemay invoke it whenfound()creates a record); - does not rely on process-local state from a previous run;
- can resume after a partial failure without creating duplicates; and
- limits memory use and external requests appropriately.
Data Health provides idempotent record creation through its identity constraint, but the detection query and any surrounding application behavior remain your responsibility.
Avoid wrapping a large scan in one database transaction. If detection fails halfway through, findings already reported remain valid and the next run can safely refresh them.
What repeat detection does
Section titled “What repeat detection does”Finding identity combines the finding key, affected model type, model ID, and context hash. Reporting that same identity again updates the existing record rather than inserting another one.
The existing status determines what happens:
| Current status | Result of detecting it again |
|---|---|
active |
Remains active and refreshes last_detected_at. |
ignored |
Remains ignored and refreshes last_detected_at. |
resolved |
Becomes active and refreshes last_detected_at. |
This means a resolved problem can recur without losing its original record identity, while an intentionally ignored occurrence stays ignored even when detection continues to observe it.
Detection does not resolve missing results
Section titled “Detection does not resolve missing results”A detector reports the problems it sees; it does not automatically resolve active records that were absent from the latest scan.
Absence can be ambiguous: the model may have been filtered out, an external service may have been unavailable, or a batched scan may not have reached that model yet. Automatically resolving every unseen record would therefore produce false resolutions.
Use CanVerify when an existing finding can determine that its underlying problem no longer applies. See Verifying Findings for verification workflows.
Run detection manually
Section titled “Run detection manually”php artisan health:detect PaidOrderMarkedPending -nWithout -n, a terminal session opens finding selection automatically. Piped or redirected runs execute without prompting. The Detection command reference covers every argument, option, queue override, and progress behavior.
Command parameters
Section titled “Command parameters”Use finding keys or class names to select candidates and --except to exclude them. See Detection arguments and options for the complete reference.
Queue a manual run
Section titled “Queue a manual run”Add --async to dispatch detection jobs and optionally override their queue and connection. See Queue a run for command options and Scheduling and Queues for worker setup.
Output and exit status
Section titled “Output and exit status”The command reports each finding and a final summary. See Progress and output for what those counts measure and Exit status for success and failure behavior.
Call detection from PHP
Section titled “Call detection from PHP”Call a detectable finding directly from application code, a job, or Tinker:
use App\DataHealth\PaidOrderMarkedPending;
PaidOrderMarkedPending::detect();For periodic execution, add the Scheduled attribute as described in Scheduling and Queues. Data Health Filament can also expose detectable findings as manual actions; see Finding Types and Detection.
Test detection behavior
Section titled “Test detection behavior”A focused test should prove both that unhealthy models are reported and that healthy models are ignored:
use App\DataHealth\PaidOrderMarkedPending;use App\Models\Order;use DataHealth\Enums\RecordStatus;use DataHealth\Models\FindingRecord;
it('detects paid orders that are still pending', function () { $unhealthy = Order::factory()->create([ 'paid_at' => now(), 'status' => 'pending', ]);
Order::factory()->create([ 'paid_at' => now(), 'status' => 'paid', ]);
PaidOrderMarkedPending::detect();
$record = FindingRecord::query()->sole();
expect($record->status)->toBe(RecordStatus::Active) ->and($record->model->is($unhealthy))->toBeTrue();});Run detection twice in another test and assert that only one record exists for the same identity. When context is involved, test that equivalent context reuses a record and genuinely different context creates another one.
Continue with Context when a model can have multiple occurrences of the same problem, or Large Datasets when one run should process only a controlled batch.