@blamejs/blamejs-shop 0.4.62 → 0.4.64

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/CHANGELOG.md CHANGED
@@ -8,6 +8,10 @@ upgrading across more than a few patches at a time.
8
8
 
9
9
  ## v0.4.x
10
10
 
11
+ - v0.4.64 (2026-06-19) — **A failed side-effect can no longer strand a claimed record.** Hardens the atomic-claim concurrency fixes (shipped over the previous releases) against the case where the side-effect fails or the worker crashes AFTER a record was claimed. Each claim now restores or recovers the record so a transient failure can't leave it permanently stuck. A scheduled payment retry that is claimed out of the due set but then fails to advance (a malformed policy or a database write error) restores its next-retry time, so the retry isn't silently dropped. Approving a seller application that crashes between claiming the approval and persisting the vendor is now recoverable — an application left approved with no vendor can be approved again rather than being stranded in a terminal state. A survey response whose insert fails after the invitation was claimed reverts the invitation to issued so it can be answered. A reorder reminder or wishlist digest whose send fails defers the retry to a later tick on a distinct cursor, so a concurrent overlapping tick can't pick up the rolled-back row and send a duplicate in the same window. No API change. **Fixed:** *Payment retry restores its schedule on a failed advance* — The retry scheduler claims an enrollment out of the due set by clearing its next-retry time before doing processor work. If advancing the enrollment then throws (a malformed retry policy, or a database write failure while recording the attempt), the next-retry time is restored to the value the tick observed, so a later tick re-attempts the retry. Previously the enrollment was left active with no next-retry time, and the due query (which requires a next-retry time) would never pick it up again, silently stopping the customer's recovery retries. · *Seller approval is recoverable after a mid-approval crash* — Approving a seller application claims the in-review-to-approved transition before registering the vendor. If the worker crashes or times out between the claim and persisting the vendor, the application is left approved with no vendor — a terminal state the rest of the primitive could never move out of. Approval now treats an approved application that has no vendor attached as re-approvable, so the registration can be retried and the application recovered instead of stranded. · *Survey response keeps the invitation retryable on insert failure* — Submitting a survey response claims the invitation (issued to responded) before inserting the response row. If that insert fails (a transient write error), the invitation is reverted to issued so the response can be submitted again, rather than being stuck responded with no response recorded and every retry rejected as already-responded. · *Reorder reminder and wishlist digest defer a failed send instead of re-firing it* — When a reorder reminder or a wishlist digest send fails after the row was claimed, the schedule cursor is rolled to a value distinct from the one the tick observed (still due, so a later tick retries) rather than back to the exact observed value. A concurrent overlapping tick that read the same cursor was waiting to claim it; restoring the exact value let it match and send a duplicate in the same window. The retry is now deferred to a later tick with no duplicate.
12
+
13
+ - v0.4.63 (2026-06-19) — **Fulfillment and customer-data actions can't double-fire under concurrent calls.** Closes a further set of concurrency races where a fulfillment or customer-data action read a row, checked its status in application code, and then performed an irreversible side-effect (open an inventory hold, create shipments, restock received stock, create an order, reparent customer records, requeue a print job, mint child carts) before an unconditional update committed — so two concurrent calls could both pass the check and both perform the side-effect. Each now claims the transition with a single conditional update and performs the side-effect only when that claim wins, reverting the claim if the side-effect then fails so a row is never stranded. Approving an exchange opens its replacement hold once; executing a split-shipment plan creates the parcels once; recording a partial purchase-order receipt restocks each line once (claimed per line); completing a pick list creates its shipment once; converting or launching a pre-order creates the order once and a reservation can't oversell its cap; merging or rolling back a customer reparents the records once; an impersonation notice, a duplicate-suggestion link, a print-job retry, and a cart split each happen once. Behavior for a single sequential caller is unchanged. **Fixed:** *Fulfillment transitions claim before their side-effect* — Approving an exchange now claims pending-to-approved (WHERE id = ? AND status = 'pending') before opening the replacement inventory hold, reverting to pending if the hold fails. Executing a split-shipment plan claims proposed-to-executed before creating any shipment. Recording a partial purchase-order receipt claims each receipt line by advancing its received quantity conditionally before restocking, rolling the claimed lines back if a later line fails. Completing a pick list claims its completion before creating the shipment. In each case two concurrent calls can no longer both create the holds / shipments / restock for one row. · *Pre-order conversion, launch, cancel, and reserve are atomic* — Converting a reservation to an order claims active-to-converted before creating the order (reverting on failure), so a reservation can't spawn two orders; launching a campaign claims active-to-launched before walking reservations; cancelling claims active-to-cancelled before decrementing the reserved counter. Reserving now enforces the campaign cap inside the increment itself (units_reserved + qty <= max_units_available in the update's WHERE), so concurrent reservations can't oversell the pool; a reservation that loses the cap is compensated. · *Customer merge/rollback, impersonation notice, suggestion dedup, print retry, and cart split run once* — Executing or rolling back a customer merge claims the transition before reparenting records, reverting if the reparent fails. Sending the 'an operator viewed your account' notice claims the notified stamp (WHERE customer_notified_at IS NULL) before enqueuing, so it's sent once. Linking a duplicate suggestion claims the source before migrating its votes to the canonical row. Marking a print job failed claims the transition before inserting the retry job, so a job isn't reprinted twice. Splitting a cart claims the source's abandon before minting the child carts, so a concurrent split can't create two sets of children.
14
+
11
15
  - v0.4.62 (2026-06-19) — **Money and approval actions can't double-fire under concurrent calls.** Closes a set of concurrency races in money- and approval-critical paths where the action read a row, checked its status in application code, and then performed an irreversible side-effect (retry a card, execute an approved action, register a vendor, bill a subscription change) before an unconditional update committed — so two concurrent calls could both pass the check and both perform the side-effect. Each now claims the transition with a single conditional update and performs the side-effect only when that claim wins. A scheduled payment retry is claimed out of the due set before the processor is called, so an overlapping scheduler tick can't retry the same card twice; a payment outcome is claimed by its attempt number before the attempt is recorded, so a redelivered webhook can't double-count it. Executing an approved operator request claims the approved-to-executed transition before returning success, so the underlying money move runs once. Approving a seller application claims the in-review-to-approved transition before registering the vendor (rolling back to in-review if registration fails), so one application can't create two vendors. Applying scheduled subscription plan changes claims each pending change before updating the plan and recording its proration invoice, and stamps a deterministic idempotency key on the invoice, so an overlapping or retried scheduler run can't bill the proration twice. Behavior for a single sequential caller is unchanged. **Fixed:** *Scheduled payment retries and recorded outcomes claim before acting* — The retry scheduler now claims each due enrollment (nulling its next-retry time, conditional on the value the tick observed) before composing the processor retry, so two overlapping ticks can't both retry the same card for one scheduled slot — only the claim winner calls the processor. Recording a retry outcome claims the enrollment by bumping its attempt count conditionally on the observed value before writing the attempt row, so a redelivered webhook (or a manual record racing it) can't write a duplicate attempt or double-count toward the cap; the loser returns the already-advanced row. · *Executing an approved request runs the action once* — markExecuted now flips the request from approved to executed with a conditional update (WHERE id = ? AND status = 'approved') and returns success only when that update changes one row; a concurrent second call is refused with a typed error before the application runs the underlying action (a large refund, vendor payout, or bulk operation) a second time. · *Approving a seller application creates one vendor* — approveApplication now claims the in-review-to-approved transition first and registers the vendor only when the claim wins, so two concurrent approvals can't both register a vendor for one application. If vendor registration fails after the claim, the application is rolled back to in-review so it can be approved again rather than stranded as approved with no vendor. · *Applying scheduled plan changes bills the proration once* — applyScheduledChanges now claims each pending change (WHERE id = ? AND status = 'pending') before updating the subscription plan and recording the proration invoice, so an overlapping or retried scheduler run skips an already-applied change instead of billing it twice. Both the scheduled and the immediate plan-change paths now stamp a deterministic idempotency key on the proration invoice, so even a re-run that reached the billing call would dedupe against the unique invoice id rather than write a second charge. A regression test asserts a second apply pass records no additional invoice.
12
16
 
13
17
  - v0.4.61 (2026-06-19) — **Scheduled and dispatched sends no longer double-fire under concurrent ticks.** Closes a class of concurrency races in the scheduled-send and dispatch paths where a tick read a row, checked its status or schedule cursor in application code, and then performed the send (and its ledger write) before an unconditional update committed — so two overlapping ticks (a cron overrun, two workers, or a manual tick racing the schedule) could both pass the check and both send. Each path now claims the row with a single conditional update — flipping the status, or advancing the schedule cursor, only when the row is still in the expected state — and performs the send only when that claim wins; the losing tick changes zero rows and skips. The affected sends: an email campaign drain (the whole audience could be mailed twice), a queued push notification, a wishlist digest email and its sent-ledger row, a reorder reminder, a survey response record, and a dunning step's reminder email / subscription action. Behavior for a single (sequential) caller is unchanged; only the concurrent double-fire is removed. Where a send fails after the claim wins, the schedule cursor is rolled back so the row is retried on the next tick rather than skipped. **Fixed:** *Email campaign sends claim the campaign before draining* — sendNow, the scheduled dispatch tick, and the consent-gated broadcast drain now flip the campaign from scheduled to sending with a conditional update (WHERE slug = ? AND status = 'scheduled') and drain only when that update changes exactly one row. Previously the status check ran in application code before an unconditional flip, so two concurrent sends could both drain and mail the entire audience twice. The losing caller refuses (a typed send-race error) or, for the tick, skips the campaign. · *Push, wishlist-digest, and reorder-reminder ticks claim each row before sending* — Each per-row advance is now the atomic claim: a queued push notification advances to sent/failed only via WHERE id = ? AND status = 'queued'; a wishlist digest and a reorder reminder advance their schedule cursor with WHERE id = ? AND next_*_at = <the observed value>. The external send (and, for the digest, its sent-ledger row) runs only when the claim changes one row, so two overlapping ticks can't both dispatch the same row. A send that fails after winning the reminder claim rolls the cursor back so the row retries next tick. · *Survey responses and dunning steps gate their side-effect on an atomic claim* — Submitting a survey response now flips the invitation from issued to responded with WHERE id = ? AND status = 'issued' and inserts the response row only when that claim wins (a lost race returns a typed already-responded error), so a double-submit can't record two responses for one invitation. A dunning tick now claims the enrollment with WHERE id = ? AND status = 'active' AND next_action_at = <the observed value> before executing the step (the reminder email / in-app notification / pause or cancel), so overlapping dunning ticks can't send a step twice; the subsequent state transitions carry the same status guard.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.4.62",
2
+ "version": "0.4.64",
3
3
  "assets": {
4
4
  "css/admin.css": {
5
5
  "integrity": "sha384-imfe0otYErcB8rr2h6KLSGTtStirysptpXETSPY4zLv3bZoIT75Lo1dOvkOav+xL",
@@ -516,12 +516,23 @@ function create(opts) {
516
516
  // carts are not the shopper's working cart, they're scratch
517
517
  // carts for downstream fulfillment / split-order quoting).
518
518
  var ts = _now();
519
- // Mark source abandoned first so the active-session index is
520
- // free for any reuse.
521
- await query(
522
- "UPDATE carts SET status = 'abandoned', updated_at = ?1 WHERE id = ?2",
519
+ // Atomic claim: mark the source abandoned in a single
520
+ // conditional UPDATE that re-checks `status = 'active'` in its
521
+ // own WHERE. `_loadCart` read the status in JS, but two
522
+ // concurrent splitCart calls would both pass that check and
523
+ // both mint a full set of child carts (double-create). SQLite /
524
+ // D1 serializes writers, so exactly one of the racing UPDATEs
525
+ // flips active→abandoned (rowCount === 1) and earns the right
526
+ // to mint the children; the loser sees rowCount === 0 and
527
+ // refuses rather than producing a second set of child carts.
528
+ // This also frees the active-session index for any reuse.
529
+ var claim = await query(
530
+ "UPDATE carts SET status = 'abandoned', updated_at = ?1 WHERE id = ?2 AND status = 'active'",
523
531
  [ts, input.cart_id],
524
532
  );
533
+ if (Number(claim.rowCount || 0) !== 1) {
534
+ throw new TypeError("cartBulkOps.splitCart: cart " + input.cart_id + " already split/modified");
535
+ }
525
536
  var children = [];
526
537
  for (var gi = 0; gi < groupOrder.length; gi += 1) {
527
538
  var groupKey = groupOrder[gi];
@@ -492,6 +492,20 @@ function create(opts) {
492
492
  if (!notifications) {
493
493
  return { notified: false, customer_notified_at: null };
494
494
  }
495
+
496
+ // Enqueue FIRST, then record the confirmation stamp — so
497
+ // `customer_notified_at` only ever means "the notice was
498
+ // successfully enqueued", never "claimed but the enqueue may have
499
+ // failed". A claim-before-enqueue stamp let a concurrent caller
500
+ // observe the provisional stamp and report `notified: true` while
501
+ // the winner's enqueue was still pending (and might then throw and
502
+ // roll the stamp back), silently dropping the privacy notice.
503
+ // Recording the stamp only on enqueue success closes that. A
504
+ // concurrent caller that also slipped past the null-check above may
505
+ // enqueue a second time; a duplicate "an operator viewed your
506
+ // account" notice is benign and strictly preferable to missing it,
507
+ // and the audit stamp still resolves to a single value.
508
+ var now = _now();
495
509
  await notifications.enqueue({
496
510
  recipient_id: existing.customer_id,
497
511
  channel: "account-impersonation",
@@ -506,12 +520,21 @@ function create(opts) {
506
520
  expires_at: Number(existing.expires_at),
507
521
  },
508
522
  });
509
- var now = _now();
523
+
524
+ // Stamp the confirmation idempotently — the first writer to land
525
+ // wins (WHERE customer_notified_at IS NULL); a concurrent second
526
+ // caller's UPDATE matches zero rows and returns the already-
527
+ // recorded stamp. An enqueue throw above propagates before this,
528
+ // leaving the row un-stamped so a retry re-attempts delivery.
510
529
  await query(
511
- "UPDATE impersonations SET customer_notified_at = ?1 WHERE id = ?2",
530
+ "UPDATE impersonations SET customer_notified_at = ?1 " +
531
+ "WHERE id = ?2 AND customer_notified_at IS NULL",
512
532
  [now, id],
513
533
  );
514
- return { notified: true, customer_notified_at: now };
534
+ var stampedRow = await _getRow(id);
535
+ var stampedAt = stampedRow && stampedRow.customer_notified_at != null
536
+ ? Number(stampedRow.customer_notified_at) : now;
537
+ return { notified: true, customer_notified_at: stampedAt };
515
538
  },
516
539
 
517
540
  // ---- listForOperator ------------------------------------------------
@@ -693,26 +693,70 @@ function create(opts) {
693
693
  throw drErr;
694
694
  }
695
695
 
696
- // Commit every reparent.
697
- var actual = await _reparentAll(row.source_customer_id, row.target_customer_id);
698
-
699
- // Archive the source customer + insert the redirect marker.
700
- await customers.archiveCustomer(row.source_customer_id);
696
+ // Atomically CLAIM the proposed->executed transition BEFORE
697
+ // running any exactly-once side effect. SQLite serializes
698
+ // writers, so this conditional UPDATE is the race-free claim:
699
+ // two concurrent executeMerge calls on the same proposed row
700
+ // both pass the JS status check above, but only one lands
701
+ // rowCount===1 here — the loser sees rowCount 0 and bails out
702
+ // returning the now-executed row, so the reparent / archive /
703
+ // redirect-insert fire exactly once.
701
704
  var ts = _now();
702
- await query(
703
- "INSERT INTO customer_merge_redirects " +
704
- "(source_customer_id, target_customer_id, merge_id, executed_at) " +
705
- "VALUES (?1, ?2, ?3, ?4)",
706
- [row.source_customer_id, row.target_customer_id, mergeId, ts],
705
+ var claim = await query(
706
+ "UPDATE customer_merges SET status = 'executed', " +
707
+ "executed_at = ?1, executed_by = ?2 WHERE id = ?3 AND status = 'proposed'",
708
+ [ts, executedBy, mergeId],
707
709
  );
710
+ if (Number(claim.rowCount || 0) !== 1) {
711
+ // Lost the race (or the row left 'proposed' between our read
712
+ // and the claim). Re-read: an already-executed row is the
713
+ // winner's result; anything else is a genuine state error.
714
+ var current = await _getMergeRow(mergeId);
715
+ if (current && current.status === "executed") {
716
+ return _hydrateMerge(current);
717
+ }
718
+ var raceErr = new Error("customerMerge.executeMerge: merge_id " + mergeId +
719
+ " is no longer proposed, only proposed merges can be executed");
720
+ raceErr.code = "CUSTOMER_MERGE_NOT_PROPOSED";
721
+ throw raceErr;
722
+ }
708
723
 
709
- // Land the merge in executed; freeze the actual reparent
710
- // counts on plan_json so rollback has the exact footprint.
724
+ // Claim won now run the exactly-once side effects. If any
725
+ // throws, REVERT the claim (self-targeting the row we just
726
+ // flipped) so the merge isn't stranded in 'executed' with the
727
+ // reparents only partially applied; then rethrow.
728
+ var actual;
729
+ try {
730
+ // Commit every reparent.
731
+ actual = await _reparentAll(row.source_customer_id, row.target_customer_id);
732
+
733
+ // Archive the source customer + insert the redirect marker.
734
+ await customers.archiveCustomer(row.source_customer_id);
735
+ await query(
736
+ "INSERT INTO customer_merge_redirects " +
737
+ "(source_customer_id, target_customer_id, merge_id, executed_at) " +
738
+ "VALUES (?1, ?2, ?3, ?4)",
739
+ [row.source_customer_id, row.target_customer_id, mergeId, ts],
740
+ );
741
+ } catch (sideErr) {
742
+ await query(
743
+ "UPDATE customer_merges SET status = 'proposed', " +
744
+ "executed_at = NULL, executed_by = NULL WHERE id = ?1 AND status = 'executed'",
745
+ [mergeId],
746
+ );
747
+ throw sideErr;
748
+ }
749
+
750
+ // Freeze the actual reparent counts on plan_json so rollback
751
+ // has the exact footprint. Status / executed_at / executed_by
752
+ // already landed in the claim above.
711
753
  var sealed = Object.assign({}, capturedPlan, { actual: actual });
754
+ // Gate on still-'executed' so this metadata seal can't land on a
755
+ // row a concurrent rollback (now allowed once the redirect exists)
756
+ // has already flipped to 'rolled_back'.
712
757
  await query(
713
- "UPDATE customer_merges SET status = 'executed', plan_json = ?1, " +
714
- "executed_at = ?2, executed_by = ?3 WHERE id = ?4",
715
- [JSON.stringify(sealed), ts, executedBy, mergeId],
758
+ "UPDATE customer_merges SET plan_json = ?1 WHERE id = ?2 AND status = 'executed'",
759
+ [JSON.stringify(sealed), mergeId],
716
760
  );
717
761
  return _hydrateMerge(await _getMergeRow(mergeId));
718
762
  },
@@ -743,6 +787,8 @@ function create(opts) {
743
787
  throw stErr;
744
788
  }
745
789
  var now = _now();
790
+ // Keep the in-window check BEFORE the claim — a past-window
791
+ // merge must refuse without flipping status.
746
792
  if (now - Number(row.executed_at) > ROLLBACK_WINDOW_MS) {
747
793
  var winErr = new Error("customerMerge.rollbackMerge: merge_id " + mergeId +
748
794
  " executed " + Math.floor((now - Number(row.executed_at)) / C.TIME.days(1)) +
@@ -752,21 +798,56 @@ function create(opts) {
752
798
  throw winErr;
753
799
  }
754
800
 
755
- // Reverse every reparent (target -> source).
756
- await _reparentAll(row.target_customer_id, row.source_customer_id);
757
-
758
- // Restore the source customer + drop the redirect marker.
759
- await customers.restoreCustomer(row.source_customer_id);
760
- await query(
761
- "DELETE FROM customer_merge_redirects WHERE source_customer_id = ?1",
762
- [row.source_customer_id],
763
- );
764
-
765
- await query(
801
+ // Atomically CLAIM the executed->rolled_back transition BEFORE
802
+ // running the reverse reparent / restore / redirect-delete.
803
+ // The conditional UPDATE is the race-free guard: two concurrent
804
+ // rollbackMerge calls both pass the JS status + window checks,
805
+ // but only one lands rowCount===1 here — the loser bails out so
806
+ // the reverse side effects fire exactly once.
807
+ // Gate the claim on the redirect row EXISTING. executeMerge flips
808
+ // status to 'executed' BEFORE its reparent/archive complete and
809
+ // inserts the redirect as its LAST side effect, so the redirect's
810
+ // presence is the proof that the reparent + archive are durable.
811
+ // Without this gate a rollback racing an in-flight execute (status
812
+ // already 'executed', reparents not yet done) would flip to
813
+ // 'rolled_back' and reverse nothing. If the redirect isn't there
814
+ // yet the merge is still finalizing — refuse so the caller retries.
815
+ var claim = await query(
766
816
  "UPDATE customer_merges SET status = 'rolled_back', " +
767
- "rolled_back_at = ?1, rollback_reason = ?2 WHERE id = ?3",
768
- [now, reason, mergeId],
817
+ "rolled_back_at = ?1, rollback_reason = ?2 WHERE id = ?3 AND status = 'executed' " +
818
+ "AND EXISTS (SELECT 1 FROM customer_merge_redirects WHERE source_customer_id = ?4)",
819
+ [now, reason, mergeId, row.source_customer_id],
769
820
  );
821
+ if (Number(claim.rowCount || 0) !== 1) {
822
+ var raceErr = new Error("customerMerge.rollbackMerge: merge_id " + mergeId +
823
+ " is no longer executed (or its merge is still finalizing); only fully-executed merges can be rolled back");
824
+ raceErr.code = "CUSTOMER_MERGE_NOT_EXECUTED";
825
+ throw raceErr;
826
+ }
827
+
828
+ // Claim won — now run the reverse side effects. If any throws,
829
+ // REVERT the claim (self-targeting the row we just flipped) so
830
+ // the merge isn't stranded in 'rolled_back' with the reparents
831
+ // only partially reversed; then rethrow.
832
+ try {
833
+ // Reverse every reparent (target -> source).
834
+ await _reparentAll(row.target_customer_id, row.source_customer_id);
835
+
836
+ // Restore the source customer + drop the redirect marker.
837
+ await customers.restoreCustomer(row.source_customer_id);
838
+ await query(
839
+ "DELETE FROM customer_merge_redirects WHERE source_customer_id = ?1",
840
+ [row.source_customer_id],
841
+ );
842
+ } catch (sideErr) {
843
+ await query(
844
+ "UPDATE customer_merges SET status = 'executed', " +
845
+ "rolled_back_at = NULL, rollback_reason = NULL WHERE id = ?1 AND status = 'rolled_back'",
846
+ [mergeId],
847
+ );
848
+ throw sideErr;
849
+ }
850
+
770
851
  return _hydrateMerge(await _getMergeRow(mergeId));
771
852
  },
772
853
 
@@ -749,11 +749,26 @@ function create(opts) {
749
749
  }
750
750
 
751
751
  var responseId = b.uuid.v7();
752
- await query(
753
- "INSERT INTO survey_responses (id, invitation_id, answers_json, occurred_at) " +
754
- "VALUES (?1, ?2, ?3, ?4)",
755
- [responseId, invitation.id, JSON.stringify(canonicalAnswers), occurredAt],
756
- );
752
+ try {
753
+ await query(
754
+ "INSERT INTO survey_responses (id, invitation_id, answers_json, occurred_at) " +
755
+ "VALUES (?1, ?2, ?3, ?4)",
756
+ [responseId, invitation.id, JSON.stringify(canonicalAnswers), occurredAt],
757
+ );
758
+ } catch (insErr) {
759
+ // The claim above already flipped the invitation to 'responded'. If
760
+ // the response insert fails (a transient D1/SQLite write error),
761
+ // revert the claim to 'issued' so the invitation stays retryable —
762
+ // otherwise it is stranded 'responded' with no response row and
763
+ // every retry is rejected as ALREADY_RESPONDED, so the response can
764
+ // never be recorded.
765
+ await query(
766
+ "UPDATE survey_invitations SET status = 'issued', responded_at = NULL " +
767
+ "WHERE id = ?1 AND status = 'responded'",
768
+ [invitation.id],
769
+ );
770
+ throw insErr;
771
+ }
757
772
 
758
773
  return {
759
774
  response_id: responseId,
@@ -286,28 +286,59 @@ function create(opts) {
286
286
  }
287
287
  _assertTransition(existing.status, "approveExchange");
288
288
 
289
- // Pin the replacement shelf BEFORE flipping the DB row. A
290
- // hold failure (insufficient stock, unknown location)
291
- // surfaces to the caller; the row stays pending so the next
292
- // operator attempt decides whether to retry, source from a
293
- // different shelf, or reject the exchange.
294
- if (invAllocs) {
295
- await invAllocs.holdForCart({
296
- cart_id: existing.id,
297
- sku: existing.replacement_sku,
298
- variant_id: existing.replacement_variant_id || null,
299
- quantity: existing.replacement_qty,
300
- // allow:raw-time-literal — hold TTL in SECONDS (passed to holdForCart's ttl_seconds); C.TIME returns ms
301
- ttl_seconds: input.hold_ttl_seconds || 86400,
302
- });
303
- }
304
-
289
+ // Claim pending -> approved ATOMICALLY before the inventory
290
+ // hold. The conditional WHERE (status = 'pending') is the
291
+ // serialization point: two operators racing the same exchange
292
+ // both pass the JS _assertTransition above, but only the writer
293
+ // whose UPDATE matches a still-pending row wins (rowCount === 1).
294
+ // The loser's UPDATE matches zero rows -> it refuses here and
295
+ // never opens a duplicate hold. Without this, both callers would
296
+ // reach holdForCart and pin the replacement SKU twice.
305
297
  var ts = _monotonicTs();
306
- await query(
298
+ var claim = await query(
307
299
  "UPDATE order_exchanges SET status = 'approved', approver_id = ?1, updated_at = ?2 " +
308
- "WHERE id = ?3",
300
+ "WHERE id = ?3 AND status = 'pending'",
309
301
  [approverId, ts, exchangeId],
310
302
  );
303
+ if (Number(claim.rowCount || 0) !== 1) {
304
+ var refused = new Error(
305
+ "order-exchanges: transition 'approveExchange' refused from state '" +
306
+ existing.status + "' (lost the race to a concurrent transition)"
307
+ );
308
+ refused.code = "EXCHANGE_TRANSITION_REFUSED";
309
+ throw refused;
310
+ }
311
+
312
+ // Pin the replacement shelf AFTER winning the claim. A hold
313
+ // failure (insufficient stock, unknown location) surfaces to the
314
+ // caller; we revert the claim back to pending so the next
315
+ // operator attempt decides whether to retry, source from a
316
+ // different shelf, or reject the exchange — the row is never
317
+ // stranded in `approved` without a hold.
318
+ if (invAllocs) {
319
+ try {
320
+ await invAllocs.holdForCart({
321
+ cart_id: existing.id,
322
+ sku: existing.replacement_sku,
323
+ variant_id: existing.replacement_variant_id || null,
324
+ quantity: existing.replacement_qty,
325
+ // allow:raw-time-literal — hold TTL in SECONDS (passed to holdForCart's ttl_seconds); C.TIME returns ms
326
+ ttl_seconds: input.hold_ttl_seconds || 86400,
327
+ });
328
+ } catch (holdErr) {
329
+ // Self-targeting revert: only un-claim the row WE just
330
+ // claimed (status still 'approved'). A concurrent follow-on
331
+ // transition that already moved the row off `approved` is
332
+ // left untouched.
333
+ await query(
334
+ "UPDATE order_exchanges SET status = 'pending', approver_id = NULL, updated_at = ?1 " +
335
+ "WHERE id = ?2 AND status = 'approved'",
336
+ [_monotonicTs(), exchangeId],
337
+ );
338
+ throw holdErr;
339
+ }
340
+ }
341
+
311
342
  return await _getRow(exchangeId);
312
343
  },
313
344
 
@@ -604,19 +604,50 @@ function create(opts) {
604
604
  );
605
605
  if (Number(claim.rowCount || 0) !== 1) continue; // another tick claimed it
606
606
 
607
- var policy = await _getPolicy(enrollment.policy_slug);
608
- if (!policy) {
609
- // Policy went missing between enrollment + tick close
610
- // as abandoned so the row doesn't spin forever.
607
+ // Pre-charge prep. The claim above nulled next_retry_at to take
608
+ // the row out of the due set; a throw HERE (a missing policy /
609
+ // malformed retry schedule) is BEFORE any processor work, so it is
610
+ // safe to restore the observed next_retry_at (only while still
611
+ // NULL, so a partial re-stamp isn't clobbered) and let a later
612
+ // tick re-attempt — otherwise the enrollment is stranded active
613
+ // with next_retry_at NULL and the due SELECT (next_retry_at IS NOT
614
+ // NULL) never picks it up again.
615
+ var policy, schedule;
616
+ try {
617
+ policy = await _getPolicy(enrollment.policy_slug);
618
+ if (!policy) {
619
+ // Policy went missing between enrollment + tick — close
620
+ // as abandoned so the row doesn't spin forever.
621
+ await query(
622
+ "UPDATE payment_retry_enrollments SET status = 'abandoned', next_retry_at = NULL, " +
623
+ "ended_at = ?1, end_reason = 'policy_missing' WHERE id = ?2",
624
+ [now, enrollment.id],
625
+ );
626
+ advanced.push(await _refetchEnrollment(enrollment.id));
627
+ continue;
628
+ }
629
+ schedule = _parseSchedule(policy.retry_schedule_json);
630
+ } catch (prepErr) {
611
631
  await query(
612
- "UPDATE payment_retry_enrollments SET status = 'abandoned', next_retry_at = NULL, " +
613
- "ended_at = ?1, end_reason = 'policy_missing' WHERE id = ?2",
614
- [now, enrollment.id],
632
+ "UPDATE payment_retry_enrollments SET next_retry_at = ?1 " +
633
+ "WHERE id = ?2 AND status = 'active' AND next_retry_at IS NULL",
634
+ [enrollment.next_retry_at, enrollment.id],
615
635
  );
616
- advanced.push(await _refetchEnrollment(enrollment.id));
617
- continue;
636
+ throw prepErr;
618
637
  }
619
- var schedule = _parseSchedule(policy.retry_schedule_json);
638
+
639
+ // _tickAdvance composes paymentHandle.retryIntent — the real
640
+ // card-charge retry — which runs BEFORE the attempt-ledger and
641
+ // status writes. By the time any throw escapes _tickAdvance the
642
+ // charge has already been submitted, so DO NOT restore
643
+ // next_retry_at on such a throw: re-stamping it would let a later
644
+ // or overlapping tick call retryIntent AGAIN for the same attempt
645
+ // and double-move money. The enrollment is left active with
646
+ // next_retry_at NULL for a recovery sweep / operator to advance;
647
+ // retryIntent is passed attempt_number as its idempotency
648
+ // dimension, so a conformant handle de-dupes a deliberate
649
+ // re-attempt at the same number. (Not stranding without a charge
650
+ // is the prep branch above; not double-charging is here.)
620
651
  var refreshed = await _tickAdvance(enrollment, policy, schedule, now);
621
652
  advanced.push(refreshed);
622
653
  }
package/lib/pick-lists.js CHANGED
@@ -548,31 +548,69 @@ function create(opts) {
548
548
  }
549
549
  perOrder[oid].push(list.lines[k]);
550
550
  }
551
- var shipments = [];
552
- for (var m = 0; m < orderSeq.length; m += 1) {
553
- var ord = orderSeq[m];
554
- // A picked-from-shelf parcel has no carrier yet the operator
555
- // assigns one when they hand it off. orderTracking's carrier enum
556
- // doesn't carry a "pickup" / "none" value, so the parcel rides the
557
- // 'other' escape hatch with a "pickup" label until a real carrier
558
- // is recorded against it (the operator updates the shipment, or a
559
- // shipping-label record supplies the carrier).
560
- var s = await orderTracking.createShipment({
561
- order_id: ord,
562
- carrier: "other",
563
- carrier_other_name: "pickup",
564
- notes: "pick-list:" + listId,
565
- });
566
- shipments.push({
567
- order_id: ord,
568
- shipment_id: s.id,
569
- });
570
- }
551
+
552
+ // Atomically claim completion BEFORE fanning out any shipment.
553
+ // The JS status check above is necessary (it produces the
554
+ // operator-facing "list is <status>" refusal) but NOT sufficient:
555
+ // two concurrent markListComplete callers both read 'in_progress'
556
+ // and would each run the createShipment loop, double-creating one
557
+ // shipment per parent order. The conditional UPDATE guarded by
558
+ // the same precondition in its own WHERE — is the atomic claim
559
+ // (SQLite/D1 serializes writers, so exactly one UPDATE matches a
560
+ // row in an eligible state). The loser sees rowCount===0 and
561
+ // refuses; only the winner proceeds to createShipment.
571
562
  var ts = _now();
572
- await query(
573
- "UPDATE pick_lists SET status = 'complete', completed_at = ?1 WHERE id = ?2",
563
+ var claim = await query(
564
+ "UPDATE pick_lists SET status = 'complete', completed_at = ?1 " +
565
+ "WHERE id = ?2 AND status IN ('generated', 'in_progress')",
574
566
  [ts, listId],
575
567
  );
568
+ if (Number(claim.rowCount || 0) !== 1) {
569
+ // Lost the race (or the row left an eligible state between the
570
+ // read and the claim). Surface the same terminal-state refusal
571
+ // a sequential caller would see — the shipments belong to the
572
+ // caller that won the claim.
573
+ throw new TypeError("pick-lists.markListComplete: list is no longer " +
574
+ "generated or in_progress (already completed or cancelled by a concurrent caller)");
575
+ }
576
+
577
+ var shipments = [];
578
+ try {
579
+ for (var m = 0; m < orderSeq.length; m += 1) {
580
+ var ord = orderSeq[m];
581
+ // A picked-from-shelf parcel has no carrier yet — the operator
582
+ // assigns one when they hand it off. orderTracking's carrier enum
583
+ // doesn't carry a "pickup" / "none" value, so the parcel rides the
584
+ // 'other' escape hatch with a "pickup" label until a real carrier
585
+ // is recorded against it (the operator updates the shipment, or a
586
+ // shipping-label record supplies the carrier).
587
+ var s = await orderTracking.createShipment({
588
+ order_id: ord,
589
+ carrier: "other",
590
+ carrier_other_name: "pickup",
591
+ notes: "pick-list:" + listId,
592
+ });
593
+ shipments.push({
594
+ order_id: ord,
595
+ shipment_id: s.id,
596
+ });
597
+ }
598
+ } catch (e) {
599
+ // The side-effect threw after the claim landed. Revert the claim
600
+ // (self-targeting WHERE so we only undo a row WE moved to
601
+ // 'complete') so the list isn't stranded terminal with a
602
+ // partial / zero shipment fan-out — the operator can retry once
603
+ // the createShipment fault clears.
604
+ try {
605
+ await query(
606
+ "UPDATE pick_lists SET status = ?1, completed_at = NULL " +
607
+ "WHERE id = ?2 AND status = 'complete'",
608
+ [list.status, listId],
609
+ );
610
+ } catch (_e) { /* drop-silent — the original createShipment error is what the operator needs */ }
611
+ throw e;
612
+ }
613
+
576
614
  var hydrated = await _getHydrated(listId);
577
615
  hydrated.shipments = shipments;
578
616
  return hydrated;