DEV Community

Cover image for How to Keep AI Outputs Explainable in Data-Heavy B2B Products
Vic Tekys for Devico Solutions

Posted on

How to Keep AI Outputs Explainable in Data-Heavy B2B Products

Every team I've worked with that shipped an AI feature into a B2B data product eventually gets the same ticket: *"The number changed and your assistant says it's because of updated supplier data. Which supplier? When did it land?"*Answering it took three engineers, a Slack thread, and a hand-written SQL query against a processing log nobody had designed to be read.

The reflex at that point is to bolt SHAP or LIME onto the model and ship feature importances into the UI. Don't. Feature attribution tells you which input dimensions moved a score. It says nothing about the customer's CSV that failed validation at 03:12, the tenant boundary the recommendation crossed, or the fact that the figure on screen is eleven days stale. Attribution explains the model. Lineage explains the answer. In a data-heavy B2B product, the answer is what's on trial.

NIST draws the same line in the AI Risk Management Framework: "Transparency can answer the question of 'what happened' in the system. Explainability can answer the question of 'how' a decision was made in the system." Most of the tickets you'll get are "what happened" tickets. That's a data-path problem, and it's built by product engineers in ingestion, storage and UI — not by the two data scientists on the team.

The four questions behind "why did it say that?"

Strip the phrasing off enough support tickets and procurement questionnaires and you get four questions, none of which touch model internals:

  1. Which records produced this? Not which features — which rows, which uploaded file, which API sync, which supplier ID.
  2. How fresh are they? Was this computed on last night's batch or on a file that silently stopped arriving in July?
  3. What does the non-AI number say? The deterministic figure the customer already trusted, sitting beside the recommendation, unchanged.
  4. Who else can see this? Tenant and role scope is part of the explanation in every multi-tenant product, and it's the first thing security review asks about.

Each maps to a system property: provenance, freshness, a deterministic fallback surface, access scope. All four are addressable in the pipeline and the UI. None require you to open the model.

The demand is real and it's getting worse, not better. In the 2025 Stack Overflow Developer Survey, 84% of respondents were using or planning to use AI tools, but only 3.1% highly trusted the accuracy of AI output, against 46% who actively distrusted it — and the top frustration, cited by 66%, was "AI solutions that are almost right, but not quite." Google's 2025 DORA report found 90% of respondents using AI at work and 30% reporting little or no trust in what it generates. Your buyers are those developers. They ship AI, they don't trust AI, and they assume yours is wrong until the product shows its work.

One limit worth stating up front: in regulated contexts, lineage isn't a substitute for formal attribution. Article 86 of the EU AI Act gives a person subject to a decision based on a high-risk system the right to "clear and meaningful explanations" of the system's role and the main elements of the decision. If you're in Annex III territory, you owe both. For everyone else, lineage is the part users actually ask for and the part most products don't have.

Provenance starts at ingestion, or it doesn't exist

You can only explain an output if every stage between the customer's file and the figure on screen is named, addressable and replayable. That's an architectural decision made months before anyone writes a prompt.

On a carbon management platform — a German sustainability company, three full-stack developers, running since 2023 — the ingestion path is a serverless AWS pipeline where, as the team put it, a certain service is responsible for a certain stage of the process: CSV upload, validation, processing, then calculation, wired together with Lambda, SNS, SQS and DynamoDB. The driver was volume: customers were entering emission data product by product, and the platform moved to batch file processing so bulk calculations were possible at all. Infrastructure ships per cluster via AWS TypeScript CDK and SAM, because white-label deployments land in different regions depending on where the client sits.

That staging is not lineage tooling — the team built it for throughput and white-label deploys, not for explainability. But it's the precondition. A pipeline with named stages gives you somewhere to hang the record; a monolithic processUpload() gives you nothing.

What to do with those stages once they exist:

  • Give every artifact an ID and carry it forward. Upload ID → row IDs → intermediate record IDs → output ID. If the chain breaks at any hop, the explanation stops there.
  • Make each stage idempotent and replayable. Amazon's own docs are blunt that standard SQS queues guarantee at-least-once delivery, so "more than one copy of a message might be delivered, and messages may occasionally arrive out of order." If a duplicate can double-count a row, your provenance record is a fiction. Replay is also how you reconstruct a decision later without re-uploading the customer's file.
  • Record validation rejections instead of dropping them. The single highest-value row in a lineage table is the one that says 1,204 of 8,900 rows failed schema validation at 03:12. That's the answer to half your "why did it say that" tickets, and if you drop rejects you've destroyed it.
  • Scope every record to a tenant at write time, not at read time. Filtering on the way out is a leak waiting for a bad join.
  • Timestamp arrival separately from event time. "Freshness" means both, and users conflate them.

The envelope doesn't need to be clever. This is enough:

type StageRecord = {

runId: string;          // one ingestion run

tenantId: string;       // scope, written at ingest

stage: 'upload' | 'validation' | 'processing' | 'calculation';

inputRefs: string[];    // IDs of what came in

outputRefs: string[];   // IDs of what went out

rejected: { rowId: string; rule: string }[];

eventTime: string;      // when the data happened

receivedAt: string;     // when we got it

codeVersion: string;    // git sha of the stage

};

codeVersion matters more than it looks. Half the "the number changed and nothing changed" tickets are a deploy.

The trade-off: serverless fan-out suits bursty batch ingest well and sustained streaming badly. If files arrive every ten minutes rather than nightly, price the per-invocation and per-message cost before you copy this shape.

Keep the deterministic surface intact underneath

The cheapest explanation you will ever ship is the unchanged number sitting next to the recommendation. Ship AI *beside*the existing view, not in place of it.

GazeHealth, a US analytics and EMR platform for mental-healthcare providers running since 2019, is a good shape to copy. The platform already had 15+ charts covering different aspects of patient data, including a Sankey chart built from scratch in D3 for case-record analysis and a hybrid treatment tracker that combines a timeline for medicine intake with a line chart for test results. The AI/Big Data treatment recommendations were added alongside that, not on top of it. Access is routed by role and company through AWS Cognito, over a React/TypeScript/D3 front end and a NestJS, TypeORM and PostgreSQL back end. The EMR and the analytics platform can be used separately or together.

Three things that arrangement buys you:

  1. The chart carries the interpretive load. A clinician reading a treatment tracker they've used for years doesn't need a saliency map; they need the recommendation adjacent to the timeline they already know how to read.
  2. Scope is visible, not implied. Role- and company-based routing means "who else can see this" has a concrete answer in the same system that decides what's rendered.
  3. You can turn the AI surface off. If the recommendation layer is a separate panel, degrading it during an incident is a feature flag, not a rollback.

Nothing about accuracy, adoption or clinical validation is published for that platform, and I'm not claiming any. The point is structural: recommendation-not-replacement is a placement decision.

Look at the staffing too — 6 full-stack developers and 2 AI data scientists. That ratio is the honest shape of this work. Explainability in a data-heavy product is mostly product engineering, and treating it as a data-science deliverable is how it ends up as a SHAP plot nobody reads.

The cost is real: two surfaces means a second consistency model. When the deterministic figure and the AI panel disagree because they read at different times, you own that gap in the UI.

Decision history is the audit trail

An explanation you can't reconstruct next quarter isn't an explanation. It's a tooltip.

CYDEF, a Canadian cybersecurity company reviewing 100% of endpoint activity with a five-person team since 2020, ran into the workflow version of this. Threat processing was a long expert-driven sequence with no way back: analysts couldn't return to previous steps of thread processing, so the workflow was redesigned to retain history, with structured data in PostgreSQL and threat processing history in AWS Blob Storage. The volumes are the interesting part — hundreds of gigabytes of telemetry daily from client devices, with millions of messages received, processed and stored via Azure IoT Hub. Database indexing and caching, memory-leak tracking with alerting, and an internal device-monitoring tool came with it.

That history was built for analyst workflow, not for AI explainability. But it's the exact pattern an AI surface needs, and it generalizes:

  • Split the store by access pattern. Hot, indexed, queryable state for the last N days in your relational store; older inputs and intermediate artifacts in blob storage. At hundreds of GB/day you cannot keep everything hot, and you don't need to.
  • Persist prior outputs, not just current ones. "What did it say last month?" is the most common audit question and the one an overwrite makes unanswerable.
  • Keep the history query off the live path. Indexing and caching exist so that an analyst paging through last quarter doesn't degrade ingestion.
  • Monitor the ingest path itself. Without arrival monitoring you cannot separate "the model was wrong" from "the data never arrived" — and in my experience the second is far more common.

The EU is codifying this direction anyway: Article 12 requires high-risk systems to technically allow automatic recording of events over the system's lifetime, at a level appropriate for traceability. Retention costs money. Not being able to reconstruct a decision costs a renewal.

Explanations are testable artifacts

Here's the part most teams skip. If the explanation is generated by code — and it is, once you're citing record IDs — then it belongs in the test suite exactly like any other output.

A testable explanation is one where you can assert, without a human reading it, that: every cited record exists; every cited record belongs to the requesting tenant; the cited set actually produced the stated figure; and the freshness timestamp matches the newest record in that set.

test('explanation payload is consistent with the deterministic figure', async () => {

const { value, explanation } = await getInsight({ tenantId: 'acme', metric: 'scope3_q3' });

const rows = await repo.findByIds(explanation.sourceRecordIds);

expect(rows).toHaveLength(explanation.sourceRecordIds.length);   // no dangling citations

expect(rows.every(r => r.tenantId === 'acme')).toBe(true);       // no cross-tenant leak

expect(sum(rows.map(r => r.amount))).toBeCloseTo(value, 6);      // cites what it computed

expect(explanation.asOf).toEqual(maxBy(rows, 'receivedAt').receivedAt);

});

That test catches the three failures that actually reach customers: a stale ID set after a replay, a tenant leak from a bad join, and an explanation that drifted from the number it claims to explain.

You need the harness to make it routine. On the CYDEF engagement the team built over 1,500 test cases and over 700 automated tests, reaching 98% coverage of the desktop agents, with CI/CD extended across components and automated regression suites. (DeviQA's page on the same client states 1.9k+ test cases; take "over 1,500" as the conservative figure.)

Topology matters as much as count. On MINT, an Italian AdTech platform, delivery runs across 14 teams and up to 40 engineers, each team with at least one QA professional, independent sandboxes per team, a separate production-like UAT environment, and several releases per day. That engagement was QA and team scaling — MINT's own automation and its 16 channels and 350+ integrations as of 2023 are the client's product, not ours. Cite it for cadence and topology: per-team sandboxes and a shared UAT environment are what make explanation assertions runnable several times a day instead of quarterly.

The limit is worth being blunt about: coverage numbers describe effort, not defect escape rate. And you can test that an explanation is consistent. You cannot test that it's correct.

What it costs, and when SHAP is right

None of this is free:

  • Retention bills, and they scale with telemetry, not with revenue.
  • A second read path for history that has to stay off the hot path.
  • Slower iteration — changing a calculation now means versioning it, because old explanations must still resolve.
  • UI work to show uncertainty and staleness without turning a dashboard into a disclaimer.

And formal attribution genuinely is the right tool in three cases: adverse-decision regimes where you must explain a specific decision to the person it affected, model debugging when you need to know which features a model is leaning on, and bias audits across cohorts. If you're there, use SHAP, and use it in addition to the lineage, not instead of it.

The order I'd build in, on a product where customer data is the input: provenance at ingestion first, because you cannot retrofit it; the deterministic surface kept intact next, because it's the cheapest explanation available; decision history retained third, because audits arrive later than you plan for; and the explanation asserted in CI last, because that's what keeps the other three honest as the code changes. Then, only if your regulatory posture requires it, attach attribution on top — for the model, not for the answer.

Top comments (0)