LCOV - code coverage report
Current view: top level - matchscore/application/advancement - reconcile.clj Coverage Total Hit
Test: lcov.info Lines: 89.0 % 693 617
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.application.advancement.reconcile
       2              :   "Recomputes advancements for the stage owning a recently-changed match.
       3              :    For each wildcard advancement rule on the stage, determines which
       4              :    participants are mathematically locked into their required rank. Ties
       5              :    are settled by the current standings order only after every compared
       6              :    participant has finished their matches. Diffs the desired state against
       7              :    existing advancements: promotes new ones and revokes the ones whose lock
       8              :    no longer holds."
       9              :   (:require
      10              :    [cats.core :as c]
      11              :    [cats.monad.either :as either]
      12              :    [clojure.set :as set]
      13              :    [matchscore.application.advancement.bracket-reconcile :as bracket-reconcile]
      14              :    [matchscore.application.advancement.bye :as bye]
      15              :    [matchscore.application.advancement.common :as common]
      16              :    [matchscore.application.group-participants.sync-matches :as sync-matches]
      17              :    [matchscore.application.stage.helpers :as stage-helpers]
      18              :    [matchscore.domain.advancement-rule.repository.postgres :as advancement-rule-repo]
      19              :    [matchscore.domain.advancement.repository.postgres :as advancement-repo]
      20              :    [matchscore.domain.bracket-match-slot.repository.postgres :as bms-repo]
      21              :    [matchscore.domain.draw.repository.postgres :as draw-repo]
      22              :    [matchscore.domain.group-participant.repository.postgres :as gp-repo]
      23              :    [matchscore.domain.group.repository.postgres :as group-repo]
      24              :    [matchscore.domain.match.repository.postgres :as match-repo]
      25              :    [matchscore.utils.errors :as utils.errors]
      26              :    [next.jdbc :as jdbc]
      27              :    [next.jdbc.result-set :as rs]
      28              :    [taoensso.telemere :as t]))
      29              : 
      30              : 
      31              : ;; ---------------------------------------------------------------------------
      32              : ;; Lock detection
      33              : ;; ---------------------------------------------------------------------------
      34              : 
      35              : 
      36            4 : (defn lock-window
      37              :  "Returns [lock-from lock-to] (1-based, inclusive) — the tightest rank
      38              :    range pid is guaranteed to finish within, regardless of future results.
      39              :    Uses worst-case win bounds while matches remain. When both compared
      40              :    participants are finished, their order in :ranked-participants is final
      41              :    because wins and set difference can no longer change. Conservative —
      42              :    never says 'locked' when the rank could move."
      43              :  [{:keys [participants ranked-participants wins-by-pid remaining-by-pid]} pid]
      44           15 :  (let [participants (filterv :participant-id participants) ; ignore empty/TBD slots
      45            9 :        pid-str      (str pid)
      46            6 :        n            (count participants)
      47              :        ;; Standings sort (wins, set difference, then slot) is authoritative
      48              :        ;; only after both compared participants have finished their matches.
      49           15 :        rank-by-pid  (zipmap ranked-participants (range))
      50            9 :        rank-p       (get rank-by-pid pid)
      51           12 :        w-p          (get wins-by-pid pid-str 0)
      52           12 :        r-p          (get remaining-by-pid pid-str 0)
      53            9 :        max-p        (+ w-p r-p)
      54           27 :        others       (remove #(= pid (:participant-id %)) participants)
      55            3 :        above-cnt    (count
      56            6 :                      (filter
      57            3 :                       (fn [q]
      58           12 :                        (let [q-id   (:participant-id q)
      59           18 :                              w-q    (get wins-by-pid (str q-id) 0)
      60           18 :                              r-q    (get remaining-by-pid (str q-id) 0)
      61            9 :                              rank-q (get rank-by-pid q-id)]
      62           62 :                          (or (> w-q max-p) (and (zero? r-p) (zero? r-q) (< rank-q rank-p)))))
      63            3 :                       others))
      64            3 :        below-cnt    (count
      65            6 :                      (filter
      66            3 :                       (fn [q]
      67           12 :                        (let [q-id   (:participant-id q)
      68           18 :                              w-q    (get wins-by-pid (str q-id) 0)
      69           18 :                              r-q    (get remaining-by-pid (str q-id) 0)
      70            9 :                              max-q  (+ w-q r-q)
      71            9 :                              rank-q (get rank-by-pid q-id)]
      72           62 :                          (or (< max-q w-p) (and (zero? r-p) (zero? r-q) (> rank-q rank-p)))))
      73            3 :                       others))]
      74           18 :    [(inc above-cnt) (- n below-cnt)]))
      75              : 
      76              : 
      77            4 : (defn locked-at?
      78              :  "True iff pid is mathematically locked at exactly rank in its group."
      79              :  [ranked-group pid rank]
      80           15 :  (let [[lock-from lock-to] (lock-window ranked-group pid)]
      81           28 :    (and (= lock-from rank) (= lock-to rank))))
      82              : 
      83              : 
      84              : ;; ---------------------------------------------------------------------------
      85              : ;; Desired-state per rule
      86              : ;; ---------------------------------------------------------------------------
      87              : 
      88              : 
      89            4 : (defn- locked-candidate-at-rank
      90              :   "If the participant currently at 1-based rank R in the ranked group is
      91              :    locked at R, returns their participant-id. Otherwise nil."
      92              :   [ranked-group rank]
      93            6 :   (let [{:keys [ranked-participants]} ranked-group
      94           15 :         pid (nth ranked-participants (dec rank) nil)]
      95           37 :     (when (and pid (locked-at? ranked-group pid rank)) pid)))
      96              : 
      97              : 
      98            4 : (defn- rank-pending?
      99              :   "True when a real participant occupies this group slot (so it's
     100              :    structurally possible for this rank to eventually promote someone) but
     101              :    isn't locked there yet — more results could still change who ends up at
     102              :    this rank. False either when nobody occupies the slot at all (the group
     103              :    is too small to ever reach this rank — permanently empty) or when the
     104              :    occupant is already locked (settled). Used to tell 'still waiting on
     105              :    results' apart from 'permanently a bye', independent of whether every
     106              :    match in the group has been played — a group can have irrelevant
     107              :    unplayed matches (ones that can no longer change any rank) forever."
     108              :   [ranked-group rank]
     109            6 :   (let [{:keys [ranked-participants]} ranked-group
     110           15 :         pid (nth ranked-participants (dec rank) nil)]
     111           40 :     (and (some? pid) (not (locked-at? ranked-group pid rank)))))
     112              : 
     113              : 
     114            4 : (defn- desired-for-rank-range-by-group-rank
     115              :   "Returns {:target-kind :group :target-group-id ... :candidates [{:participant-id pid}]}
     116              :    or nil if the rule's target group cannot be found."
     117              :   [repos rule ranked-groups]
     118            2 :   (let [{:keys [rank-from target-draw-id extra]} rule
     119            3 :         target-group-order (:group-by-rank extra)
     120            6 :         all-target-groups  (group-repo/find-by-draw-id (:group-postgres-repo repos) target-draw-id)
     121           12 :         target-group       (some #(when (= target-group-order (:order %)) %) all-target-groups)]
     122            3 :     (when target-group
     123            6 :       {:target-kind     :group
     124            1 :        :target-draw-id  target-draw-id
     125            3 :        :target-group-id (:uuid target-group)
     126            2 :        :candidates      (mapv
     127            1 :                          (fn [pid]
     128            3 :                           {:participant-id pid})
     129            8 :                          (keep #(locked-candidate-at-rank % rank-from) ranked-groups))})))
     130              : 
     131              : 
     132            4 : (defn- desired-for-rank-range-by-draw-rank
     133              :   "groups_monrad all-places: rank_range rule where each rule targets its own
     134              :    bracket draw (one draw per place). Seeds the participants locked at rank-from
     135              :    in each source group into seeds 1..N of the target bracket — one per group."
     136              :   [rule ranked-groups]
     137            2 :   (let [{:keys [rank-from target-draw-id]} rule]
     138            3 :     (when rank-from
     139            3 :       (let [candidates (keep-indexed
     140            1 :                         (fn [idx rg]
     141           10 :                          (when-let [pid (locked-candidate-at-rank rg rank-from)]
     142            4 :                            {:participant-id pid
     143            2 :                             :assigned-seed  (inc idx)}))
     144            1 :                         ranked-groups)]
     145            5 :         {:target-kind    :bracket
     146            1 :          :target-draw-id target-draw-id
     147            3 :          :candidates     (vec candidates)}))))
     148              : 
     149              : 
     150            4 : (defn- desired-for-top-n
     151              :   "Returns {:target-kind :bracket :candidates [{:participant-id ...
     152              :    :assigned-seed N}]} — interleaved seeds matching place-in-target-bracket!.
     153              :    Each (rank, group) position is included only if that participant is
     154              :    locked at that exact rank in their group."
     155              :   [rule ranked-groups]
     156            4 :   (let [{:keys [take target-draw-id]} rule
     157            6 :         groups (vec ranked-groups)
     158            4 :         ng     (count groups)]
     159           10 :     {:target-kind    :bracket
     160            2 :      :target-draw-id target-draw-id
     161            4 :      :candidates     (vec
     162          134 :                       (for [r      (range take)
     163            8 :                             [g rg] (map-indexed vector groups)
     164           10 :                             :let   [pid (locked-candidate-at-rank rg (inc r))]
     165            2 :                             :when  pid]
     166            8 :                         {:participant-id pid
     167           10 :                          :assigned-seed  (common/top-n-seed ng r g)}))}))
     168              : 
     169              : 
     170            4 : (defn- desired-for-top-n-source-group
     171              :   "top_n on a single source group → target bracket. Seeds start at
     172              :    target-seed (defaulting to 1) and increment by rank. A candidate
     173              :    qualifies iff its rank within the source group is mathematically
     174              :    locked at that exact rank."
     175              :   [rule ranked-group]
     176            2 :   (let [{:keys [take target-draw-id target-seed]} rule
     177            6 :         seed-base (or target-seed 1)]
     178            5 :     {:target-kind    :bracket
     179            1 :      :target-draw-id target-draw-id
     180            2 :      :candidates     (vec
     181           33 :                       (for [r     (range take)
     182            5 :                             :let  [pid (locked-candidate-at-rank ranked-group (inc r))]
     183            1 :                             :when pid]
     184            4 :                         {:participant-id pid
     185            3 :                          :assigned-seed  (+ seed-base r)}))}))
     186              : 
     187              : 
     188            4 : (defn- desired-for-rank-range-source-group
     189              :   "rank_range on a single source group with explicit target-group-id and
     190              :    target-slot → places the participant at rank-from into target-slot of
     191              :    target group. Expects rank-from = rank-to (or rank-to nil) — single
     192              :    placement. Returns nil if target-group-id or target-slot is missing."
     193              :   [rule ranked-group]
     194            2 :   (let [{:keys [rank-from target-draw-id target-group-id target-slot]} rule]
     195           11 :     (when (and target-group-id target-slot rank-from)
     196            5 :       (let [pid (locked-candidate-at-rank ranked-group rank-from)]
     197            6 :         {:target-kind     :group
     198            1 :          :target-draw-id  target-draw-id
     199            1 :          :target-group-id target-group-id
     200            2 :          :candidates      (if pid
     201            5 :                             [{:participant-id pid
     202            1 :                               :assigned-slot  target-slot}]
     203            0 :                             [])}))))
     204              : 
     205              : 
     206            4 : (defn- desired-for-rank-range-source-group-to-group
     207              :   "rank_range on a single source group into a target group without an
     208              :    explicit target-slot (see common/rank-range-to-group?) — places
     209              :    rank-from..rank-to into the target group's slots in order (see
     210              :    common/rank-range-target-group-slots). Only ranks whose occupant is
     211              :    locked become candidates."
     212              :   [repos rule ranked-group]
     213            2 :   (let [{:keys [target-draw-id target-group-id]} rule]
     214            6 :     {:target-kind     :group
     215            1 :      :target-draw-id  target-draw-id
     216            1 :      :target-group-id target-group-id
     217            2 :      :candidates      (vec
     218           33 :                        (for [[rank slot] (sort-by
     219            1 :                                           key
     220            4 :                                           (common/rank-range-target-group-slots repos rule))
     221            4 :                              :let        [pid (locked-candidate-at-rank ranked-group rank)]
     222            1 :                              :when       pid]
     223            4 :                          {:participant-id pid
     224            1 :                           :assigned-slot  slot}))}))
     225              : 
     226              : 
     227            4 : (defn- desired-for-rank-range-source-group-bracket
     228              :   "rank_range on a single source group targeting a bracket draw (a \"position\"
     229              :    rule that advances places rank-from..rank-to of one group into a shared
     230              :    placement bracket). Seeds the participants locked at each rank in
     231              :    rank-from..rank-to into the target bracket.
     232              : 
     233              :    Seeding is place-then-group across num-groups so that (a) sibling per-group
     234              :    rules sharing one target draw never collide on seeds, and (b) the two
     235              :    finishers of a single group land num-groups seeds apart rather than in
     236              :    adjacent seeds — keeping group-mates out of the same round-1 match:
     237              :      seed = (rank - rank-from) * num-groups + (group-order - 1) + 1
     238              :    i.e. all rank-from finishers fill the first num-groups seeds (one per
     239              :    group), all rank-from+1 finishers the next num-groups seeds, etc. Ranks
     240              :    with no locked participant (e.g. place 4 in a 3-player group) are simply
     241              :    skipped, leaving their seed slot as TBD."
     242              :   [rule ranked-group num-groups]
     243            2 :   (let [{:keys [rank-from rank-to target-draw-id]} rule
     244            5 :         rank-to   (or rank-to rank-from)
     245           10 :         group-ord (or (get-in ranked-group [:group :order]) 1)]
     246            3 :     (when rank-from
     247            5 :       {:target-kind    :bracket
     248            1 :        :target-draw-id target-draw-id
     249            2 :        :candidates     (vec
     250           36 :                         (for [rank  (range rank-from (inc rank-to))
     251            4 :                               :let  [pid (locked-candidate-at-rank ranked-group rank)]
     252            1 :                               :when pid]
     253            4 :                           {:participant-id pid
     254            2 :                            :assigned-seed  (common/rank-range-bracket-seed
     255            1 :                                             num-groups
     256            1 :                                             rank-from
     257            1 :                                             group-ord
     258            1 :                                             rank)}))})))
     259              : 
     260              : 
     261            4 : (defn- desired-for-rank-range-source-group-pinned-seed
     262              :   "rank_range on a single source group with an explicit target-seed (no
     263              :    target-group-id/target-slot) — a hand-pinned or decomposed single-rank
     264              :    rule. target-seed is already the final physical bracket seed (the
     265              :    director's literal choice, or a decompose operation's pre-resolved
     266              :    physical seed), so unlike the batch branches this bypasses distribution
     267              :    remap entirely (see :pre-mapped? handling in remap-bracket-seeds)."
     268              :   [rule ranked-group]
     269            4 :   (let [{:keys [rank-from target-draw-id target-seed]} rule]
     270           14 :     (when (and rank-from target-seed)
     271           10 :       (let [pid (locked-candidate-at-rank ranked-group rank-from)]
     272           14 :         {:target-kind    :bracket
     273            2 :          :target-draw-id target-draw-id
     274              :          :pre-mapped?    true
     275            4 :          :candidates     (if pid
     276           10 :                            [{:participant-id pid
     277            2 :                              :assigned-seed  target-seed}]
     278            1 :                            [])}))))
     279              : 
     280              : 
     281            4 : (defn- remap-bracket-seeds
     282              :   "When the rule targets a bracket, remaps each candidate's logical
     283              :    place-then-group :assigned-seed to its physical seed/slot in the target
     284              :    bracket, per the rule's distribution ('by_place' spread or 'standard'
     285              :    mirror — both handled by common/apply-distribution-seed). Skipped when
     286              :    the desired map is already :pre-mapped? — its :assigned-seed is already a
     287              :    final physical seed (e.g. a hand-pinned or decomposed single-rank rule),
     288              :    and running it through distribution remap again would corrupt it."
     289              :   [repos rule desired]
     290           55 :   (if (and desired (= :bracket (:target-kind desired)) (not (:pre-mapped? desired)))
     291           14 :     (let [m (common/target-bracket-size repos (:target-draw-id desired))]
     292            6 :       (update
     293            2 :        desired
     294              :        :candidates
     295            2 :        (fn [candidates]
     296            4 :         (mapv
     297            2 :          (fn
     298              :           [{:keys [assigned-seed]
     299              :             :as   candidate}]
     300            4 :           (if assigned-seed
     301           18 :             (assoc candidate :assigned-seed (common/apply-distribution-seed rule m assigned-seed))
     302            0 :             candidate))
     303            2 :          candidates))))
     304            2 :     desired))
     305              : 
     306              : 
     307            4 : (defn- rule-desired
     308              :   "Dispatches the rule to its desired-state computation. Returns a map
     309              :    with :target-kind and :candidates, or nil if the rule shape is not
     310              :    handled here."
     311              :   [repos rule ranked-groups]
     312            6 :   (let [{:keys [selector-type extra source-group-id]} rule
     313            9 :         ranked-group (first ranked-groups)
     314              :         desired
     315           41 :         (cond (and (= selector-type "rank_range") (contains? extra :group-by-rank))
     316            5 :               (desired-for-rank-range-by-group-rank repos rule ranked-groups)
     317              : 
     318           28 :               (and (= selector-type "rank_range") (contains? extra :draw-by-rank))
     319            4 :               (desired-for-rank-range-by-draw-rank rule ranked-groups)
     320              : 
     321           30 :               (and (= selector-type "rank_range") source-group-id ranked-group)
     322           23 :               (cond (and (:target-group-id rule) (:target-slot rule))
     323            4 :                     (desired-for-rank-range-source-group rule ranked-group)
     324              : 
     325            6 :                     (:target-seed rule)
     326            8 :                     (desired-for-rank-range-source-group-pinned-seed rule ranked-group)
     327              : 
     328            3 :                     (:target-group-id rule)
     329            5 :                     (desired-for-rank-range-source-group-to-group repos rule ranked-group)
     330              : 
     331              :                     :else
     332            3 :                     (let [num-groups (max
     333              :                                       1
     334            1 :                                       (count
     335            2 :                                        (group-repo/find-by-draw-id
     336            3 :                                         (:group-postgres-repo repos)
     337            6 :                                         (get-in ranked-group [:group :draw-id]))))]
     338            5 :                       (desired-for-rank-range-source-group-bracket rule ranked-group num-groups)))
     339              : 
     340           23 :               (and (= selector-type "top_n") source-group-id ranked-group)
     341            4 :               (desired-for-top-n-source-group rule ranked-group)
     342              : 
     343           14 :               (= selector-type "top_n") (desired-for-top-n rule ranked-groups))]
     344           15 :     (remap-bracket-seeds repos rule desired)))
     345              : 
     346              : 
     347              : ;; ---------------------------------------------------------------------------
     348              : ;; Diff (per-rule) → {:to-add ... :to-keep ... :to-remove ...}
     349              : ;; ---------------------------------------------------------------------------
     350              : 
     351              : 
     352            4 : (defn- placement-changed?
     353              :   "True when the desired candidate pins a placement (seed or slot) that differs
     354              :    from the existing advancement's. Candidates that don't pin a placement — e.g.
     355              :    group-by-rank, which fills empty slots dynamically — never count as changed,
     356              :    preserving identity-only semantics for them. Lets a re-seed (such as switching
     357              :    a rule to the 'standard' distribution) surface as a move rather than a no-op."
     358              :   [desired-candidate existing]
     359            9 :   (or
     360            5 :    (and
     361            3 :     (:assigned-seed desired-candidate)
     362            7 :     (not= (:assigned-seed desired-candidate) (:assigned-seed existing)))
     363              :    (and
     364            3 :     (:assigned-slot desired-candidate)
     365            7 :     (not= (:assigned-slot desired-candidate) (:assigned-slot existing)))))
     366              : 
     367              : 
     368            4 : (defn- diff-rule
     369              :   "Given desired candidates and existing advancement records for a rule,
     370              :    returns {:to-add [candidate ...] :to-remove [advancement ...] :to-keep [...]}.
     371              :    Diff keyed by participant-id, except a participant whose pinned placement
     372              :    (seed/slot) changed is treated as a move: removed at its old placement and
     373              :    re-added at the new one."
     374              :   [desired existing]
     375           12 :   (let [existing-by-pid (reduce
     376            4 :                          (fn [m a]
     377           18 :                           (assoc m (str (:participant-id a)) a))
     378            4 :                          {}
     379            4 :                          existing)
     380            8 :         desired-by-pid  (reduce
     381            4 :                          (fn [m d]
     382           36 :                           (assoc m (str (:participant-id d)) d))
     383            4 :                          {}
     384            4 :                          desired)
     385           20 :         desired-pids    (set (keys desired-by-pid))
     386           20 :         existing-pids   (set (keys existing-by-pid))
     387           16 :         common-pids     (set/intersection desired-pids existing-pids)
     388            8 :         moved-pids      (into
     389            4 :                          #{}
     390            8 :                          (filter
     391            4 :                           (fn [pid]
     392            8 :                            (placement-changed? (desired-by-pid pid) (existing-by-pid pid))))
     393            4 :                          common-pids)
     394           16 :         keep-pids       (set/difference common-pids moved-pids)
     395           28 :         add-pids        (set/union (set/difference desired-pids existing-pids) moved-pids)
     396           28 :         remove-pids     (set/union (set/difference existing-pids desired-pids) moved-pids)]
     397           48 :     {:to-add    (filterv (comp add-pids str :participant-id) desired)
     398           16 :      :to-remove (mapv existing-by-pid remove-pids)
     399           16 :      :to-keep   (mapv existing-by-pid keep-pids)}))
     400              : 
     401              : 
     402              : ;; ---------------------------------------------------------------------------
     403              : ;; Apply: revoke + promote
     404              : ;; ---------------------------------------------------------------------------
     405              : 
     406              : 
     407            4 : (defn- update-match-for-slot!
     408              :   "Updates only home (slot=1) or away (slot=2) participant on all matches
     409              :    linked to a bracket match. participant-id nil clears the field."
     410              :   [repos bracket-match-id slot-number participant-id]
     411            8 :   (match-repo/update-bracket-slot-participant!
     412           12 :    (:match-postgres-repo repos)
     413            4 :    bracket-match-id
     414            4 :    slot-number
     415            4 :    participant-id))
     416              : 
     417              : 
     418            4 : (defn- revoke-group-advancement!
     419              :   "Clears the group_participant slot the advancement points at."
     420              :   [repos {:keys [to-group-id assigned-slot]}]
     421            4 :   (let [gp-repo-impl (:group-participant-postgres-repo repos)
     422            1 :         slot         assigned-slot
     423            4 :         gps          (gp-repo/find-by-group-id gp-repo-impl to-group-id)
     424           12 :         target-gp    (some #(when (= slot (:slot %)) %) gps)]
     425           12 :     (when target-gp (gp-repo/bulk-upsert! gp-repo-impl [(assoc target-gp :participant-id nil)]))))
     426              : 
     427              : 
     428            4 : (def ^:private empty-bracket-diff
     429           16 :   {:bracket-promoted []
     430            4 :    :bracket-revoked  []})
     431              : 
     432              : 
     433            4 : (defn- revoke-bracket-advancement!
     434              :   "Restores the bracket_match_slot whose participant is the advancee
     435              :    back to a 'seed' source-type carrying its original source-seed, resets
     436              :    that bracket_match's results, and cascades the now-unresolved outcome
     437              :    to every later round that took its winner/loser. Returns
     438              :    {:bracket-promoted [...] :bracket-revoked [...]} slot summaries."
     439              :   [repos {:keys [participant-id to-bracket-match-id assigned-seed]}]
     440            8 :   (let [bms-repo-impl (:bracket-match-slot-postgres-repo repos)
     441            8 :         slots         (bms-repo/find-by-bracket-match-id bms-repo-impl to-bracket-match-id)
     442           32 :         target-slot   (some #(when (= (str (:participant-id %)) (str participant-id)) %) slots)]
     443            6 :     (when target-slot
     444            4 :       (bms-repo/upsert!
     445            2 :        bms-repo-impl
     446           16 :        (assoc target-slot
     447              :         :participant-id nil
     448              :         :source-type    "seed"
     449            2 :         :source-seed    assigned-seed))
     450           16 :       (update-match-for-slot! repos to-bracket-match-id (:slot target-slot) nil)
     451            8 :       (common/reset-bracket-match-results! repos to-bracket-match-id)
     452            2 :       (let [{:keys [promoted revoked]}
     453            8 :             (bracket-reconcile/propagate-from-bracket-match! repos to-bracket-match-id)]
     454            8 :         {:bracket-promoted promoted
     455            2 :          :bracket-revoked  revoked}))))
     456              : 
     457              : 
     458            4 : (defn- merge-bracket-diffs
     459              :   [a b]
     460           22 :   {:bracket-promoted (into (:bracket-promoted a) (:bracket-promoted b))
     461           16 :    :bracket-revoked  (into (:bracket-revoked a) (:bracket-revoked b))})
     462              : 
     463              : 
     464            4 : (defn- revoke!
     465              :   "Revokes the given advancements and deletes their rows. Returns the
     466              :    bracket slot changes cascaded from revoked bracket seeds as
     467              :    {:bracket-promoted [...] :bracket-revoked [...]}."
     468              :   [repos to-remove]
     469           12 :   (let [cascade (reduce
     470            4 :                  (fn [acc adv]
     471           16 :                   (cond (:to-group-id adv) (do (revoke-group-advancement! repos adv) acc)
     472              : 
     473            6 :                         (:to-bracket-match-id adv)
     474           14 :                         (merge-bracket-diffs acc (revoke-bracket-advancement! repos adv))
     475              : 
     476            0 :                         :else acc))
     477            4 :                  empty-bracket-diff
     478            4 :                  to-remove)
     479           28 :         ids     (mapv (comp str :uuid) to-remove)]
     480           24 :     (advancement-repo/delete-by-ids! (:advancement-postgres-repo repos) ids)
     481            4 :     cascade))
     482              : 
     483              : 
     484            4 : (defn- save-advancements!
     485              :   "Constructs and bulk-inserts advancement records, returning an Either."
     486              :   [repos rule-id target-draw-id placements]
     487           24 :   (let [records         (common/make-advancement-records rule-id target-draw-id placements)
     488           24 :         [ok? saved err] (advancement-repo/bulk-insert! (:advancement-postgres-repo repos) records)]
     489            8 :     (if ok?
     490           12 :       (either/right saved)
     491            0 :       (either/left
     492            0 :        (utils.errors/build-error
     493              :         :database
     494            0 :         {:code    :error.advancement-reconcile/insert-failed
     495            0 :          :message err})))))
     496              : 
     497              : 
     498            4 : (defn- promote-group-explicit-slots!
     499              :   "Places each to-add candidate at its declared :assigned-slot in the
     500              :    target group, then writes advancement rows. Used by source-group
     501              :    rank_range rules that pin a participant to a specific slot."
     502              :   [repos rule target-group-id target-draw-id to-add]
     503            3 :   (let [results (mapv
     504            1 :                  (fn [{:keys [participant-id assigned-slot]}]
     505            2 :                   [participant-id
     506            1 :                    assigned-slot
     507            2 :                    (common/place-in-target-group-at-slot!
     508            1 :                     repos
     509            1 :                     target-group-id
     510            1 :                     assigned-slot
     511            1 :                     participant-id)])
     512            1 :                  to-add)
     513            2 :         failed  (some
     514            1 :                  (fn [[_ _ [ok?] :as r]]
     515            3 :                   (when-not ok? r))
     516            1 :                  results)]
     517            2 :     (if failed
     518            0 :       (either/left
     519            0 :        (utils.errors/build-error
     520              :         :database
     521            0 :         {:code    :error.advancement-reconcile/place-group-failed
     522            0 :          :message (let [[_ _ [_ _ err]] failed] err)}))
     523            3 :       (let [placements (mapv
     524            1 :                         (fn [[pid slot _]]
     525            5 :                          {:participant-id pid
     526            1 :                           :to-group-id    target-group-id
     527            1 :                           :assigned-slot  slot})
     528            1 :                         results)]
     529            8 :         (save-advancements! repos (:uuid rule) target-draw-id placements)))))
     530              : 
     531              : 
     532            4 : (defn- promote-group!
     533              :   "Places the to-add participants into the target group and writes
     534              :    advancement rows. If candidates carry :assigned-slot, places at those
     535              :    explicit slots; otherwise fills empty slots sequentially. Returns
     536              :    Either<Error, [advancement ...]>."
     537              :   [repos rule {:keys [target-group-id target-draw-id]} to-add]
     538            8 :   (if (empty? to-add)
     539            3 :     (either/right [])
     540           10 :     (if (some :assigned-slot to-add)
     541            7 :       (promote-group-explicit-slots! repos rule target-group-id target-draw-id to-add)
     542           10 :       (let [pids (mapv :participant-id to-add)
     543           10 :             [ok? _ err placed-gps] (common/place-in-target-group! repos target-group-id pids)]
     544            8 :         (if-not ok?
     545            2 :           (either/left
     546            3 :            (utils.errors/build-error
     547              :             :database
     548            4 :             {:code    :error.advancement-reconcile/place-group-failed
     549            1 :              :message err}))
     550            6 :           (let [placements (mapv
     551            2 :                             (fn [pid gp]
     552           10 :                              {:participant-id pid
     553            2 :                               :to-group-id    target-group-id
     554            6 :                               :assigned-slot  (:slot gp)})
     555            2 :                             pids
     556            2 :                             placed-gps)]
     557           16 :             (save-advancements! repos (:uuid rule) target-draw-id placements)))))))
     558              : 
     559              : 
     560            4 : (defn- classify-bracket-candidate
     561              :   "Resolves a candidate against the target bracket's round-1 slots and
     562              :    returns one of:
     563              :      {:kind :place     :slot <seed-slot>}    — empty seed slot to fill
     564              :      {:kind :idempotent :slot <slot>}        — already holds the desired pid
     565              :      {:kind :conflict   :slot <slot>}        — slot occupied by someone else
     566              :      {:kind :missing}                        — no slot at this seed at all"
     567              :   [slots-by-seed {:keys [participant-id assigned-seed]}]
     568           16 :   (let [slot (get slots-by-seed assigned-seed)]
     569           29 :     (cond (nil? slot) {:kind :missing}
     570              : 
     571           20 :           (= "seed" (:source-type slot))
     572           16 :           {:kind :place
     573            4 :            :slot slot}
     574              : 
     575            9 :           (= (str (:participant-id slot)) (str participant-id))
     576            4 :           {:kind :idempotent
     577            1 :            :slot slot}
     578              : 
     579              :           :else
     580            4 :           {:kind :conflict
     581            1 :            :slot slot})))
     582              : 
     583              : 
     584            4 : (defn- promote-bracket!
     585              :   "Places each to-add candidate at its assigned-seed in the target
     586              :    bracket-draw's round-1 slots, then writes advancement rows.
     587              : 
     588              :    Tolerates partial state: missing or conflicting seed slots are logged
     589              :    and skipped (rather than failing the whole rule). A slot that already
     590              :    carries the desired participant is treated as idempotent — we record
     591              :    the advancement without re-upserting the slot."
     592              :   [repos rule {:keys [target-draw-id]} to-add]
     593           16 :   (if (empty? to-add)
     594            6 :     (either/right [])
     595           12 :     (let [slots-by-seed (into
     596            4 :                          {}
     597            8 :                          (keep
     598            4 :                           (fn [s]
     599           48 :                            (when-let [seed (:source-seed s)] [seed s])))
     600           16 :                          (common/find-round1-slots repos target-draw-id))
     601            8 :           classified    (mapv
     602            4 :                          (fn [cand]
     603           32 :                           (assoc (classify-bracket-candidate slots-by-seed cand) :candidate cand))
     604            4 :                          to-add)
     605           36 :           to-place      (filter #(= :place (:kind %)) classified)
     606           36 :           idempotent    (filter #(= :idempotent (:kind %)) classified)
     607           36 :           missing       (filter #(= :missing (:kind %)) classified)
     608           36 :           conflicts     (filter #(= :conflict (:kind %)) classified)]
     609           68 :       (doseq [{:keys [candidate]} missing]
     610            0 :         (t/log!
     611              :          :warn
     612            0 :          {:message        "advancement reconcile: target seed slot not found; skipping"
     613            0 :           :rule-id        (str (:uuid rule))
     614            0 :           :assigned-seed  (:assigned-seed candidate)
     615            0 :           :participant-id (str (:participant-id candidate))}))
     616           68 :       (doseq [{:keys [candidate slot]} conflicts]
     617            0 :         (t/log!
     618              :          :warn
     619            0 :          {:message
     620              :           "advancement reconcile: target seed slot occupied by a different participant; skipping"
     621            0 :           :rule-id (str (:uuid rule))
     622            0 :           :assigned-seed (:assigned-seed candidate)
     623            0 :           :wanted-pid (str (:participant-id candidate))
     624            0 :           :occupant-pid (str (:participant-id slot))}))
     625           12 :       (let [results (mapv
     626            4 :                      (fn [{:keys [candidate slot]}]
     627            8 :                       (bms-repo/upsert!
     628           12 :                        (:bracket-match-slot-postgres-repo repos)
     629           32 :                        (assoc slot
     630           12 :                         :participant-id (:participant-id candidate)
     631              :                         :source-type    "explicit_participant"
     632              :                         :source-seed    nil)))
     633            4 :                      to-place)
     634            8 :             failed  (first
     635            8 :                      (filter
     636            4 :                       (fn [[ok?]]
     637           12 :                        (not ok?))
     638            4 :                       results))]
     639            8 :         (if failed
     640            0 :           (either/left
     641            0 :            (utils.errors/build-error
     642              :             :database
     643            0 :             {:code    :error.advancement-reconcile/place-bracket-failed
     644            0 :              :message (last failed)}))
     645            4 :           (do
     646          116 :             (doseq [{:keys [candidate slot]} (concat to-place idempotent)]
     647            8 :               (update-match-for-slot!
     648            4 :                repos
     649           12 :                (:bracket-match-id slot)
     650           12 :                (:slot slot)
     651           12 :                (:participant-id candidate)))
     652           12 :             (let [placements (mapv
     653            4 :                               (fn [{:keys [candidate slot]}]
     654           28 :                                {:participant-id      (:participant-id candidate)
     655           12 :                                 :to-bracket-match-id (:bracket-match-id slot)
     656           12 :                                 :assigned-seed       (:assigned-seed candidate)})
     657           16 :                               (concat to-place idempotent))]
     658           32 :               (save-advancements! repos (:uuid rule) target-draw-id placements))))))))
     659              : 
     660              : 
     661              : ;; ---------------------------------------------------------------------------
     662              : ;; Resolution helpers
     663              : ;; ---------------------------------------------------------------------------
     664              : 
     665              : 
     666            4 : (defn- resolve-match-group-context
     667              :   "Returns Either<Error, {:stage-uuid ... :group-uuid ... :draw-uuid ...}>.
     668              :    Lefts if match not found, not a group match, or group/draw/stage link is missing.
     669              :    stage-uuid is read from match.stage-id when present, otherwise resolved via the draw."
     670              :   [repos match-uuid]
     671           21 :   (let [match    (match-repo/find-by-id (:match-postgres-repo repos) match-uuid)
     672            9 :         group-id (:group-id match)
     673           27 :         group    (when group-id (group-repo/find-by-id (:group-postgres-repo repos) group-id))
     674           18 :         draw-id  (when group (:draw-id group))
     675            9 :         stage-id (when draw-id
     676           24 :                    (:stage-id (draw-repo/find-by-id (:draw-postgres-repo repos) draw-id)))]
     677           27 :     (cond (nil? match)
     678            4 :           (either/left
     679            6 :            (utils.errors/build-error
     680              :             :check
     681           12 :             {:code    :error.advancement-reconcile/match-not-found
     682              :              :message "Could not resolve match"
     683           10 :              :context {:match-id (str match-uuid)}}))
     684              : 
     685           12 :           (nil? group-id)
     686            4 :           (either/left
     687            6 :            (utils.errors/build-error
     688              :             :check
     689           12 :             {:code    :error.advancement-reconcile/not-a-group-match
     690              :              :message "Match is not part of a group"
     691           10 :              :context {:match-id (str match-uuid)}}))
     692              : 
     693           12 :           (nil? draw-id)
     694            0 :           (either/left
     695            0 :            (utils.errors/build-error
     696              :             :check
     697            0 :             {:code    :error.advancement-reconcile/stage-not-resolvable
     698              :              :message "Could not resolve draw from match group"
     699            0 :              :context {:match-id (str match-uuid)
     700            0 :                        :group-id (str group-id)}}))
     701              : 
     702           12 :           (nil? stage-id)
     703            0 :           (either/left
     704            0 :            (utils.errors/build-error
     705              :             :check
     706            0 :             {:code    :error.advancement-reconcile/stage-not-resolvable
     707              :              :message "Could not resolve stage from match group"
     708            0 :              :context {:match-id (str match-uuid)
     709            0 :                        :group-id (str group-id)}}))
     710              : 
     711              :           :else
     712            6 :           (either/right
     713           15 :            {:stage-uuid stage-id
     714            3 :             :group-uuid group-id
     715            3 :             :draw-uuid  draw-id}))))
     716              : 
     717              : 
     718              : ;; ---------------------------------------------------------------------------
     719              : ;; Public entry point
     720              : ;; ---------------------------------------------------------------------------
     721              : 
     722              : 
     723            4 : (defn- relevant-rule-for-group?
     724              :   "Predicate for rules reconcile knows how to handle, scoped to the match's
     725              :    group and draw:
     726              :    - Wildcard draw-source rules whose source-draw-id matches draw-uuid.
     727              :    - Source-group rules whose source-group-id matches group-uuid."
     728              :   [group-uuid draw-uuid rule]
     729            6 :   (let [{:keys [selector-type extra source-draw-id source-group-id]} rule]
     730            7 :     (cond
     731              :       ;; Source-group rules
     732           33 :       (= (str group-uuid) (str source-group-id)) (contains? #{"top_n" "rank_range"} selector-type)
     733              : 
     734              :       ;; Wildcard rules
     735           31 :       (and (= "wildcard" (:type extra)) (= (str draw-uuid) (str source-draw-id)))
     736           17 :       (or
     737            6 :        (= "top_n" selector-type)
     738            7 :        (and (= "rank_range" selector-type) (or (:group-by-rank extra) (:draw-by-rank extra))))
     739              : 
     740              :       :else false)))
     741              : 
     742              : 
     743            4 : (defn- ranked-groups-for-rule
     744              :   "Returns the ranked-groups subset relevant to a rule. For wildcard
     745              :    rules: all groups in the source draw. For source-group rules: only
     746              :    the group matching :source-group-id."
     747              :   [rule ranked-groups]
     748           22 :   (if-let [gid (:source-group-id rule)]
     749           32 :     (filterv #(= (str gid) (str (get-in % [:group :uuid]))) ranked-groups)
     750            2 :     ranked-groups))
     751              : 
     752              : 
     753            4 : (defn- rule-has-pending-candidates?
     754              :   "True when some (rank, group) position this rule could ever promote from
     755              :    is still pending (see rank-pending?) — i.e. more results could still
     756              :    change who ends up filling a target seed. False means every position
     757              :    this rule iterates over is either already locked/promoted or
     758              :    permanently impossible (its group is too small to reach that rank), so
     759              :    any of the rule's target seeds still empty are genuine, permanent byes
     760              :    — this can be true well before every group match is played, since
     761              :    locking only needs enough results to rule out a swap, not all of them."
     762              :   [rule ranked-groups]
     763            6 :   (let [{:keys [selector-type extra source-group-id rank-from rank-to take]} rule
     764            9 :         ranked-group (first ranked-groups)]
     765            3 :     (boolean
     766           49 :      (cond (and (= selector-type "rank_range") (or (:group-by-rank extra) (:draw-by-rank extra)))
     767            8 :            (some #(rank-pending? % rank-from) ranked-groups)
     768              : 
     769           30 :            (and (= selector-type "rank_range") source-group-id ranked-group)
     770           32 :            (some #(rank-pending? ranked-group %) (range rank-from (inc (or rank-to rank-from))))
     771              : 
     772           23 :            (and (= selector-type "top_n") source-group-id ranked-group)
     773           11 :            (some #(rank-pending? ranked-group (inc %)) (range take))
     774              : 
     775            6 :            (= selector-type "top_n")
     776            4 :            (some
     777            2 :             (fn [r]
     778           18 :              (some #(rank-pending? % (inc r)) ranked-groups))
     779            6 :             (range take))
     780              : 
     781              :            :else false))))
     782              : 
     783              : 
     784            4 : (def ^:private empty-diff
     785           16 :   {:promoted []
     786            4 :    :revoked  []})
     787              : 
     788              : 
     789            4 : (def ^:private diff-keys
     790              :   "Advancement changes (:promoted/:revoked) plus bracket slot changes that
     791              :    cascaded from revoked bracket seeds (:bracket-promoted/:bracket-revoked)."
     792           20 :   [:promoted :revoked :bracket-promoted :bracket-revoked])
     793              : 
     794              : 
     795            4 : (defn- accumulate-diff
     796              :   "Concatenates every diff key of `diff` onto `acc`."
     797              :   [acc diff]
     798           32 :   (merge-with into acc (select-keys diff diff-keys)))
     799              : 
     800              : 
     801           36 : (defn- diff-changed? [diff] (boolean (some (comp seq diff) diff-keys)))
     802              : 
     803              : 
     804            4 : (defn- resolve-byes-for-target-draws!
     805              :   "For every distinct target-draw-id among relevant-rules, resolves
     806              :    permanent byes/walkovers once NONE of the rules sharing that target
     807              :    draw have any pending candidate left (see rule-has-pending-candidates?).
     808              : 
     809              :    Sibling per-group rules can share one target draw (see
     810              :    desired-for-rank-range-source-group-bracket — e.g. 4 separate rank_range
     811              :    rules, one per source group, all targeting the same manually-created
     812              :    bracket draw) — relevant-rules is scoped to the rules relevant to the
     813              :    CURRENTLY TRIGGERING match's own group, so checking only those would
     814              :    incorrectly declare the draw settled the moment that one group locks,
     815              :    even while sibling groups targeting the same draw still have pending
     816              :    candidates. all-rules (the full, unscoped rule set for the stage) is
     817              :    used to find every sibling rule targeting each draw instead.
     818              : 
     819              :    If a sibling rule's own ranked-groups can't be resolved from the
     820              :    already-loaded ranked-groups (e.g. it sources from a different draw
     821              :    than the triggering match), it's conservatively treated as still
     822              :    pending rather than risking a premature bye."
     823              :   [ctx relevant-rules all-rules ranked-groups]
     824           93 :   (doseq [target-draw-id (distinct (keep :target-draw-id relevant-rules))]
     825           42 :     (let [sibling-rules (filter #(= (str target-draw-id) (str (:target-draw-id %))) all-rules)
     826            6 :           any-pending?  (some
     827            3 :                          (fn [rule]
     828           15 :                           (let [rule-ranked-groups (ranked-groups-for-rule rule ranked-groups)]
     829           12 :                             (or
     830            9 :                              (empty? rule-ranked-groups)
     831            9 :                              (rule-has-pending-candidates? rule rule-ranked-groups))))
     832            3 :                          sibling-rules)]
     833           22 :       (when-not any-pending? (bye/resolve-byes-and-walkovers! ctx target-draw-id)))))
     834              : 
     835              : 
     836            4 : (defn- rule-source-draw-id
     837              :   "A rule's own source draw: source-group-id rules source from that group's
     838              :    draw; wildcard/draw-source rules carry source-draw-id directly."
     839              :   [repos rule]
     840            0 :   (or
     841            0 :    (:source-draw-id rule)
     842            0 :    (when-let [gid (:source-group-id rule)]
     843            0 :      (:draw-id (group-repo/find-by-id (:group-postgres-repo repos) (str gid))))))
     844              : 
     845              : 
     846            4 : (defn draw-ready-for-byes?
     847              :  "True when no advancement rule targeting draw-id still has a pending
     848              :    candidate (see rule-has-pending-candidates?) — i.e. it's safe to resolve
     849              :    permanent byes/walkovers for this draw from a call site that only has
     850              :    the draw-id at hand (unlike resolve-byes-for-target-draws!, which reuses
     851              :    ranked-groups already loaded for the triggering match's own stage).
     852              :    A rule whose own source draw can't be resolved is conservatively
     853              :    treated as still pending, same as resolve-byes-for-target-draws!."
     854              :  [repos draw-id]
     855            3 :  (let [rules (advancement-rule-repo/find-by-target-draw-id
     856            3 :               (:advancement-rule-postgres-repo repos)
     857            1 :               draw-id)]
     858            2 :    (not
     859            2 :     (some
     860            1 :      (fn [rule]
     861            0 :       (let [source-draw-id (rule-source-draw-id repos rule)]
     862            0 :         (or
     863            0 :          (nil? source-draw-id)
     864              :          (let [rule-ranked-groups
     865            0 :                (ranked-groups-for-rule rule (common/load-ranked-groups repos source-draw-id))]
     866            0 :            (or
     867            0 :             (empty? rule-ranked-groups)
     868            0 :             (rule-has-pending-candidates? rule rule-ranked-groups))))))
     869            1 :      rules))))
     870              : 
     871              : 
     872            4 : (defn- sync-touched-group-matches!
     873              :   "Syncs home/away participant IDs on matches for every target group touched
     874              :    by this rule's promote or revoke. No-op when nothing changed. Returns
     875              :    Either<Error, nil>."
     876              :   [repos desired to-add to-remove]
     877           56 :   (let [promoted-gid (when (and (seq to-add) (= :group (:target-kind desired)))
     878            6 :                        (:target-group-id desired))
     879           16 :         revoked-gids (keep :to-group-id to-remove)
     880           40 :         group-ids    (into #{} (remove nil?) (cons promoted-gid revoked-gids))]
     881           16 :     (if (empty? group-ids)
     882           12 :       (either/right nil)
     883            4 :       (reduce
     884            2 :        (fn [acc gid]
     885           24 :         (c/mlet [_ acc] (sync-matches/execute! repos gid)))
     886            6 :        (either/right nil)
     887            2 :        group-ids))))
     888              : 
     889              : 
     890            4 : (defn- process-rule!
     891              :   "Reconciles a single rule against the loaded ranked groups. Returns
     892              :    Either<Error, {:promoted [...] :revoked [...]}>. Right<empty-diff>
     893              :    when the rule shape produces no desired state."
     894              :   [repos rule ranked-groups existing-by-rule]
     895           15 :   (let [ranked-groups (ranked-groups-for-rule rule ranked-groups)
     896           15 :         desired       (rule-desired repos rule ranked-groups)]
     897           15 :     (if (nil? desired)
     898            0 :       (either/right empty-diff)
     899           27 :       (let [rule-existing  (get existing-by-rule (str (:uuid rule)) [])
     900           18 :             {:keys [to-add to-remove]} (diff-rule (:candidates desired) rule-existing)
     901              :             ;; FIX: Revoke stale advancements FIRST to free up slots/bracket seeds
     902           12 :             cascade        (revoke! repos to-remove)
     903              :             ;; Promote new candidates
     904           15 :             promote-result (case (:target-kind desired)
     905            6 :                              :group   (promote-group! repos rule desired to-add)
     906           18 :                              :bracket (promote-bracket! repos rule desired to-add))]
     907           15 :         (cond (either/left? promote-result)
     908            1 :               (do
     909           92 :                 (t/log!
     910              :                  :error
     911            5 :                  {:message "advancement reconcile: promote failed"
     912            3 :                   :error   (c/extract promote-result)
     913            5 :                   :rule-id (str (:uuid rule))})
     914            1 :                 promote-result)
     915              : 
     916              :               :else
     917           21 :               (let [sync-result (sync-touched-group-matches! repos desired to-add to-remove)]
     918           12 :                 (if (either/left? sync-result)
     919            0 :                   (do
     920            0 :                     (t/log!
     921              :                      :error
     922            0 :                      {:message "advancement reconcile: sync target group matches failed"
     923            0 :                       :error   (c/extract sync-result)
     924            0 :                       :rule-id (str (:uuid rule))})
     925            0 :                     sync-result)
     926            6 :                   (either/right
     927            6 :                    (merge
     928            3 :                     cascade
     929           18 :                     {:promoted (c/extract promote-result)
     930            9 :                      :revoked  (vec to-remove)})))))))))
     931              : 
     932              : 
     933            4 : (defn- reconcile-rules!
     934              :   "Folds process-rule! over the rules, short-circuiting on the first Left."
     935              :   [repos rules ranked-groups existing-by-rule]
     936            9 :   (let [result (reduce
     937            3 :                 (fn [acc rule]
     938           21 :                  (let [res (process-rule! repos rule ranked-groups existing-by-rule)]
     939           33 :                    (if (either/left? res) (reduced res) (accumulate-diff acc (c/extract res)))))
     940            3 :                 empty-diff
     941            3 :                 rules)]
     942           22 :     (if (either/left? result) result (either/right result))))
     943              : 
     944              : 
     945            4 : (defn execute!
     946              :  "Reconciles advancements for the group owning the given match.
     947              :    Scopes to rules that source from the match's group or its draw only.
     948              :    Returns Either<Error, {:promoted [...] :revoked [...] :draw-uuid ...}>."
     949              :  [{:keys [repos pg]} match-uuid]
     950           33 :  (c/mlet [{:keys [stage-uuid group-uuid draw-uuid]} (resolve-match-group-context repos match-uuid)]
     951            9 :    (let [all-rules      (advancement-rule-repo/find-by-stage-id
     952            9 :                          (:advancement-rule-postgres-repo repos)
     953            3 :                          stage-uuid)
     954           24 :          relevant-rules (filter (partial relevant-rule-for-group? group-uuid draw-uuid) all-rules)]
     955           12 :      (if (empty? relevant-rules)
     956            3 :        (either/right empty-diff)
     957           15 :        (if (nil? pg)
     958              :          ;; Backward-compatible non-transactional path (primarily for older test fixtures)
     959            5 :          (let [ranked-groups    (common/load-ranked-groups repos draw-uuid)
     960            2 :                existing         (advancement-repo/find-by-rule-ids
     961            3 :                                  (:advancement-postgres-repo repos)
     962            4 :                                  (mapv :uuid relevant-rules))
     963            7 :                existing-by-rule (group-by (comp str :rule-id) existing)]
     964           13 :            (c/mlet [diff (reconcile-rules! repos relevant-rules ranked-groups existing-by-rule)]
     965           11 :              (c/return (if (diff-changed? diff) (assoc diff :draw-uuid draw-uuid) empty-diff))))
     966              :          ;; Transactional path
     967            3 :          (try
     968           12 :            (jdbc/with-transaction
     969            3 :             [tx pg]
     970           21 :             (let [tx-opts          (jdbc/with-options tx {:builder-fn rs/as-unqualified-kebab-maps})
     971           21 :                   tx-repos         (assoc (stage-helpers/make-tx-repos repos tx-opts)
     972            6 :                                     :advancement-postgres-repo (advancement-repo/make-repository
     973            3 :                                                                 tx-opts))
     974           12 :                   ranked-groups    (common/load-ranked-groups tx-repos draw-uuid)
     975            6 :                   existing         (advancement-repo/find-by-rule-ids
     976            9 :                                     (:advancement-postgres-repo tx-repos)
     977           12 :                                     (mapv :uuid relevant-rules))
     978           21 :                   existing-by-rule (group-by (comp str :rule-id) existing)
     979           27 :                   tx-result        (c/mlet [diff (reconcile-rules!
     980            3 :                                                   tx-repos
     981            3 :                                                   relevant-rules
     982            3 :                                                   ranked-groups
     983            3 :                                                   existing-by-rule)]
     984            6 :                                      (c/return
     985           12 :                                       (if (diff-changed? diff)
     986           15 :                                         (assoc diff :draw-uuid draw-uuid)
     987            1 :                                         empty-diff)))]
     988           12 :               (if (either/left? tx-result)
     989              :                 ;; Force database rollback on logical Either/Left errors
     990            9 :                 (throw (ex-info "Transaction failed" {:error (c/extract tx-result)}))
     991            3 :                 (do
     992            6 :                   (resolve-byes-for-target-draws!
     993           12 :                    {:repos tx-repos
     994            3 :                     :pg    tx}
     995            3 :                    relevant-rules
     996            3 :                    all-rules
     997            3 :                    ranked-groups)
     998            3 :                   tx-result))))
     999              :            (catch clojure.lang.ExceptionInfo e
    1000           10 :              (if-let [err (:error (ex-data e))]
    1001            3 :                (either/left err)
    1002            0 :                (throw e)))))))))
    1003              : 
    1004              : 
    1005              : ;; ---------------------------------------------------------------------------
    1006              : ;; Bracket-match-rule reconciliation (source-type = "bracket_match")
    1007              : ;; ---------------------------------------------------------------------------
    1008              : 
    1009              : 
    1010            4 : (defn- desired-for-bracket-match-rule
    1011              :   "Computes desired advancement state for a source-type=bracket_match rule.
    1012              :    Uses compute-source-outcome to determine winner/loser, then returns the
    1013              :    same {:target-kind :bracket/:group :target-draw-id ... :candidates [...]}
    1014              :    shape expected by promote-bracket! / promote-group!."
    1015              :   [repos rule]
    1016            2 :   (let [{:keys [selector-type target-draw-id source-bracket-match-id target-seed]} rule
    1017            6 :         outcome (bracket-reconcile/compute-source-outcome repos (str source-bracket-match-id))]
    1018            3 :     (case selector-type
    1019            5 :       "winner" {:target-kind    :bracket
    1020            1 :                 :target-draw-id target-draw-id
    1021            7 :                 :candidates     (if (and outcome target-seed)
    1022            7 :                                   [{:participant-id (:winner-id outcome)
    1023            1 :                                     :assigned-seed  target-seed}]
    1024            1 :                                   [])}
    1025              : 
    1026            1 :       "loser"  (let [groups
    1027            3 :                      (sort-by
    1028              :                       :order
    1029            6 :                       (group-repo/find-by-draw-id (:group-postgres-repo repos) target-draw-id))]
    1030            6 :                  {:target-kind     :group
    1031           23 :                   :target-group-id (some->
    1032            1 :                                      groups
    1033            1 :                                      first
    1034              :                                      :uuid
    1035            1 :                                      str)
    1036            1 :                   :target-draw-id  target-draw-id
    1037            8 :                   :candidates      (if (and outcome (:loser-id outcome))
    1038            6 :                                      [{:participant-id (:loser-id outcome)}]
    1039            0 :                                      [])})
    1040              : 
    1041              :       nil)))
    1042              : 
    1043              : 
    1044            4 : (defn- process-bracket-match-rule!
    1045              :   "Reconciles a single bracket_match-source advancement rule. Analogous to
    1046              :    process-rule! but computes desired state from the bracket match outcome
    1047              :    rather than ranked groups."
    1048              :   [repos rule existing-by-rule]
    1049            5 :   (let [desired (desired-for-bracket-match-rule repos rule)]
    1050            5 :     (if (nil? desired)
    1051            0 :       (either/right empty-diff)
    1052            9 :       (let [rule-existing  (get existing-by-rule (str (:uuid rule)) [])
    1053            6 :             {:keys [to-add to-remove]} (diff-rule (:candidates desired) rule-existing)
    1054            4 :             cascade        (revoke! repos to-remove)
    1055            5 :             promote-result (case (:target-kind desired)
    1056            6 :                              :bracket (promote-bracket! repos rule desired to-add)
    1057            6 :                              :group   (promote-group! repos rule desired to-add))]
    1058            4 :         (if (either/left? promote-result)
    1059            0 :           (do
    1060            0 :             (t/log!
    1061              :              :error
    1062            0 :              {:message "bracket-match rule reconcile: promote failed"
    1063            0 :               :error   (c/extract promote-result)
    1064            0 :               :rule-id (str (:uuid rule))})
    1065            0 :             promote-result)
    1066            7 :           (let [sync-result (sync-touched-group-matches! repos desired to-add to-remove)]
    1067            4 :             (if (either/left? sync-result)
    1068            0 :               (do
    1069            0 :                 (t/log!
    1070              :                  :error
    1071            0 :                  {:message "bracket-match rule reconcile: sync target group matches failed"
    1072            0 :                   :error   (c/extract sync-result)
    1073            0 :                   :rule-id (str (:uuid rule))})
    1074            0 :                 sync-result)
    1075            2 :               (either/right
    1076            2 :                (merge
    1077            1 :                 cascade
    1078            6 :                 {:promoted (c/extract promote-result)
    1079            3 :                  :revoked  (vec to-remove)})))))))))
    1080              : 
    1081              : 
    1082            4 : (defn execute-for-bracket-match-rules!
    1083              :  "Reconciles cross-stage advancement rules triggered by bracket-match results.
    1084              :    Finds rules with source-type=bracket_match whose source-bracket-match-id
    1085              :    matches the given match's bracket-match, then diffs desired vs existing
    1086              :    state and applies changes.
    1087              :    Returns Either<Error, {:promoted [...] :revoked [...] :draw-uuid ...}>."
    1088              :  [{:keys [repos pg]} match-uuid]
    1089           18 :  (let [match (match-repo/find-by-id (:match-postgres-repo repos) (str match-uuid))
    1090           34 :        bm-id (some->
    1091            2 :                match
    1092              :                :bracket-match-id
    1093            2 :                str)]
    1094           10 :    (if (nil? bm-id)
    1095            3 :      (either/right empty-diff)
    1096           10 :      (let [draw-id  (bracket-reconcile/bracket-match->draw-id repos bm-id)
    1097            6 :            stage-id (when draw-id
    1098           16 :                       (:stage-id (draw-repo/find-by-id (:draw-postgres-repo repos) draw-id)))]
    1099           10 :        (if (nil? stage-id)
    1100            0 :          (either/right empty-diff)
    1101            6 :          (let [all-rules (advancement-rule-repo/find-by-stage-id
    1102            6 :                           (:advancement-rule-postgres-repo repos)
    1103            2 :                           stage-id)
    1104            4 :                relevant  (filter
    1105            2 :                           (fn [r]
    1106            4 :                            (and
    1107            5 :                             (= "bracket_match" (:source-type r))
    1108            6 :                             (= bm-id (str (:source-bracket-match-id r)))))
    1109            2 :                           all-rules)]
    1110            8 :            (if (empty? relevant)
    1111            3 :              (either/right empty-diff)
    1112            1 :              (try
    1113            4 :                (jdbc/with-transaction
    1114            1 :                 [tx pg]
    1115            3 :                 (let [tx-opts          (jdbc/with-options
    1116            1 :                                         tx
    1117            3 :                                         {:builder-fn rs/as-unqualified-kebab-maps})
    1118            7 :                       tx-repos         (assoc (stage-helpers/make-tx-repos repos tx-opts)
    1119            2 :                                         :advancement-postgres-repo (advancement-repo/make-repository
    1120            1 :                                                                     tx-opts))
    1121            2 :                       existing         (advancement-repo/find-by-rule-ids
    1122            3 :                                         (:advancement-postgres-repo tx-repos)
    1123            4 :                                         (mapv :uuid relevant))
    1124            7 :                       existing-by-rule (group-by (comp str :rule-id) existing)
    1125            2 :                       tx-result        (reduce
    1126            1 :                                         (fn [acc rule]
    1127            3 :                                          (let [res (process-bracket-match-rule!
    1128            1 :                                                     tx-repos
    1129            1 :                                                     rule
    1130            1 :                                                     existing-by-rule)]
    1131            4 :                                            (if (either/left? res)
    1132            0 :                                              (reduced res)
    1133            6 :                                              (accumulate-diff acc (c/extract res)))))
    1134            1 :                                         empty-diff
    1135            1 :                                         relevant)]
    1136            4 :                   (if (either/left? tx-result)
    1137            0 :                     (throw (ex-info "Transaction failed" {:error (c/extract tx-result)}))
    1138            2 :                     (either/right
    1139            4 :                      (if (diff-changed? tx-result)
    1140            5 :                        (assoc tx-result :draw-uuid draw-id)
    1141            0 :                        empty-diff)))))
    1142              :                (catch clojure.lang.ExceptionInfo e
    1143            0 :                  (if-let [err (:error (ex-data e))]
    1144            0 :                    (either/left err)
    1145            0 :                    (throw e)))))))))))
        

Generated by: LCOV version 2.0-1