feat(engagement): retention — three sweeps and one recorded refusal
All checks were successful
PR Checks / client-build (pull_request) Successful in 34s
PR Checks / bot-tests (pull_request) Successful in 34s
PR Checks / server-tests (pull_request) Successful in 13m23s

ENGAGEMENT.md Phase 14, the last phase of the workstream. Four engagement
tables grew on every fire and nothing had ever deleted from any of them.

Three of them now have a horizon, swept nightly by one worker
(utils/engagementRetentionPrune.js — setInterval + unref + stop(), batched
1000 x 50, each table's failure caught on its own so a lock timeout on one
does not leave the other two unbounded):

  engagement_sends      180 days   engagement_sends_retain_days      (7-3650)
  engagement_cooldowns   30 days   engagement_cooldowns_retain_days  (2-3650)
  engagement_outbox      30 days   engagement_outbox_retain_days     (2-3650)

The fourth, engagement_suppressions, does not expire, and that is the
recorded decision rather than an omission: a suppression is a standing
decision, and ageing out a hard bounce re-mails an address that already
bounced. The way out stays deliberate, and is now reachable per row.

Six decisions were settled by the org lead before any code. Two of them
widened the phase past what was offered:

  * the send-log horizon is admin-configurable, so retention got a SCREEN
    (Admin -> Engagement -> Retention) where team_activity and
    user_notifications keep theirs in invisible settings rows. The send-log
    horizon changes what an operator-facing page is able to show, so it has
    to be visible; the other two came with it, because "what does this
    deployment keep" is one question.
  * the suppression purge, which cost a Phase 9 decision. The list
    deliberately stripped address_hash from every row, so the only way out
    was a window.prompt asking the operator to retype an address the screen
    has never shown them. The row had no handle at all. The hash is now
    returned: this route is admin-only and an admin can already suppress and
    unsuppress any address they can name, so it grants no capability they
    lack. GET /sends still strips its own.

The outbox sweep is TERMINAL-ONLY and that is a correctness rule: a
scheduled row is a send this deployment still intends to make (delay_seconds
can put one a day out) and a sending row may be mid-flight.

One shipped defect had to be fixed for the sweep to be a bound at all.
reclaimStale returned every stale sending row to scheduled, and MAX_ATTEMPTS
is consulted only on a graceful retry outcome — so a send that killed the
process mid-flight cycled sending -> scheduled -> sending forever, never
terminal, therefore never eligible for any sweep. It now fails an exhausted
row BEFORE reclaiming the rest; the order is the fix.

Two indexes (idx_engo_sweep, idx_engs_sweep): every existing index on those
tables has created_at in second position, which serves a per-rule window and
is useless to a whole-table horizon.

Proved twice: engagementRetentionSql.test.js against a real MariaDB (7
tests, incl. the acceptance case and the wrong reclaim order run
deliberately), and the live stack, where a 90-day-old cancelled row was
swept and a 90-day-old scheduled row survived.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-09-01 15:40:53 -05:00
parent e59a68c152
commit 5779d15150
22 changed files with 1728 additions and 17 deletions

View File

@@ -78,8 +78,23 @@ const get = async (ruleId, userId, subjectKey, channel) => {
* failure `teamActivityPrune` was written for. A dropped row means the next fire
* is treated as a first fire, which is correct as long as the retention window is
* longer than the longest configured cooldown - the caller's job, not this one's.
* Phase 14 gave it that caller (`engagementRetentionPrune`), which also enforces
* the horizon-versus-longest-cooldown rule this comment names.
*
* `limit` bounds one statement, for `userNotificationsPrune`'s reason: a first
* sweep after a long outage must be a series of bounded DELETEs rather than one
* that holds locks over a million rows. Omitting it keeps the original
* unbounded behaviour, so existing callers and tests are unaffected.
*
* @returns {Promise<number>} rows deleted
*/
const prune = (olderThan) =>
query('DELETE FROM engagement_cooldowns WHERE last_fired_at < ?', [olderThan])
const prune = async (olderThan, limit = 0) => {
const bounded = Number(limit) > 0
const result = await query(
`DELETE FROM engagement_cooldowns WHERE last_fired_at < ?${bounded ? ' LIMIT ?' : ''}`,
bounded ? [olderThan, Math.floor(limit)] : [olderThan],
)
return Number(result?.affectedRows || 0)
}
module.exports = { claim, get, prune }

View File

@@ -132,11 +132,61 @@ async function cancel(ruleId, subjectKey, userId = null) {
* stamped it), and the window has to be comfortably longer than the slowest
* legitimate send or this reclaims rows that are merely slow.
*/
const reclaimStale = (before) =>
query(
const reclaimStale = async (before, maxAttempts = 0) => {
// Give up first, reclaim second, and in that order: a row that has already
// burned its attempts must leave 'sending' as `failed`, or the reclaim below
// hands it straight back to `findDue` and it is retried forever.
//
// **This is what makes `pruneTerminal` a bound at all** (Phase 14). Attempts
// are incremented by `claim`, but `MAX_ATTEMPTS` is only consulted on a
// graceful `retry` outcome — a send that kills the process mid-flight never
// reaches that branch, so before this the row cycled sending → scheduled →
// sending forever, never reached a terminal status, and was therefore never
// eligible for any retention sweep. One poisoned payload was an outbox row
// that outlived every horizon.
let failed = 0
if (Number(maxAttempts) > 0) {
const gaveUp = await query(
`UPDATE engagement_outbox
SET status = 'failed', last_error = 'gave up after repeated interruptions'
WHERE status = 'sending' AND updated_at < ? AND attempts >= ?`,
[before, Math.floor(maxAttempts)],
)
failed = Number(gaveUp?.affectedRows || 0)
}
const reclaimed = await query(
"UPDATE engagement_outbox SET status = 'scheduled' WHERE status = 'sending' AND updated_at < ?",
[before],
)
return { failed, reclaimed: Number(reclaimed?.affectedRows || 0) }
}
/**
* Delete terminal rows older than `before` (Phase 14).
*
* **Terminal only, and the status list is the whole policy.** A `scheduled` row
* is a promise the engine has not kept yet — `delay_seconds` can legitimately
* put one up to a day out (`MAX_DELAY_SECONDS`) — and a `sending` row may be a
* worker mid-flight. Deleting either is not retention, it is cancelling a send
* nobody asked to cancel. Only `sent`, `failed`, `cancelled` and `suppressed`
* are outcomes that have already happened.
*
* `created_at` rather than `updated_at` is the clock deliberately: the horizon
* an operator sets means "how long we keep the record of a delivery", which is
* measured from when it was enqueued, not from whenever it was last touched.
*
* @returns {Promise<number>} rows deleted
*/
const pruneTerminal = async (before, limit = 1000) => {
const result = await query(
`DELETE FROM engagement_outbox
WHERE status IN ('sent', 'failed', 'cancelled', 'suppressed')
AND created_at < ?
LIMIT ?`,
[before, Math.floor(limit)],
)
return Number(result?.affectedRows || 0)
}
const getById = async (id) => {
const [row] = await query('SELECT * FROM engagement_outbox WHERE id = ?', [id])
@@ -157,6 +207,7 @@ module.exports = {
finish,
cancel,
reclaimStale,
pruneTerminal,
getById,
listForRule,
}

View File

@@ -0,0 +1,175 @@
// ── Engagement retention policy ────────────────────────────────────────────
//
// ENGAGEMENT.md Phase 14. Three horizons, one place to read and write them, so
// the nightly worker and Admin → Engagement → Retention cannot disagree about
// what this deployment keeps — and so `/privacy` has one thing to describe.
//
// **The fourth engagement table is deliberately absent from this file.**
// `engagement_suppressions` does not expire (org lead, 2026-09-01): a
// suppression is a standing decision, and ageing out a hard bounce re-mails an
// address that already bounced, which is how a sender loses a domain's
// reputation. The one way out of that table stays what Phase 9 built — a
// deliberate act by an admin, which Phase 14 only made reachable per row.
//
// Settings rows rather than env, for `teamActivityPrune`'s reason: an operator
// tightening a busy shard should not need a deploy. Unlike the two workers this
// copies, these three get a screen — the send log's horizon changes what an
// operator-facing page can show, so it cannot be an invisible key.
const settings = require('../settings/settings.model')
const rulesDb = require('./engagementRules.db')
const log = require('../../utils/logger')('engagement')
/**
* One entry per horizon. `min` is not a UI nicety — each is the point below
* which the sweep breaks something that is not retention:
*
* - **cooldowns**: a pruned row makes the next fire a FIRST fire, i.e. a
* duplicate send. `MAX_COOLDOWN_SECONDS` is a validated 86 400 (one day), so
* 2 days is the smallest provably-safe value against any rule that can be
* saved. `checkCooldownHorizon` re-checks it against the rules that exist.
* - **outbox**: `MAX_DELAY_SECONDS` is also 86 400, so no `scheduled` row is
* ever more than a day out; terminal rows younger than that are still the
* most recent thing an operator would look at.
* - **sends**: the per-rule hourly ceiling (§7.1 Q3) counts this table, so a
* horizon under an hour would silently disable it. The floor is set far
* above that, at the point the Send Log stops being worth opening.
*/
const HORIZONS = {
sends: {
key: 'engagement_sends_retain_days',
default: 180,
min: 7,
max: 3650,
label: 'Send log',
},
cooldowns: {
key: 'engagement_cooldowns_retain_days',
default: 30,
min: 2,
max: 3650,
label: 'Cooldowns',
},
outbox: {
key: 'engagement_outbox_retain_days',
default: 30,
min: 2,
max: 3650,
label: 'Outbox',
},
}
const NAMES = Object.keys(HORIZONS)
/**
* The current policy, as `{ sends, cooldowns, outbox }` in days.
*
* Wrapped in a try like `teamActivity.retentionConfig` and for its reason: the
* nightly worker calls this with nobody watching, so a settings table that is
* briefly unavailable must yield defaults rather than an exception that kills
* the job. An unreadable, absent, non-numeric or out-of-range value all mean
* the same thing — use the default — because none of them is a horizon.
*/
async function get() {
const out = {}
for (const name of NAMES) {
const spec = HORIZONS[name]
let days = spec.default
try {
const raw = await settings.get(spec.key)
const n = Number(raw)
if (Number.isFinite(n) && n >= spec.min && n <= spec.max) days = Math.floor(n)
} catch (err) {
log.debug('retention setting unreadable; using the default', {
key: spec.key,
message: err.message,
})
}
out[name] = days
}
return out
}
/**
* Write one or more horizons. Unknown names are ignored rather than rejected, so
* a client sending the whole object back is not coupled to this list; an
* out-of-range value IS rejected, because silently clamping a number an operator
* typed would leave the screen showing something the deployment is not doing.
*
* @returns {Promise<object>} the policy as it now stands
*/
async function set(patch = {}, updatedBy = null) {
for (const name of NAMES) {
if (!(name in patch) || patch[name] === undefined || patch[name] === null) continue
const spec = HORIZONS[name]
const n = Number(patch[name])
if (!Number.isFinite(n) || Math.floor(n) !== n) {
throw Object.assign(new Error(`${spec.label} retention must be a whole number of days`), {
status: 400,
})
}
if (n < spec.min || n > spec.max) {
throw Object.assign(
new Error(`${spec.label} retention must be between ${spec.min} and ${spec.max} days`),
{ status: 400 },
)
}
await settings.set(spec.key, String(n), updatedBy)
}
return get()
}
/**
* The longest cooldown any ENABLED rule configures, in seconds — see
* `engagementRules.db.maxEnabledCooldownSeconds` for why enabled only.
*
* Swallows its error rather than propagating: this is consulted by a worker
* running on a timer, and a database hiccup must degrade the WARNING, never the
* sweep. Zero reads as "no enabled rule has a cooldown", which produces no
* warning — the same answer as an unreadable table, and the safe one, because
* the alternative is a nightly alarm nobody can act on.
*/
async function longestEnabledCooldownSeconds() {
try {
return await rulesDb.maxEnabledCooldownSeconds()
} catch (err) {
log.debug('could not read the longest enabled cooldown', { message: err.message })
return 0
}
}
/**
* Phase 14's acceptance line: the cooldown horizon is CHECKED against the
* longest enabled rule's cooldown rather than picked.
*
* It returns a warning rather than throwing, and the worker sweeps anyway. The
* alternative — refusing to prune — trades a bounded, describable fault (one
* rule may re-fire early once) for the unbounded one this phase exists to end.
* The screen surfaces the same warning, which is where an operator can act on it.
*
* @returns {Promise<{ ok: boolean, longestCooldownSeconds: number, message: string|null }>}
*/
async function checkCooldownHorizon(days) {
const longest = await longestEnabledCooldownSeconds()
const horizonSeconds = days * 24 * 60 * 60
if (longest > 0 && horizonSeconds <= longest) {
return {
ok: false,
longestCooldownSeconds: longest,
message:
`Cooldown retention is ${days} day(s), but an enabled rule has a cooldown of `
+ `${longest} second(s). Pruning a cooldown row that is still in force makes the next `
+ 'fire count as a first fire, so that rule can send twice. Raise the horizon.',
}
}
return { ok: true, longestCooldownSeconds: longest, message: null }
}
module.exports = {
HORIZONS,
NAMES,
get,
set,
longestEnabledCooldownSeconds,
checkCooldownHorizon,
}

View File

@@ -135,9 +135,25 @@ const countUsingSegment = async (segmentId) => {
return Number(row?.n || 0)
}
/**
* The longest cooldown any ENABLED rule configures, in seconds (Phase 14).
*
* Enabled only, deliberately: a disabled rule fires nothing, so it writes no
* cooldown row a retention sweep could destroy, and letting a forgotten disabled
* rule with a 24-hour cooldown veto a tighter horizon would make the warning
* advice nobody can act on.
*/
const maxEnabledCooldownSeconds = async () => {
const [row] = await query(
'SELECT MAX(cooldown_seconds) AS n FROM engagement_rules WHERE enabled = 1',
)
return Number(row?.n || 0)
}
module.exports = {
list,
getById,
maxEnabledCooldownSeconds,
enabledForTrigger,
enabledCancelledBy,
insert,

View File

@@ -107,4 +107,26 @@ const count = async (opts = {}) => {
return Number(row?.n || 0)
}
module.exports = { record, countSentSince, list, count, TEST_SEND_TRIGGER }
/**
* Delete send-log rows older than `before` (Phase 14).
*
* **Every row here is terminal**, which is why this has no status filter and the
* outbox's sweep does: `engagement_sends` records an attempt that has already
* resolved. The care is entirely in the horizon, because this table has two live
* readers and they pull in opposite directions — `countSentSince` implements the
* per-rule hourly ceiling (§7.1 Q3), so any horizon under an hour silently
* disables that ceiling, and Admin -> Engagement -> Send Log is the operator's
* only answer to "was this person told", so a short one blinds it. Both are the
* caller's problem, and `engagementRetention` is where that judgement lives.
*
* @returns {Promise<number>} rows deleted
*/
const prune = async (before, limit = 1000) => {
const result = await query('DELETE FROM engagement_sends WHERE created_at < ? LIMIT ?', [
before,
Math.floor(limit),
])
return Number(result?.affectedRows || 0)
}
module.exports = { record, countSentSince, list, count, prune, TEST_SEND_TRIGGER }