---
id: SI0113
title: "Feature drift monitor"
url: https://carbium.sh/library/si/feature-drift-monitor
collection: AI and blockchain
category: ML classification
revision: 1
updated: 2026-11-23
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Feature drift monitor

Pull a program's last 1,000 signatures and the network's recent throughput samples, split each into a reference window and a current window, and print a PSI score per model input so you see drift before labels arrive.

## Why a classifier drifts

A classifier trained on one stretch of chain activity assumes the next rows look like the training rows. On Solana that assumption breaks with no change in your code. A program ships an update and its failure rate moves. A new router starts sending through it and the spacing between its transactions changes. Network load shifts with the hour. The model keeps answering with the same confidence on inputs it has never seen.

Accuracy shows the damage only once labels arrive, and for many chain tasks labels arrive late or never. Drift on the inputs shows it sooner and needs no labels. The check here compares two windows of one stream: the older rows are the reference, the newest rows are current.

The score is the population stability index, PSI. Each window is cut into bins over the same edges, and the score sums, over the bins, the difference between the two shares times the log of their ratio. Identical shares score 0 and the score grows as they separate. If your inputs are embeddings, [Streamed transaction embeddings](https://carbium.sh/library/si/streamed-transaction-embeddings) shows where those vectors come from; the test below applies to any numeric column you can bin.

## Three inputs from two reads

The monitor builds three numeric inputs from two calls. Both are read-only, run in parallel and settle on their own, so one failing leaves the other's lines on screen.

| Input | Read | A shift means |
|---|---|---|
| Slot gap between consecutive signatures | `getSignaturesForAddress` | the program's traffic bunches up or thins out |
| Failed flag, 1 when `err` is set | `getSignaturesForAddress` | the program's failure rate moved |
| Non-vote transactions per second | `getRecentPerformanceSamples` | whole-network load changed |

Signature rows come newest first, each with a `slot`, an `err` field and a `blockTime`. The gap is the slot difference to the next older row, and it is 0 when two transactions share a slot. The newest third of the rows is current and the older two thirds are the reference. The call asks for `confirmed` explicitly; @solana/kit would fill in the same value, but a monitor should say which level its rows come from.

A performance sample carries `numNonVoteTransactions` and `samplePeriodSecs`, so dividing one by the other gives a rate per second. Mainnet blocks carry no vote transactions since Alpenglow, so the non-vote count now tracks the raw count. The call asks for 720 samples, the most one call returns, and the reference and current windows are cut the same way, newest third against the rest.

The gap uses fixed bins at 1, 2, 4 and 8 slots, which suit a busy program: 0 means the same slot, and the top bin holds long silences. The failed flag has two bins. The network rate has no natural scale, so its bin edges are the reference window's quartiles.

## The monitor file

One file on @solana/kit 8.6.0 and Node 24, which strips the types when it loads. Set `CARBIUM_KEY` first; the file exits with a message when it is missing. `CARBIUM_RPC_URL` overrides the endpoint, which defaults to `https://services.carbium.sh`.

`main.ts` (run: `node main.ts`)

```ts
// SI0113 · Feature drift monitor
// https://carbium.sh/library/si/feature-drift-monitor
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Feature drift monitor: PSI between older and newest chain rows for three model inputs.
// Run: CARBIUM_KEY=... node main.ts [program-address]
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY to your Carbium API key.");
  process.exit(1);
}
const url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";
const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));
const program = address(process.argv[2] ?? "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4");

// Population stability index over shared bin edges; 0.5 is added to each bin so an empty bin keeps the log finite.
function psi(ref: number[], cur: number[], edges: number[]): number {
  const share = (xs: number[]) => {
    const bins: number[] = new Array(edges.length + 1).fill(0.5);
    for (const x of xs) bins[edges.filter((e) => x >= e).length]++;
    const total = bins.reduce((a, b) => a + b, 0);
    return bins.map((b) => b / total);
  };
  const p = share(ref);
  const q = share(cur);
  return p.reduce((sum, pv, i) => sum + (q[i] - pv) * Math.log(q[i] / pv), 0);
}

const quartiles = (xs: number[]) => {
  const s = [...xs].sort((a, b) => a - b);
  return [...new Set([0.25, 0.5, 0.75].map((f) => s[Math.floor(f * (s.length - 1))]))];
};
const mean = (xs: number[]) => xs.reduce((a, b) => a + b, 0) / xs.length;

// Rows arrive newest first: the newest third is current, the older two thirds are the reference.
function report(name: string, newestFirst: number[], edges?: number[]) {
  const cut = Math.floor(newestFirst.length / 3);
  const cur = newestFirst.slice(0, cut);
  const ref = newestFirst.slice(cut);
  if (cur.length < 30) throw new Error(`only ${newestFirst.length} rows, need 90 or more`);
  const p = psi(ref, cur, edges ?? quartiles(ref));
  const verdict = p < 0.1 ? "stable" : p < 0.25 ? "shifting" : "drifted";
  console.log(`${name.padEnd(16)} PSI ${p.toFixed(3)} ${verdict.padEnd(9)} mean ${mean(ref).toFixed(3)} -> ${mean(cur).toFixed(3)} (${ref.length} vs ${cur.length} rows)`);
}

function ok<T>(r: PromiseSettledResult<T>): T {
  if (r.status === "rejected") throw r.reason;
  return r.value;
}
function attempt(name: string, run: () => void) {
  try {
    run();
  } catch (e) {
    console.log(`${name.padEnd(16)} FAILED ${(e as Error).message}`);
  }
}

const [sigs, perf] = await Promise.allSettled([
  rpc.getSignaturesForAddress(program, { limit: 1000, commitment: "confirmed" }).send(),
  rpc.getRecentPerformanceSamples(720).send(),
]);

attempt("slot gap", () => {
  const rows = ok(sigs);
  report("slot gap", rows.slice(0, -1).map((r, i) => Number(r.slot - rows[i + 1].slot)), [1, 2, 4, 8]);
});
attempt("failed flag", () => report("failed flag", ok(sigs).map((r) => (r.err === null ? 0 : 1)), [1]));
attempt("network tx/s", () =>
  report("network tx/s", ok(perf).map((s) => Number(s.numNonVoteTransactions) / s.samplePeriodSecs)),
);
```

With no argument it watches a busy swap router program. Pass any program or token address as the first argument to watch that instead. Each output line gives the input, its PSI, a verdict word, the mean in the reference window and in the current one, and the row counts.

The `psi` function takes two arrays of numbers and a list of bin edges, so it works on any column you can pull from your own feature table, not only these three.

## Reading the score

The usual bands are below 0.1 stable, 0.1 to 0.25 shifting and above 0.25 drifted. They come from credit scoring practice and are conventions. Tune them on your own history of scores before you wire an alert to them.

Every bin gets 0.5 added before the shares are taken, so an empty bin keeps the logarithm finite. A small sample also scores above 0 with no real change. Expect a noise floor near the bin count minus one, times the sum of the two inverse sample sizes. With 666 reference rows, 333 current rows and five gap bins that is about 0.02. With 480 and 240 network samples in four bins it is about 0.02 as well. A score well above that floor means something.

- Gap PSI high, failed PSI low: the program is busier or quieter, and its outcomes look the same.
- Failed PSI high: an update, a changed route mix or a bad upstream is failing transactions that used to pass. Check what the classifier does with failed rows.
- Network PSI high with the program steady: the whole chain moved and your window sat across it. Compare against the program's own scores before blaming the model.

Two scores on the same address a few runs apart tell you more than one. A single reading jumps as the 1,000-row window slides, so alert when two in a row cross a band.

## Cost

A run makes one `getSignaturesForAddress` call at 50 cells and one `getRecentPerformanceSamples` call. The signatures call runs at 0.24 req/s on Free, 1.2 on Dev, 100 on Business and 500 on Pro, so a Free key can start one about every four seconds, far more often than a monitor needs.

[Limits](https://carbium.sh/docs/limits) are per account and an account's keys share one budget, so the monitor competes with whatever else uses it. A read refused for its rate prints FAILED on its own lines with the 429 message, and the other read still prints. Credits meter RPC work, so every run spends some on its two calls.

## Where it ends

- PSI measures movement of the inputs. It does not say the model got worse, and a drifted input can still be classified well. Pair it with labelled accuracy when labels exist.
- The reference is the older part of the same window, so a slow change across the whole window hides inside both halves. For that, store a baseline from a past run in `node:sqlite` and compare today's rows to it. The file keeps nothing between runs.
- One call returns at most 1,000 signatures. A busy program fills that in a short span, so current may mean a few minutes. A quiet program may span days, and the address index behind [signature history](https://carbium.sh/docs/migrate) stops at 30 days. [Signature history pagination](https://carbium.sh/library/howsolana/signature-history-pagination) pages further back inside that limit.
- Signatures at confirmed include failed transactions, which is why the failed flag works, but a slot can still be dropped after it is listed.
- Three inputs are a demonstration. A production classifier has dozens of columns, and a score per column with a count of how many crossed 0.25 is the usual summary.
- The gap in slots is a proxy for time. After the Alpenglow switch a slot is about 200 ms, so a gap of 8 slots is around 1.6 seconds.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| All three lines print FAILED with a 401 message. | The key is unknown at the door. Attach the whole key in `CARBIUM_KEY`, with no truncation and no quotes left in the value. |
| A line prints FAILED with 'only 40 rows, need 90 or more'. | The address is too quiet for a three-way split. Pass a busier program, or lower the minimum in `report` and accept a noisier score. |
| One read prints FAILED with a 429 message. | Wait for the retry-after hint and rerun. Other keys on the account spend the same budget, so check what else is running. |
| The failed flag line shows mean 0.000 -> 0.000 on every run. | The program had no failures in either window, so there is nothing to compare. Read its slot gap line instead, or watch an address with a mixed outcome history. |
| The score on one address swings between 0.03 and 0.2 across consecutive runs. | The 1,000-row window slides as new transactions land, and a short window gives a wide noise band. Alert on two readings in a row, or compare against a stored baseline. |
| The network line reads drifted while the program looks steady. | The 720 samples cover many hours and network load follows the hour. Compare against the same span on an earlier day, or bin the samples by hour before scoring. |

## Questions

### Can I run this on my own model's columns?

Yes. `psi(ref, cur, edges)` takes plain number arrays. Build the edges from the reference column, as `quartiles` does, then reuse them for the current window and for every later run.

### Why PSI and not a Kolmogorov-Smirnov test?

The Kolmogorov-Smirnov test suits a continuous column and gives a p-value, which grows over-sensitive with thousands of rows. PSI is one score with bands that are easy to alert on, and it handles flags and counts the same way.

### Why confirmed for the signature read?

Monitoring wants a recent view that a slot drop rarely reverses, and finalized sits 0 to 1 slots behind processed since Alpenglow, so the levels sit close. Change `commitment` to `finalized` if the input must never revert.

### How do I keep a baseline between runs?

Write the reference bin shares to a `node:sqlite` table keyed by input name and date, then load them instead of splitting the live window. Keep the edges with the shares so the next run bins the same way.

## Related

- [Streamed transaction embeddings](https://carbium.sh/library/si/streamed-transaction-embeddings) (AI and blockchain, SI0073)
- [Signature history pagination](https://carbium.sh/library/howsolana/signature-history-pagination) (How to use Solana, HS0034)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/migrate](https://carbium.sh/docs/migrate)
- [carbium.sh/docs/errors](https://carbium.sh/docs/errors)
