@hogsend/engine 0.59.0 → 0.61.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +11 -11
- package/src/buckets/bucket-access.ts +34 -11
- package/src/buckets/check-membership.ts +74 -10
- package/src/buckets/membership-epoch.ts +11 -1
- package/src/campaigns/cohort-sql.ts +10 -0
- package/src/index.ts +10 -6
- package/src/journeys/execute-journey-run.ts +139 -70
- package/src/journeys/journey-context.ts +43 -7
- package/src/lib/agent/tools.ts +29 -4
- package/src/lib/attribution-backfill.ts +35 -4
- package/src/lib/attribution.ts +22 -3
- package/src/lib/connector-actions.ts +17 -17
- package/src/lib/contacts.ts +541 -175
- package/src/lib/conversion-dispatch.ts +16 -2
- package/src/lib/enrollment-guards.ts +19 -12
- package/src/lib/feed.ts +5 -5
- package/src/lib/flags.ts +26 -9
- package/src/lib/ingestion.ts +14 -2
- package/src/lib/journey-lift.ts +17 -5
- package/src/lib/preferences.ts +78 -29
- package/src/lib/recipient-preferences.ts +16 -2
- package/src/lib/refine.ts +16 -10
- package/src/lib/revenue.ts +20 -5
- package/src/lib/sms-inbound.ts +6 -1
- package/src/lib/sms-tracked.ts +18 -1
- package/src/lib/timezone.ts +11 -1
- package/src/lib/tracked.ts +19 -8
- package/src/lib/tracking-events.ts +28 -0
- package/src/lib/unique-violation.ts +44 -0
- package/src/routes/admin/buckets.ts +21 -1
- package/src/routes/admin/bulk.ts +14 -2
- package/src/routes/admin/contacts.ts +20 -7
- package/src/routes/admin/conversions.ts +20 -4
- package/src/routes/admin/emails.ts +17 -2
- package/src/routes/admin/events.ts +32 -41
- package/src/routes/admin/funnels.ts +6 -1
- package/src/routes/admin/groups.ts +4 -0
- package/src/routes/admin/impact.ts +30 -10
- package/src/routes/admin/journey-impact.ts +18 -9
- package/src/routes/admin/journeys.ts +8 -1
- package/src/routes/admin/maintenance.ts +7 -1
- package/src/routes/admin/preferences.ts +85 -46
- package/src/routes/admin/reporting.ts +25 -5
- package/src/routes/admin/targeting.ts +1 -0
- package/src/routes/admin/timeline.ts +16 -10
- package/src/routes/email/preferences.ts +18 -1
- package/src/routes/feed/recipient.ts +5 -0
- package/src/routes/lists/index.ts +6 -6
- package/src/workflows/backfill-contact-id.ts +210 -30
- package/src/workflows/bucket-backfill.ts +145 -67
- package/src/workflows/bucket-reconcile.ts +164 -51
- package/src/workflows/check-alerts.ts +4 -0
- package/src/workflows/impact-digest.ts +10 -3
- package/src/workflows/journey-blueprint-interpreter.ts +8 -1
- package/src/workflows/send-campaign.ts +18 -11
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Conditions } from "@hatchet-dev/typescript-sdk/v1/index.js";
|
|
2
2
|
import type { JsonValue } from "@hatchet-dev/typescript-sdk/v1/types.js";
|
|
3
|
-
import { type DurationObject, durationToMs } from "@hogsend/core";
|
|
3
|
+
import { bySubject, type DurationObject, durationToMs } from "@hogsend/core";
|
|
4
4
|
import type {
|
|
5
5
|
JourneyMeta,
|
|
6
6
|
JourneyRunFn,
|
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
journeyConfigs,
|
|
13
13
|
journeyStates,
|
|
14
14
|
} from "@hogsend/db";
|
|
15
|
-
import { and, eq, inArray, isNull, notInArray,
|
|
15
|
+
import { and, eq, inArray, isNull, notInArray, sql } from "drizzle-orm";
|
|
16
16
|
import { getAnalytics } from "../lib/analytics-singleton.js";
|
|
17
17
|
import { blueprintGraphLock } from "../lib/blueprint-lock.js";
|
|
18
18
|
import { ALL_IDENTITY_KINDS, lookupContactIdByKey } from "../lib/contacts.js";
|
|
@@ -28,6 +28,10 @@ import { ingestEvent } from "../lib/ingestion.js";
|
|
|
28
28
|
import { createLogger } from "../lib/logger.js";
|
|
29
29
|
import { emitOutbound } from "../lib/outbound.js";
|
|
30
30
|
import { resolveTimezoneWithSource } from "../lib/timezone.js";
|
|
31
|
+
import {
|
|
32
|
+
isUniqueViolationOn,
|
|
33
|
+
UQ_CONTACT_JOURNEY_ACTIVE,
|
|
34
|
+
} from "../lib/unique-violation.js";
|
|
31
35
|
import { getClientScheduleDefaults } from "./client-defaults-singleton.js";
|
|
32
36
|
import { JourneyExitedError } from "./errors.js";
|
|
33
37
|
import {
|
|
@@ -171,6 +175,17 @@ async function resolveEnrollmentContactId(opts: {
|
|
|
171
175
|
* CONFLICT specification") at runtime. The `where` reproduces the index
|
|
172
176
|
* predicate (`status IN ('active','waiting')`) EXACTLY — see
|
|
173
177
|
* journey-states.ts:uq_user_journey_active.
|
|
178
|
+
*
|
|
179
|
+
* PRD 05 T3 — the arbiter deliberately STAYS on the string key. The second live
|
|
180
|
+
* index, `uq_contact_journey_active`, cannot be an arbiter here: drizzle's
|
|
181
|
+
* `target` accepts columns only (no expression), and a bare
|
|
182
|
+
* `(contact_id, journey_id)` target would never fire for a NULL `contact_id` —
|
|
183
|
+
* i.e. for every anonymous visitor, a permanent supported state — so an
|
|
184
|
+
* anonymous re-trigger of a live journey would insert a second row and die on
|
|
185
|
+
* the string index. Instead its 23505 is caught below and mapped to the SAME
|
|
186
|
+
* zero-rows outcome, which the caller reads as `already_active`. That is the
|
|
187
|
+
* correct answer: the contact IS already live in this journey, under a different
|
|
188
|
+
* string key that adoption has since folded onto the same contact.
|
|
174
189
|
*/
|
|
175
190
|
export async function insertEnrollment(opts: {
|
|
176
191
|
db: Database;
|
|
@@ -224,24 +239,39 @@ export async function insertEnrollment(opts: {
|
|
|
224
239
|
where: sql`status IN ('active', 'waiting')`,
|
|
225
240
|
};
|
|
226
241
|
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
.
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
242
|
+
try {
|
|
243
|
+
if (!opts.serializeWithGraphLock) {
|
|
244
|
+
const [row] = await opts.db
|
|
245
|
+
.insert(journeyStates)
|
|
246
|
+
.values(values)
|
|
247
|
+
.onConflictDoNothing(onConflict)
|
|
248
|
+
.returning();
|
|
249
|
+
return row;
|
|
250
|
+
}
|
|
235
251
|
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
.
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
252
|
+
// `await` (not a bare return) so a 23505 raised inside the transaction is
|
|
253
|
+
// caught HERE, after the transaction has already rolled back.
|
|
254
|
+
return await opts.db.transaction(async (tx) => {
|
|
255
|
+
await tx.execute(blueprintGraphLock(opts.journeyId));
|
|
256
|
+
const [row] = await tx
|
|
257
|
+
.insert(journeyStates)
|
|
258
|
+
.values(values)
|
|
259
|
+
.onConflictDoNothing(onConflict)
|
|
260
|
+
.returning();
|
|
261
|
+
return row;
|
|
262
|
+
});
|
|
263
|
+
} catch (err) {
|
|
264
|
+
if (!isUniqueViolationOn(err, UQ_CONTACT_JOURNEY_ACTIVE)) throw err;
|
|
265
|
+
// Same contact, DIFFERENT string key, already live in this journey. Zero
|
|
266
|
+
// rows is exactly what the string arbiter returns for the same situation,
|
|
267
|
+
// and the caller maps it to the `already_active` skip.
|
|
268
|
+
logger.info("journey enrollment skipped — contact already live", {
|
|
269
|
+
journeyId: opts.journeyId,
|
|
270
|
+
userId: opts.userId,
|
|
271
|
+
contactId: opts.contactId ?? null,
|
|
272
|
+
});
|
|
273
|
+
return undefined;
|
|
274
|
+
}
|
|
245
275
|
}
|
|
246
276
|
|
|
247
277
|
export interface ExecuteJourneyRunOptions {
|
|
@@ -335,6 +365,26 @@ export async function executeJourneyRun(
|
|
|
335
365
|
|
|
336
366
|
let state = recovered;
|
|
337
367
|
|
|
368
|
+
// The subject this run's ENTRY reads and writes history for, resolved AT MOST
|
|
369
|
+
// ONCE. PRD 05 T4 moved the entry guards off the mutable `user_id` string and
|
|
370
|
+
// onto `bySubject`, so the guards now need the same value the enrollment
|
|
371
|
+
// insert already stamped — memoizing it keeps that at one resolve per run
|
|
372
|
+
// rather than one per reader (`undefined` = not yet resolved; `null` = a
|
|
373
|
+
// resolved-to-nothing subject, which is a permanent supported state and must
|
|
374
|
+
// not re-probe).
|
|
375
|
+
let resolvedContactId: string | null | undefined;
|
|
376
|
+
const enrollmentContactId = async (): Promise<string | null> => {
|
|
377
|
+
if (resolvedContactId === undefined) {
|
|
378
|
+
resolvedContactId = await resolveEnrollmentContactId({
|
|
379
|
+
db,
|
|
380
|
+
userId,
|
|
381
|
+
journeyId: meta.id,
|
|
382
|
+
pushed: input.contactId,
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
return resolvedContactId;
|
|
386
|
+
};
|
|
387
|
+
|
|
338
388
|
// FIRST ENTRY ONLY — the enrollment guards gate ENTRY, not resume. A
|
|
339
389
|
// recovered enrollment already passed them on first entry, so it skips
|
|
340
390
|
// straight to resuming the run. (Sends inside `run` still re-check
|
|
@@ -364,6 +414,7 @@ export async function executeJourneyRun(
|
|
|
364
414
|
db,
|
|
365
415
|
journey: meta,
|
|
366
416
|
userId,
|
|
417
|
+
contactId: await enrollmentContactId(),
|
|
367
418
|
});
|
|
368
419
|
const entryPolicy = evaluateEnrollmentPolicy({
|
|
369
420
|
journey: meta,
|
|
@@ -374,7 +425,11 @@ export async function executeJourneyRun(
|
|
|
374
425
|
return { status: "skipped", reason: entryPolicy.reason };
|
|
375
426
|
}
|
|
376
427
|
|
|
377
|
-
const prefs = await checkEmailPreferences({
|
|
428
|
+
const prefs = await checkEmailPreferences({
|
|
429
|
+
db,
|
|
430
|
+
userId,
|
|
431
|
+
contactId: await enrollmentContactId(),
|
|
432
|
+
});
|
|
378
433
|
const preferencePolicy = evaluateEnrollmentPolicy({
|
|
379
434
|
journey: meta,
|
|
380
435
|
properties,
|
|
@@ -407,26 +462,23 @@ export async function executeJourneyRun(
|
|
|
407
462
|
if (!holdoutPolicy.allowed) {
|
|
408
463
|
const priorHoldout = await db.query.journeyStates.findFirst({
|
|
409
464
|
where: and(
|
|
410
|
-
|
|
465
|
+
bySubject(journeyStates, {
|
|
466
|
+
contactId: await enrollmentContactId(),
|
|
467
|
+
userKey: userId,
|
|
468
|
+
}),
|
|
411
469
|
eq(journeyStates.journeyId, meta.id),
|
|
412
470
|
eq(journeyStates.status, "held_out"),
|
|
413
471
|
),
|
|
414
472
|
});
|
|
415
473
|
if (!priorHoldout) {
|
|
416
474
|
const heldOutAt = new Date();
|
|
417
|
-
// PRD 04 dual-write
|
|
418
|
-
//
|
|
419
|
-
//
|
|
420
|
-
//
|
|
421
|
-
// control-flow change to the
|
|
422
|
-
//
|
|
423
|
-
|
|
424
|
-
const heldOutContactId = await resolveEnrollmentContactId({
|
|
425
|
-
db,
|
|
426
|
-
userId,
|
|
427
|
-
journeyId: meta.id,
|
|
428
|
-
pushed: input.contactId,
|
|
429
|
-
});
|
|
475
|
+
// PRD 04 dual-write, via the run-scoped memo the guard above already
|
|
476
|
+
// paid for (identical arguments, so identical value). Deliberately
|
|
477
|
+
// NOT the `subjectContactId` compute below: that one lives INSIDE the
|
|
478
|
+
// ingest try/catch, and hoisting it would change which failures skip
|
|
479
|
+
// the `journey.heldout` re-emit — a control-flow change to the
|
|
480
|
+
// identity-provenance path, made for bookkeeping.
|
|
481
|
+
const heldOutContactId = await enrollmentContactId();
|
|
430
482
|
const inserted = await db
|
|
431
483
|
.insert(journeyStates)
|
|
432
484
|
.values({
|
|
@@ -474,25 +526,16 @@ export async function executeJourneyRun(
|
|
|
474
526
|
// real contact, or one asserting an email, must keep creating.
|
|
475
527
|
// This leg runs BEFORE the timezone `contact` fetch below, so
|
|
476
528
|
// provenance is resolved locally: the pushed `input.contactId`
|
|
477
|
-
// when the entry ingest resolved a row
|
|
478
|
-
//
|
|
479
|
-
//
|
|
480
|
-
//
|
|
481
|
-
//
|
|
529
|
+
// when the entry ingest resolved a row (that precedence is
|
|
530
|
+
// unchanged), else the alias-aware lookup for the live contact
|
|
531
|
+
// owning this canonical key — every column form
|
|
532
|
+
// (`external_id ?? anonymous_id ?? id`) plus the identity table,
|
|
533
|
+
// so a merged-away key pins the SURVIVOR rather than resolving
|
|
534
|
+
// nothing.
|
|
482
535
|
const subjectContactId =
|
|
483
536
|
input.contactId ??
|
|
484
|
-
(
|
|
485
|
-
|
|
486
|
-
where: and(
|
|
487
|
-
isNull(contacts.deletedAt),
|
|
488
|
-
or(
|
|
489
|
-
eq(contacts.externalId, userId),
|
|
490
|
-
eq(contacts.anonymousId, userId),
|
|
491
|
-
),
|
|
492
|
-
),
|
|
493
|
-
columns: { id: true },
|
|
494
|
-
})
|
|
495
|
-
)?.id;
|
|
537
|
+
(await lookupContactIdByKey(db, userId)) ??
|
|
538
|
+
undefined;
|
|
496
539
|
await ingestEvent({
|
|
497
540
|
db,
|
|
498
541
|
registry: getJourneyRegistrySingleton(),
|
|
@@ -560,7 +603,10 @@ export async function executeJourneyRun(
|
|
|
560
603
|
|
|
561
604
|
const activeState = await db.query.journeyStates.findFirst({
|
|
562
605
|
where: and(
|
|
563
|
-
|
|
606
|
+
bySubject(journeyStates, {
|
|
607
|
+
contactId: await enrollmentContactId(),
|
|
608
|
+
userKey: userId,
|
|
609
|
+
}),
|
|
564
610
|
eq(journeyStates.journeyId, meta.id),
|
|
565
611
|
inArray(journeyStates.status, ["active", "waiting"]),
|
|
566
612
|
),
|
|
@@ -574,6 +620,21 @@ export async function executeJourneyRun(
|
|
|
574
620
|
return { status: "skipped", reason: activePolicy.reason };
|
|
575
621
|
}
|
|
576
622
|
|
|
623
|
+
// PRD 04 dual-write — the pushed pin when ingest resolved one, else one
|
|
624
|
+
// D6-wrapped probe. NULL (unknown subject / refused resolve) is a legal
|
|
625
|
+
// stamp: the enrollment proceeds exactly as before. Resolved FRESH here
|
|
626
|
+
// (not via the guard-time memo): the guard chain is long enough for a
|
|
627
|
+
// concurrent identify to mint the subject's contact mid-window, and a
|
|
628
|
+
// stale NULL stamp on the insert would sit outside the contact-scoped
|
|
629
|
+
// unique index that backstops double-enrollment. The memo cache is
|
|
630
|
+
// refreshed with the result so later readers agree with the stamp.
|
|
631
|
+
resolvedContactId = await resolveEnrollmentContactId({
|
|
632
|
+
db,
|
|
633
|
+
userId,
|
|
634
|
+
journeyId: meta.id,
|
|
635
|
+
pushed: input.contactId,
|
|
636
|
+
});
|
|
637
|
+
|
|
577
638
|
// A successful insert always returns exactly one row, so undefined here
|
|
578
639
|
// can ONLY mean a burst-race conflict (see insertEnrollment's doc for
|
|
579
640
|
// the race + arbiter mechanics) — the same outcome as the read guard,
|
|
@@ -592,15 +653,7 @@ export async function executeJourneyRun(
|
|
|
592
653
|
hatchetRunId: workflowRunId,
|
|
593
654
|
journeyVersionHash: meta.versionHash ?? null,
|
|
594
655
|
journeyVersionLabel: meta.version ?? null,
|
|
595
|
-
|
|
596
|
-
// D6-wrapped probe. NULL (unknown subject / refused resolve) is a legal
|
|
597
|
-
// stamp: the enrollment proceeds exactly as before.
|
|
598
|
-
contactId: await resolveEnrollmentContactId({
|
|
599
|
-
db,
|
|
600
|
-
userId,
|
|
601
|
-
journeyId: meta.id,
|
|
602
|
-
pushed: input.contactId,
|
|
603
|
-
}),
|
|
656
|
+
contactId: resolvedContactId,
|
|
604
657
|
serializeWithGraphLock: options.serializeEnrollment,
|
|
605
658
|
});
|
|
606
659
|
if (!state) {
|
|
@@ -634,6 +687,9 @@ export async function executeJourneyRun(
|
|
|
634
687
|
stateId,
|
|
635
688
|
journeyId: meta.id,
|
|
636
689
|
journeyName: meta.name,
|
|
690
|
+
// The enrollment row's OWN stamp — replay-stable (a recovered run reads
|
|
691
|
+
// back what first entry wrote) and NULL for a contactless subject.
|
|
692
|
+
contactId: state.contactId,
|
|
637
693
|
};
|
|
638
694
|
|
|
639
695
|
// The injected analytics instance (set by createHogsendClient). Same
|
|
@@ -652,8 +708,17 @@ export async function executeJourneyRun(
|
|
|
652
708
|
// of the fn BEFORE the try/catch below (which would strand the row —
|
|
653
709
|
// already inserted "active" — outside the failure handling). The PostHog
|
|
654
710
|
// leg already `.catch`es; mirror it on the contact read.
|
|
655
|
-
|
|
656
|
-
|
|
711
|
+
//
|
|
712
|
+
// Alias-aware resolve, then read the row by id. The old
|
|
713
|
+
// `external_id = :userId` probe missed an anon-keyed contact entirely and,
|
|
714
|
+
// carrying no `deleted_at` filter, read a merged-away loser's TOMBSTONE
|
|
715
|
+
// timezone in preference to the live survivor's.
|
|
716
|
+
lookupContactIdByKey(db, userId)
|
|
717
|
+
.then((contactId) =>
|
|
718
|
+
contactId
|
|
719
|
+
? db.query.contacts.findFirst({ where: eq(contacts.id, contactId) })
|
|
720
|
+
: undefined,
|
|
721
|
+
)
|
|
657
722
|
.catch(() => undefined),
|
|
658
723
|
posthog?.getPersonProperties(userId).catch(() => undefined),
|
|
659
724
|
]);
|
|
@@ -708,14 +773,18 @@ export async function executeJourneyRun(
|
|
|
708
773
|
journeyId: meta.id,
|
|
709
774
|
entryLimit: meta.entryLimit,
|
|
710
775
|
...(meta.entryPeriod ? { entryPeriod: meta.entryPeriod } : {}),
|
|
711
|
-
//
|
|
712
|
-
//
|
|
713
|
-
//
|
|
714
|
-
//
|
|
715
|
-
//
|
|
776
|
+
// The subject contact id — feeds BOTH the group-scope resolver and (PRD
|
|
777
|
+
// 05 T4) every bySubject history read on the context. `state.contactId`
|
|
778
|
+
// FIRST: it is the enrollment row's own stamp, validated by
|
|
779
|
+
// `resolveEnrollmentContactId` (a merged-away tombstone pin is rejected
|
|
780
|
+
// and re-resolved to the survivor) and replay-stable, where the raw
|
|
781
|
+
// pushed pin can be stale by the queue delay and the `contact` row here
|
|
782
|
+
// is an externalId-only best-effort fetch that misses anon-keyed
|
|
783
|
+
// contacts. The pin/row legs remain only as fallbacks for a NULL stamp
|
|
784
|
+
// (a pre-column-era recovered enrollment the sweep has not reached).
|
|
716
785
|
...(input.groups ? { triggerGroups: input.groups } : {}),
|
|
717
|
-
...((input.contactId ?? contact?.id)
|
|
718
|
-
? { contactId: input.contactId ?? contact?.id }
|
|
786
|
+
...((state.contactId ?? input.contactId ?? contact?.id)
|
|
787
|
+
? { contactId: state.contactId ?? input.contactId ?? contact?.id }
|
|
719
788
|
: {}),
|
|
720
789
|
});
|
|
721
790
|
|
|
@@ -9,6 +9,7 @@ import {
|
|
|
9
9
|
} from "@hatchet-dev/typescript-sdk/v1/index.js";
|
|
10
10
|
import type { DurationObject } from "@hogsend/core";
|
|
11
11
|
import {
|
|
12
|
+
bySubject,
|
|
12
13
|
durationToMs,
|
|
13
14
|
evaluateEventCondition,
|
|
14
15
|
evaluatePropertyConditions,
|
|
@@ -229,6 +230,15 @@ export function createJourneyContext(
|
|
|
229
230
|
defaultSendWindow,
|
|
230
231
|
} = config;
|
|
231
232
|
|
|
233
|
+
// PRD 05 T4 — the subject a history read is about. The run's resolved
|
|
234
|
+
// `contactId` applies ONLY to the ENROLLED user: `ctx.history.*` takes an
|
|
235
|
+
// arbitrary `userId` from author code, and scoping someone else's key to THIS
|
|
236
|
+
// run's contact would read the wrong person. A key that is not the enrolled
|
|
237
|
+
// one has no contact in hand, so it keeps `bySubject`'s text-key arm — which
|
|
238
|
+
// is exactly today's behavior for it.
|
|
239
|
+
const subjectFor = (targetUserId: string): string | null =>
|
|
240
|
+
targetUserId === userId ? (config.contactId ?? null) : null;
|
|
241
|
+
|
|
232
242
|
// Replay-stable clock: the real DurableContext.now() is memoized across
|
|
233
243
|
// replays; a pre-eviction engine (or a test ctx without it) falls back to the
|
|
234
244
|
// live clock. Only RECOMPUTED instants depend on this — never the DB-key
|
|
@@ -477,7 +487,10 @@ export function createJourneyContext(
|
|
|
477
487
|
// association map; user scope keeps the enrolled-user predicate.
|
|
478
488
|
groupScope
|
|
479
489
|
? sql`${userEvents.groups} ->> ${groupScope.type} = ${groupScope.key}`
|
|
480
|
-
:
|
|
490
|
+
: bySubject(userEvents, {
|
|
491
|
+
contactId: config.contactId,
|
|
492
|
+
userKey: userId,
|
|
493
|
+
}),
|
|
481
494
|
eq(userEvents.event, event),
|
|
482
495
|
gte(userEvents.occurredAt, scanSince),
|
|
483
496
|
...eqPreds,
|
|
@@ -676,7 +689,10 @@ export function createJourneyContext(
|
|
|
676
689
|
.from(userEvents)
|
|
677
690
|
.where(
|
|
678
691
|
and(
|
|
679
|
-
|
|
692
|
+
bySubject(userEvents, {
|
|
693
|
+
contactId: config.contactId,
|
|
694
|
+
userKey: userId,
|
|
695
|
+
}),
|
|
680
696
|
eq(userEvents.event, event),
|
|
681
697
|
gte(userEvents.occurredAt, since),
|
|
682
698
|
),
|
|
@@ -815,7 +831,10 @@ export function createJourneyContext(
|
|
|
815
831
|
.from(userEvents)
|
|
816
832
|
.where(
|
|
817
833
|
and(
|
|
818
|
-
|
|
834
|
+
bySubject(userEvents, {
|
|
835
|
+
contactId: config.contactId,
|
|
836
|
+
userKey: userId,
|
|
837
|
+
}),
|
|
819
838
|
eq(userEvents.event, event),
|
|
820
839
|
gte(userEvents.occurredAt, scanSince),
|
|
821
840
|
lte(userEvents.occurredAt, flushInstant),
|
|
@@ -1416,7 +1435,11 @@ export function createJourneyContext(
|
|
|
1416
1435
|
|
|
1417
1436
|
guard: {
|
|
1418
1437
|
async isSubscribed() {
|
|
1419
|
-
const prefs = await checkEmailPreferences({
|
|
1438
|
+
const prefs = await checkEmailPreferences({
|
|
1439
|
+
db,
|
|
1440
|
+
userId,
|
|
1441
|
+
contactId: config.contactId ?? null,
|
|
1442
|
+
});
|
|
1420
1443
|
return !prefs.unsubscribed;
|
|
1421
1444
|
},
|
|
1422
1445
|
},
|
|
@@ -1462,7 +1485,12 @@ export function createJourneyContext(
|
|
|
1462
1485
|
check: "exists",
|
|
1463
1486
|
within,
|
|
1464
1487
|
},
|
|
1465
|
-
ctx: {
|
|
1488
|
+
ctx: {
|
|
1489
|
+
db,
|
|
1490
|
+
userId: targetUserId,
|
|
1491
|
+
contactId: subjectFor(targetUserId),
|
|
1492
|
+
journeyContext,
|
|
1493
|
+
},
|
|
1466
1494
|
});
|
|
1467
1495
|
return { found: result.matched, count: result.count };
|
|
1468
1496
|
},
|
|
@@ -1476,7 +1504,10 @@ export function createJourneyContext(
|
|
|
1476
1504
|
.from(journeyStates)
|
|
1477
1505
|
.where(
|
|
1478
1506
|
and(
|
|
1479
|
-
|
|
1507
|
+
bySubject(journeyStates, {
|
|
1508
|
+
contactId: subjectFor(targetUserId),
|
|
1509
|
+
userKey: targetUserId,
|
|
1510
|
+
}),
|
|
1480
1511
|
eq(journeyStates.journeyId, targetJourneyId),
|
|
1481
1512
|
),
|
|
1482
1513
|
);
|
|
@@ -1549,7 +1580,12 @@ export function createJourneyContext(
|
|
|
1549
1580
|
limit = 50,
|
|
1550
1581
|
within,
|
|
1551
1582
|
}): Promise<RecentEvent[]> {
|
|
1552
|
-
const conditions = [
|
|
1583
|
+
const conditions = [
|
|
1584
|
+
bySubject(userEvents, {
|
|
1585
|
+
contactId: subjectFor(targetUserId),
|
|
1586
|
+
userKey: targetUserId,
|
|
1587
|
+
}),
|
|
1588
|
+
];
|
|
1553
1589
|
if (event) {
|
|
1554
1590
|
conditions.push(eq(userEvents.event, event));
|
|
1555
1591
|
}
|
package/src/lib/agent/tools.ts
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
bySubject,
|
|
3
|
+
criteriaBuilder,
|
|
4
|
+
days,
|
|
5
|
+
evaluateCondition,
|
|
6
|
+
} from "@hogsend/core";
|
|
2
7
|
import {
|
|
3
8
|
contacts,
|
|
4
9
|
emailPreferences,
|
|
@@ -130,6 +135,9 @@ export function buildAgentTools({
|
|
|
130
135
|
return db
|
|
131
136
|
.select({
|
|
132
137
|
event: userEvents.event,
|
|
138
|
+
// Display echo of the stamped key — not a scoping predicate. This
|
|
139
|
+
// tool lists the recent event stream instance-wide; there is no
|
|
140
|
+
// subject to scope by.
|
|
133
141
|
userId: userEvents.userId,
|
|
134
142
|
source: userEvents.source,
|
|
135
143
|
occurredAt: userEvents.occurredAt,
|
|
@@ -169,10 +177,18 @@ export function buildAgentTools({
|
|
|
169
177
|
execute: async ({ id }) => {
|
|
170
178
|
const contact = await resolveContact({ db, id });
|
|
171
179
|
if (!contact) return { error: `No contact for "${id}"` };
|
|
180
|
+
// Was `contact.externalId ?? contact.id` — an inline re-derivation of
|
|
181
|
+
// the canonical key that missed a preferences row written under an
|
|
182
|
+
// anonymous id. The owning contact names it directly.
|
|
172
183
|
const prefs = await db
|
|
173
184
|
.select()
|
|
174
185
|
.from(emailPreferences)
|
|
175
|
-
.where(
|
|
186
|
+
.where(
|
|
187
|
+
bySubject(emailPreferences, {
|
|
188
|
+
contactId: contact.id,
|
|
189
|
+
userKey: contactKey(contact),
|
|
190
|
+
}),
|
|
191
|
+
)
|
|
176
192
|
.limit(1);
|
|
177
193
|
return { contact, preferences: prefs[0] ?? null };
|
|
178
194
|
},
|
|
@@ -189,6 +205,10 @@ export function buildAgentTools({
|
|
|
189
205
|
const contact = await resolveContact({ db, id });
|
|
190
206
|
if (!contact) return { error: `No contact for "${id}"` };
|
|
191
207
|
const key = contactKey(contact);
|
|
208
|
+
// Read by subject: the contact was just resolved, so both legs scope
|
|
209
|
+
// on the `contact_id` FK and pick up activity from keys this person
|
|
210
|
+
// has since moved off.
|
|
211
|
+
const subject = { contactId: contact.id, userKey: key };
|
|
192
212
|
const [events, journeys] = await Promise.all([
|
|
193
213
|
db
|
|
194
214
|
.select({
|
|
@@ -197,7 +217,7 @@ export function buildAgentTools({
|
|
|
197
217
|
occurredAt: userEvents.occurredAt,
|
|
198
218
|
})
|
|
199
219
|
.from(userEvents)
|
|
200
|
-
.where(
|
|
220
|
+
.where(bySubject(userEvents, subject))
|
|
201
221
|
.orderBy(desc(userEvents.occurredAt))
|
|
202
222
|
.limit(limit),
|
|
203
223
|
db
|
|
@@ -209,7 +229,7 @@ export function buildAgentTools({
|
|
|
209
229
|
.from(journeyStates)
|
|
210
230
|
.where(
|
|
211
231
|
and(
|
|
212
|
-
|
|
232
|
+
bySubject(journeyStates, subject),
|
|
213
233
|
isNull(journeyStates.deletedAt),
|
|
214
234
|
),
|
|
215
235
|
)
|
|
@@ -296,6 +316,11 @@ export function buildAgentTools({
|
|
|
296
316
|
ctx: {
|
|
297
317
|
db,
|
|
298
318
|
userId: contactKey(c),
|
|
319
|
+
// Every row here IS a contact, so the evaluator's event leaf
|
|
320
|
+
// counts that contact's whole history — including events stamped
|
|
321
|
+
// under an earlier anonymous key. Without this the audience
|
|
322
|
+
// preview under-counts anyone who registered after being seen.
|
|
323
|
+
contactId: c.id,
|
|
299
324
|
journeyContext: (c.properties ?? {}) as Record<string, unknown>,
|
|
300
325
|
},
|
|
301
326
|
});
|
|
@@ -134,6 +134,7 @@ export async function backfillAttributionBatch(opts: {
|
|
|
134
134
|
id: userEvents.id,
|
|
135
135
|
event: userEvents.event,
|
|
136
136
|
userId: userEvents.userId,
|
|
137
|
+
contactId: userEvents.contactId,
|
|
137
138
|
properties: userEvents.properties,
|
|
138
139
|
value: userEvents.value,
|
|
139
140
|
currency: userEvents.currency,
|
|
@@ -151,9 +152,21 @@ export async function backfillAttributionBatch(opts: {
|
|
|
151
152
|
.orderBy(asc(userEvents.id))
|
|
152
153
|
.limit(limit);
|
|
153
154
|
|
|
154
|
-
//
|
|
155
|
-
//
|
|
156
|
-
|
|
155
|
+
// Owner resolution. A row stamped with `contact_id` already names its
|
|
156
|
+
// owner, so only the unstamped remainder needs the string lookup:
|
|
157
|
+
// canonical keys are externalId or the contact row uuid. MATCH ONLY —
|
|
158
|
+
// backfill never mints contacts.
|
|
159
|
+
//
|
|
160
|
+
// PRD 07 T7/D9 — BRIDGE MACHINERY: this deliberately string-matches the
|
|
161
|
+
// HISTORICAL `user_events.user_id` written before the dual-write, which is
|
|
162
|
+
// the very gap it exists to close. It is not a resolution read to flip onto
|
|
163
|
+
// `lookupContactIdByKey`: it is a set-based batch match over up to `limit`
|
|
164
|
+
// keys at once (a per-key alias-aware resolve would be N round trips), and
|
|
165
|
+
// widening it to alias-held keys would move which historical rows a
|
|
166
|
+
// recompute credits — a data change smuggled into a read flip.
|
|
167
|
+
const keys = [
|
|
168
|
+
...new Set(rows.filter((row) => !row.contactId).map((row) => row.userId)),
|
|
169
|
+
];
|
|
157
170
|
const uuidKeys = keys.filter((key) => UUID_RE.test(key));
|
|
158
171
|
const contactRows =
|
|
159
172
|
keys.length > 0
|
|
@@ -178,7 +191,7 @@ export async function backfillAttributionBatch(opts: {
|
|
|
178
191
|
let conversionsFired = 0;
|
|
179
192
|
let creditsWritten = 0;
|
|
180
193
|
for (const row of rows) {
|
|
181
|
-
const contactId = contactByKey.get(row.userId);
|
|
194
|
+
const contactId = row.contactId ?? contactByKey.get(row.userId);
|
|
182
195
|
if (!contactId) continue;
|
|
183
196
|
const fired = await evaluateConversionsAtIngest({
|
|
184
197
|
db,
|
|
@@ -206,6 +219,15 @@ export async function backfillAttributionBatch(opts: {
|
|
|
206
219
|
logger,
|
|
207
220
|
conversionId: conversion.conversionId,
|
|
208
221
|
userKey: row.userId,
|
|
222
|
+
// Scope the touchpoint path by the OWNER only when the spine row
|
|
223
|
+
// itself carries the stamp. This function replays HISTORY, and
|
|
224
|
+
// pre-upgrade history predates the `contact_id` dual-write entirely:
|
|
225
|
+
// an unstamped trigger row sits among unstamped touchpoints, which a
|
|
226
|
+
// contact-scoped scan cannot reach at all. When the trigger IS
|
|
227
|
+
// stamped, everything older is too (PRD 04's sweep cursors ascending
|
|
228
|
+
// by id), so the contact arm is both safe and the point — it reaches
|
|
229
|
+
// the anon-era touches adoption moved onto this person.
|
|
230
|
+
contactId: row.contactId,
|
|
209
231
|
value: conversion.value,
|
|
210
232
|
currency: conversion.currency,
|
|
211
233
|
occurredAt: row.occurredAt,
|
|
@@ -240,11 +262,17 @@ export async function backfillAttributionBatch(opts: {
|
|
|
240
262
|
id: conversions.id,
|
|
241
263
|
definitionId: conversions.definitionId,
|
|
242
264
|
userKey: conversions.userKey,
|
|
265
|
+
contactId: conversions.contactId,
|
|
266
|
+
// The trigger row's own stamp — the same "is this spine stamped?" test
|
|
267
|
+
// stage 1 applies, joined in because a conversions row always names an
|
|
268
|
+
// owner even when the history behind it predates `contact_id`.
|
|
269
|
+
spineContactId: userEvents.contactId,
|
|
243
270
|
value: conversions.value,
|
|
244
271
|
currency: conversions.currency,
|
|
245
272
|
occurredAt: conversions.occurredAt,
|
|
246
273
|
})
|
|
247
274
|
.from(conversions)
|
|
275
|
+
.leftJoin(userEvents, eq(conversions.eventId, userEvents.id))
|
|
248
276
|
.where(
|
|
249
277
|
and(
|
|
250
278
|
inArray(conversions.definitionId, defIds),
|
|
@@ -265,6 +293,9 @@ export async function backfillAttributionBatch(opts: {
|
|
|
265
293
|
logger,
|
|
266
294
|
conversionId: row.id,
|
|
267
295
|
userKey: row.userKey,
|
|
296
|
+
// See stage 1: the owner scopes the path only when the spine carries the
|
|
297
|
+
// stamp; unstamped (pre-upgrade) history is reachable by string key only.
|
|
298
|
+
contactId: row.spineContactId ? row.contactId : null,
|
|
268
299
|
value: row.value,
|
|
269
300
|
currency: row.currency,
|
|
270
301
|
occurredAt: row.occurredAt,
|
package/src/lib/attribution.ts
CHANGED
|
@@ -3,6 +3,7 @@ import {
|
|
|
3
3
|
computeAllModels,
|
|
4
4
|
} from "@hogsend/attribution";
|
|
5
5
|
import {
|
|
6
|
+
bySubject,
|
|
6
7
|
type DurationObject,
|
|
7
8
|
durationToMs,
|
|
8
9
|
TOUCHPOINT_EVENTS,
|
|
@@ -120,6 +121,16 @@ export async function recordAttributionCredits(opts: {
|
|
|
120
121
|
conversionId: string;
|
|
121
122
|
/** The contact's canonical event key (`user_events.user_id`). */
|
|
122
123
|
userKey: string;
|
|
124
|
+
/**
|
|
125
|
+
* The trusted owner uuid (`conversions.contact_id`). REQUIRED (not
|
|
126
|
+
* optional) for the same reason the enrollment guards' is: an optional
|
|
127
|
+
* field silently defaults a new caller onto the mutable text key, and the
|
|
128
|
+
* touchpoint path is precisely the history written BEFORE the person was
|
|
129
|
+
* identified — a key-scoped read drops the anonymous half of every journey
|
|
130
|
+
* and credits the conversion to nothing. Pass `null` explicitly for a
|
|
131
|
+
* subject with no contact; `userKey` still serves that case.
|
|
132
|
+
*/
|
|
133
|
+
contactId: string | null;
|
|
123
134
|
value: number | null;
|
|
124
135
|
currency: string | null;
|
|
125
136
|
/** When the conversion happened. */
|
|
@@ -132,8 +143,16 @@ export async function recordAttributionCredits(opts: {
|
|
|
132
143
|
*/
|
|
133
144
|
windows?: Partial<Record<TouchpointChannel, DurationObject>>;
|
|
134
145
|
}): Promise<{ touchpoints: number }> {
|
|
135
|
-
const {
|
|
136
|
-
|
|
146
|
+
const {
|
|
147
|
+
db,
|
|
148
|
+
logger,
|
|
149
|
+
conversionId,
|
|
150
|
+
userKey,
|
|
151
|
+
contactId,
|
|
152
|
+
value,
|
|
153
|
+
currency,
|
|
154
|
+
occurredAt,
|
|
155
|
+
} = opts;
|
|
137
156
|
const defaultWindowMs = opts.windowDays * 24 * 60 * 60 * 1000;
|
|
138
157
|
const channelWindowMs = new Map<TouchpointChannel, number>(
|
|
139
158
|
Object.entries(opts.windows ?? {}).map(([channel, duration]) => [
|
|
@@ -158,7 +177,7 @@ export async function recordAttributionCredits(opts: {
|
|
|
158
177
|
.from(userEvents)
|
|
159
178
|
.where(
|
|
160
179
|
and(
|
|
161
|
-
|
|
180
|
+
bySubject(userEvents, { contactId, userKey }),
|
|
162
181
|
inArray(userEvents.event, [...TOUCHPOINT_EVENTS]),
|
|
163
182
|
gte(userEvents.occurredAt, windowStart),
|
|
164
183
|
lte(userEvents.occurredAt, occurredAt),
|