Skip to content

Average metric becomes undefined after replacing rows in a transaction #300

Description

@dajiaohuang

Describe the bug

An existing avg metric becomes undefined after a transaction removes its only numeric row and adds a different numeric row. The final table is nonempty, and defining a second average over that same table returns the correct value.

Steps to Reproduce the Bug or Issue

import {createMetrics, createStore} from 'tinybase';

const store = createStore().setCell('t', 'old', 'n', 1);
const metrics = createMetrics(store).setMetricDefinition('avg', 't', 'avg', 'n');

store.transaction(() => {
  store.delRow('t', 'old');
  store.setCell('t', 'new', 'n', 2);
});

console.log(metrics.getMetric('avg')); // undefined
metrics.setMetricDefinition('fresh', 't', 'avg', 'n');
console.log(metrics.getMetric('fresh')); // 2
metrics.destroy();

Expected behavior

Both metrics should return 2 after the transaction has completed. Existing metric listeners should observe the final aggregate, not its disappearance.

Platform

  • Windows, Node.js v24.14.1
  • Reproduced after a fresh npm run compileForTest at main commit f09e5a3b74ea16b6fac93439be34cc3f954f1e7c (package version 9.7.0).

Additional context

The order matters: adding the new row before removing the old row works. Updating the existing row and replacing the table also work in the tested cases.

The incremental average removal divides by length - 1 when length is one. This produces a nonfinite intermediate value; later additions cannot recover it within the same batch, and Metrics exposes the result as undefined. Returning undefined from this removal shortcut would request the existing full-recalculation fallback over the final values.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions