Skip to content

feat(fields): persist structured field validation warnings and gate Ready #527

Closed

Description

@duguankui

Background

A type-bound field prompt may contain validation rules for the field it extracts. A bank-statement transaction table is a representative downstream configuration:

  1. The first row's balance is the opening balance and already includes that row's transaction.
  2. From the second row onward: current balance = previous balance + current credit - current debit.
  3. Opening balance + credits from row 2 onward - debits from row 2 onward = closing balance.
  4. The first row's credit/debit must not be counted twice.
  5. A mismatch means the source document or extraction result needs human review; the model must not invent fees, interest, FX transactions, or any transaction absent from the source.

This repository must not hard-code bank-statement rules, balance formulas, or a business type such as finance.bank-statement. Those rules remain downstream configuration in a field prompt or a future dedicated validation configuration.

The current FieldExtractionWorkflow returns only field name -> field value. Mapping a validation failure to null loses the important distinction between:

  • the field was not extracted; and
  • the field was extracted, but its internal validation did not pass.

The second case must preserve the extracted value so an operator can compare it with the source file. Warning text must not be inserted into the field value, a Markdown table, a memo column, ExtractedFields, searchable field values, or exported business data.

Goals

  • Keep extracted field values and validation warnings as separate, strongly typed data.
  • Return both from the same structured LLM response; do not add a second LLM call for validation.
  • Preserve the model-extracted value when validation fails.
  • Persist structured warnings associated with the correct field.
  • Route the document to operator review and block Ready until:
    • a clean field re-extraction replaces the warning set; or
    • an operator explicitly resolves the warning after comparing the source file.
  • Provide source comparison, field correction, field re-extraction, and explicit resolution actions in the document detail and review-queue UI.
  • Keep the mechanism generic and business-type-independent.
  • Preserve the six-stage ETO contract and thin event payloads.
  • Maintain en, ja, zh-Hans, and zh-Hant localization.
  • Regenerate the Angular proxy after backend contract changes.

Non-goals

  • No built-in bank-statement schema, balance formula, business validator, or business document type.
  • No downstream finance/business aggregate in Vault Extract Core.
  • No Dictionary<string, object> persistence extension bag.
  • No warning text in Markdown, field values, search indexes, export field columns, or ETO payloads.
  • No validation retry loop and no extra LLM call.
  • No generic rule engine or deterministic expression language in this issue.
  • No permanent in-product warning-history aggregate; operator resolution is recorded through the existing ABP audit system.

Design decisions

1. One structured LLM response containing values and warnings

Change the workflow contract from a bare dictionary to a strongly typed result, for example:

public sealed record FieldExtractionWorkflowResult(
    IReadOnlyDictionary<string, JsonElement?> Values,
    IReadOnlyList<FieldValidationWarningResult> ValidationWarnings);

public sealed record FieldValidationWarningResult(
    string FieldName,
    string Message);

The structured response schema becomes:

{
  "values": {
    "transactions": "| Date | Credit | Debit | Balance |\n| ... |"
  },
  "validationWarnings": [
    {
      "fieldName": "transactions",
      "message": "The balance after row 4 does not match the previous balance plus this row's credit minus debit."
    }
  ]
}

Required behavior:

  • values retains the extracted value even when the same field has a warning.
  • Missing or unparseable values continue to become null and are handled by the existing type validation and MissingRequiredFields logic.
  • A validation warning is never represented as null and is never mapped to MissingRequiredFields.
  • The system instruction owns the generic rule: retain the extracted source value, report validation failures separately, and never fabricate missing source data.
  • Field prompts and document Markdown continue to be wrapped by PromptBoundary.
  • The external LLM call remains outside an ambient unit of work.

2. Extend the existing FieldDefinition.Prompt contract

Do not add a separate ValidationPrompt column in this issue.

Reasons:

  • Existing downstream configurations already place extraction and validation requirements in the same field prompt.
  • Extraction and validation must operate over the same document and same result in one model call.
  • Two independent instruction fields create conflict/precedence rules and require unnecessary migration, CRUD, UI, and proxy work.
  • A dedicated validation configuration remains a future option if deterministic validators, rule versioning, or reusable cross-field rule sets become a demonstrated need.

Update documentation and UI help text so FieldDefinition.Prompt explicitly supports:

  • what to extract and its output format;
  • validation rules, when applicable; and
  • warn-only behavior: preserve the source-derived value and do not invent corrections.

3. Bound and validate untrusted warning output

Add shared constants, with the initial limits:

  • maximum 32 warnings per extraction;
  • maximum one merged warning per field;
  • field name uses the existing 64-character allow-listed contract;
  • maximum warning message length: 512 characters.

The JSON Schema must constrain:

  • validationWarnings.maxItems;
  • fieldName to the declared field-name enum;
  • message.maxLength;
  • required properties; and
  • additionalProperties = false.

The server must still defensively normalize the model response:

  • discard warnings for undeclared fields;
  • discard blank messages;
  • deduplicate by field;
  • safely truncate overlong messages at a valid UTF-16 character boundary;
  • take at most the configured warning count;
  • log discarded/truncated output without failing or discarding otherwise valid field values.

Malformed warning entries must not cause valid extracted values to be lost.

4. Persist warnings as a Document child collection

Add a strongly typed child entity such as DocumentFieldValidationWarning under the Document aggregate:

  • DocumentId
  • TenantId
  • FieldDefinitionId
  • Message

Use (DocumentId, FieldDefinitionId) as the composite key, reflecting one merged warning per field.

The database stores the immutable FieldDefinitionId, not field-name/display-name snapshots. REST DTOs resolve the active field definition and expose:

  • FieldDefinitionId
  • FieldName
  • FieldDisplayName
  • Message

This follows the field architecture v2 rule that internal associations use immutable IDs and avoids rename drift. A deleted field definition no longer has an active warning and must be cleaned up as described below.

The child entity:

  • is modified only through Document;
  • has no standalone repository;
  • implements IMultiTenant;
  • cascades on hard deletion of the owning Document; and
  • does not participate in field-value indexes or search queries.

Add an aggregate operation such as ReplaceFieldValidationWarnings(...) that reconciles the whole collection and updates the corresponding review-reason bit in the same operation. This prevents collection/review-bit divergence.

5. Add a blocking review reason

Add:

DocumentReviewReasons.FieldValidationWarning = 1 << 5

Include it in ReviewReasonPolicy.Blocking.

Semantics:

  • field extraction may complete successfully and publish FieldsExtractedEto;
  • extracted values are persisted normally;
  • when one or more warnings are present, lifecycle derives to PendingReview;
  • DocumentReadyEto is withheld;
  • MissingRequiredFields remains independent and non-blocking;
  • multiple review reasons may coexist.

Every blocking reason needs an operator-reachable clearing path. The clearing paths for this reason are:

  1. a later clean field extraction replaces the warning collection with an empty collection; or
  2. an explicit operator resolution clears selected warnings after source comparison.

6. Save values and the current warning set atomically

The field-extraction write phase must perform, in the same short UoW:

  1. reload the Document with field values and validation warnings;
  2. verify tenant ownership;
  3. verify the current DocumentTypeId still matches the phase-1 snapshot;
  4. reload current field definitions;
  5. filter values and warnings against current definitions;
  6. replace the full field-value set;
  7. replace the full validation-warning set;
  8. recompute MissingRequiredFields, field fingerprint, and duplicate suspicion;
  9. clear FieldExtractionIncomplete after a completed LLM extraction;
  10. persist the Document; and
  11. publish the thin FieldsExtractedEto through the transactional outbox.

A successful re-extraction always replaces, rather than appends to, the old warning set.

The no-field-definition path clears residual field values, validation warnings, fingerprints, and field-owned review reasons before publishing an empty FieldsExtractedEto.

7. Handle schema changes and in-flight races

  • Reclassification to another type clears the previous type's validation-warning collection immediately.
  • Becoming unclassified or a container clears all type-bound validation warnings.
  • Deleting a field definition clears warnings associated with that field from affected documents through the Document aggregate and re-derives lifecycle.
  • Renaming a field does not require a snapshot update; DTO projection resolves the current name/display name.
  • A prompt edit does not silently clear warnings. Admins explicitly trigger field re-extraction when they want the new prompt to supersede the current result.
  • If the document is reclassified while the LLM call is in flight, the existing DocumentTypeId guard discards both values and warnings.
  • If a field is deleted, disabled, or changes DataType/AllowMultiple while the LLM call is in flight, discard both the stale value and stale warning for that field.
  • Unknown model field names never create review state.

8. Close the reclassification -> Ready race

Today, successful classification publishes DocumentClassifiedEto, and the distributed FieldExtractionEventHandler later creates the field-extraction run. When an older field-extraction run is already succeeded, classification completion can briefly derive Ready before the new run exists.

This issue must make internal cascade scheduling transactional with classification completion:

  • once a concrete type has been assigned, create the new pending field-extraction DocumentPipelineRun before classification can derive Ready;
  • enqueue the field-extraction job with that exact run ID in the same UoW;
  • then complete the classification run, which continues to derive Processing because the new field-extraction run is pending;
  • keep publishing DocumentClassifiedEto as the external six-stage event;
  • remove or narrow the current distributed handler's internal scheduling responsibility so it cannot enqueue a duplicate run.

The internal pipeline must not depend on delayed consumption of its own external ETO to establish the Ready gate.

Add a defensive current-state check in the Ready-event handler so a stale/intermediate lifecycle event cannot publish DocumentReadyEto after the Document has already returned to Processing or PendingReview.

9. Explicit operator resolution and auditing

Add a dedicated application command, for example:

Task<DocumentDto> ResolveFieldValidationWarningsAsync(
    Guid documentId,
    ResolveFieldValidationWarningsInput input);

The input contains:

  • a bounded list of FieldDefinitionId values to resolve; and
  • an internal resolution kind:
    • SourceConfirmed: the operator confirmed that the source file itself contains the data as extracted;
    • CorrectedManually: the operator corrected the field value after comparing the source.

The Angular UI must localize these as plain office-user actions and must not display enum names.

Rules:

  • UpdateExtractedFieldsAsync does not automatically clear validation warnings.
  • Saving a manual correction leaves the warning visible until the operator explicitly confirms it as corrected.
  • Resolving selected warnings clears the review reason only when no active warnings remain.
  • Re-derive lifecycle after resolution so the Document may transition to Ready and publish DocumentReadyEto.
  • Reject resolution while field extraction is pending/running, preventing an in-flight result from immediately overwriting the human decision.
  • ABP audit logging records the user, time, document, selected fields, and resolution kind. Entity changes record the warning removals. Do not add a parallel permanent warning-history table in this issue.

10. REST and Angular UX

Add a FieldValidationWarningDto and expose warnings in:

  • DocumentDto / ReviewReasonDetailDto for the detail page;
  • a bounded summary on DocumentListItemDto for the review queue.

Document detail:

  • show the affected field display name;
  • show the concise warning message as escaped text, never rendered as HTML;
  • offer "Re-extract fields";
  • offer "Edit fields";
  • offer "Confirm source data";
  • offer "Confirm corrected";
  • keep source-file preview available for comparison.

Review queue:

  • show field display name + warning summary, not only a generic badge;
  • offer "Re-extract fields";
  • offer "Review source and data", navigating to the detail workflow;
  • do not provide a blind one-click release that bypasses source comparison.

Suggested zh-Hans static hint, using the field display name dynamically:

"{0} failed its data consistency check. Re-extract the fields first. If the issue remains, compare the source file and decide whether the source data is correct or the extracted result needs correction."

Provide equivalent en, ja, zh-Hans, and zh-Hant localizations. The actual localized wording should be natural in each language.

Remove the rejected experimental edits that changed only Document:Review:Hint:MissingRequiredFields. Validation failure must not be presented as required-field absence.

Regenerate Angular proxies with the repository command:

cd angular
npm run generate-proxy

Do not hand-edit generated proxy files.

11. Search, export, and egress isolation

  • ExtractedFields is assembled only from DocumentExtractedField.
  • Structured field search reads only typed field-value rows.
  • Validation-warning rows have no field-search indexes and are never consulted by field filtering.
  • CSV/XLSX export adds no warning column and never contains warning messages.
  • The existing generic ReviewReasons system metadata may truthfully carry FieldValidationWarning; the field-level warning text must not enter exported business-field data.
  • FieldsExtractedEto and DocumentReadyEto remain thin and contain no warning text.
  • Primary downstream consumers are protected by the blocking Ready gate.
  • REST is the operator-facing channel for structured warning details.

Database migration

Add a new table for DocumentFieldValidationWarning and update the Host EF Core migration/model snapshot.

Expected migration scope:

  • one new child table;
  • composite primary key (DocumentId, FieldDefinitionId);
  • tenant column;
  • bounded message column;
  • FK to Document with cascade hard delete;
  • FK to FieldDefinition with restrictive hard-delete behavior;
  • no new FieldDefinition.ValidationPrompt column;
  • no new Document column for the review reason because ReviewReasons is already a persisted flags integer.

Review the generated migration for accidental unrelated schema changes.

Acceptance criteria

Workflow and output validation

  • One structured LLM response returns field values and at least one field validation warning.
  • A warned field retains its extracted value.
  • The warning resolves to the correct FieldDefinitionId, current field name, and display name.
  • A warning never changes the value to null merely because validation failed.
  • An undeclared field warning is discarded and cannot set review state.
  • Blank warning text is discarded.
  • Overlong warning text is safely truncated at a character boundary.
  • Duplicate warnings for one field are merged/deduplicated.
  • Excess warnings are bounded.
  • Malformed warning entries do not discard otherwise valid field values.
  • Empty field definitions short-circuit without an LLM call and clear stale field-owned state.

Persistence and lifecycle

  • Values and the current warning set are saved in the same transaction.
  • FieldsExtractedEto is enqueued atomically with the extraction write.
  • A warning sets FieldValidationWarning and moves/keeps the Document in PendingReview.
  • FieldValidationWarning is blocking in ReviewReasonPolicy.
  • DocumentReadyEto is not published while warnings remain.
  • A clean re-extraction replaces and clears old warnings.
  • Clean re-extraction re-derives Ready when no other blocker remains.
  • Reclassification clears old warnings and queues the new field-extraction run before Ready can be derived.
  • Becoming unclassified or a container clears warnings.
  • Deleting a field definition removes its active warnings and re-derives affected documents.
  • A field definition deleted/type-changed during the LLM call cannot receive a stale value or warning.
  • A Document reclassified during the LLM call receives neither stale values nor stale warnings.
  • Manual field editing alone does not clear warnings.
  • Explicit source confirmation clears selected warnings and is audited.
  • Explicit corrected confirmation clears selected warnings and is audited.
  • Manual resolution re-derives the correct lifecycle/Ready state.
  • Resolution is rejected while field extraction is in progress.

REST and Angular

  • REST detail DTO exposes structured warnings with field ID, name, display name, and message.
  • Review-reason detail marks the reason as blocking.
  • Review-list DTO exposes a bounded warning summary.
  • Document detail renders affected fields, warning text, re-extraction, source confirmation, and correction actions.
  • Review queue renders affected fields and warning summaries and provides safe navigation/actions.
  • UI uses localized office-user wording rather than command-line parameters, enum names, pipeline codes, or implementation terminology.
  • en, ja, zh-Hans, and zh-Hant resources are complete.
  • Angular proxies are regenerated, not hand-written.

Isolation and regression

  • Warning text does not enter ExtractedFields.
  • Warning text does not enter field search/filter values.
  • Warning text does not enter CSV/XLSX business data.
  • Warning text does not enter ETO payloads.
  • Existing FieldExtraction tests remain green.
  • Existing MissingRequiredFields behavior and non-blocking policy remain green.
  • Existing DuplicateSuspected behavior and blocking policy remain green.
  • Existing oversized FieldExtractionIncomplete behavior remains green.
  • Existing export/search tests remain green.
  • Existing reclassification and field re-extraction tests remain green.
  • External LLM work is still verified to run with no ambient UoW.

Test plan

  • FieldExtractionWorkflow_Tests: new response envelope, value+warning result, unknown/blank/long/duplicate/over-count warnings, malformed warning isolation, existing typed-value validation.
  • FieldExtractionService_Tests and field-extraction integration tests: atomic replacement, correct field association, clean re-extraction, schema changes, in-flight reclassification, no-field path, ETO atomicity.
  • Domain tests: warning reconciliation, review-bit coupling, blocking policy, reclassification/container/unclassified clearing.
  • EF Core tests: mapping, composite key, tenant isolation, cascade delete, field-definition cleanup.
  • DocumentPipelineRunManagerTests and classification/background-job tests: no Ready window, stale Ready-event suppression, clean/manual release.
  • DocumentAppService_ExtractedFields_Tests: manual edit does not clear warnings, explicit resolution, DTO projection, correct lifecycle.
  • Export/search tests: warning messages are absent from business data and query values.
  • Angular/Vitest: enum contract, detail rendering, review-list rendering, localized action wiring, proxy contract.
  • Run targeted suites first, then full dotnet test, Angular tests/build, and migration review.

Downstream field-prompt example

A downstream bank-statement project may configure its transactions field prompt along these lines:

Extract the transaction details as a strict Markdown table using only values present in the source. The first row's balance is the opening balance and already reflects that row's transaction. From row 2 onward, each balance should equal the previous balance plus the current credit minus the current debit. The opening balance plus credits from row 2 onward minus debits from row 2 onward should equal the closing balance. Do not count the first row's transaction twice. If these checks do not hold, preserve the complete table exactly as extracted, do not invent or insert fees, interest, FX, or other transactions absent from the source, and mark this field for staff review with a concise explanation of the mismatch.

Core interprets only the generic value + warning contract. The business formula remains downstream configuration.

Related issues

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions