Line data Source code
1 4 : (ns matchscore.application.advancement.bracket-reconcile
2 : "Propagates winner_of / loser_of derivations from a bracket_match to all
3 : bracket_match_slots that depend on it (via source_match_id), within the
4 : same draw. Triggered alongside group-source advancement reconcile on
5 : every match result change.
6 :
7 : Resolution model: a source bracket_match has a decided outcome only
8 : when every match row under it has a recorded result. The bracket_match
9 : winner is then the participant with the strict majority of game
10 : winner_ids; ties (or any unrecorded game) mean unresolved → dependent
11 : slots are revoked (participant_id nulled, source_type preserved).
12 :
13 : Changes cascade: a dependent slot that changes resets its own
14 : bracket_match's results, so propagation continues from that match
15 : through every later round (see propagate-from-bracket-match!)."
16 : (:require
17 : [cats.monad.either :as either]
18 : [matchscore.application.advancement.common :as common]
19 : [matchscore.application.stage.helpers :as stage-helpers]
20 : [matchscore.domain.bracket-match-slot.repository.postgres :as bms-repo]
21 : [matchscore.domain.bracket-match.repository.postgres :as bracket-match-repo]
22 : [matchscore.domain.bracket-round.repository.postgres :as bracket-round-repo]
23 : [matchscore.domain.bracket.repository.postgres :as bracket-repo]
24 : [matchscore.domain.match-result.repository.postgres :as match-result-repo]
25 : [matchscore.domain.match.repository.postgres :as match-repo]
26 : [next.jdbc :as jdbc]
27 : [next.jdbc.result-set :as rs]
28 : [taoensso.telemere :as t]))
29 :
30 :
31 16 : (def ^:private propagating-source-types #{"winner_of" "loser_of"})
32 :
33 :
34 4 : (def ^:private empty-diff
35 16 : {:promoted []
36 4 : :revoked []})
37 :
38 :
39 : ;; ---------------------------------------------------------------------------
40 : ;; Resolution helpers
41 : ;; ---------------------------------------------------------------------------
42 :
43 :
44 4 : (defn bracket-match->draw-id
45 : "Resolves bracket_match → bracket_round → bracket → draw uuid string,
46 : or nil if any link is missing."
47 : [repos bracket-match-id]
48 16 : (let [bracket-match (when bracket-match-id
49 8 : (bracket-match-repo/find-by-id
50 12 : (:bracket-match-postgres-repo repos)
51 4 : bracket-match-id))
52 20 : round (when (:bracket-round-id bracket-match)
53 8 : (bracket-round-repo/find-by-id
54 12 : (:bracket-round-postgres-repo repos)
55 12 : (:bracket-round-id bracket-match)))
56 20 : bracket (when (:bracket-id round)
57 8 : (bracket-repo/find-by-id
58 12 : (:bracket-postgres-repo repos)
59 12 : (:bracket-id round)))]
60 64 : (some->
61 4 : bracket
62 : :draw-id
63 4 : str)))
64 :
65 :
66 4 : (defn compute-source-outcome
67 : "Returns {:winner-id <uuid-str> :loser-id <uuid-str>} when every match
68 : under source-bracket-match-id has a result AND one participant has a
69 : strict majority of game wins. Otherwise returns nil (unresolved)."
70 : [repos source-bracket-match-id]
71 12 : (let [matches (match-repo/find-by-bracket-match-id
72 12 : (:match-postgres-repo repos)
73 4 : source-bracket-match-id)
74 28 : match-ids (mapv (comp str :uuid) matches)
75 8 : results (match-result-repo/find-by-match-ids
76 12 : (:match-result-postgres-repo repos)
77 4 : match-ids)]
78 29 : (cond (empty? matches) nil
79 20 : (< (count results) (count matches)) nil
80 : :else
81 12 : (let [wins-by-pid (reduce
82 4 : (fn [acc {:keys [winner-id]}]
83 49 : (if winner-id (update acc (str winner-id) (fnil inc 0)) acc))
84 4 : {}
85 4 : results)
86 28 : ranked (sort-by (comp - val) wins-by-pid)
87 12 : [top top-cnt] (first ranked)
88 12 : [_ second-cnt] (second ranked)]
89 60 : (when (and top (or (nil? second-cnt) (> top-cnt second-cnt)))
90 8 : (let [winner-id top
91 4 : all-pids (->>
92 4 : matches
93 24 : (mapcat (juxt :home-participant-id :away-participant-id))
94 12 : (keep identity)
95 12 : (map str)
96 4 : set)
97 17 : loser-id (or
98 24 : (first (disj all-pids winner-id))
99 : ;; fallback when match has no home/away participants:
100 : ;; read loser directly from the result row
101 3 : (some
102 3 : (fn [r]
103 27 : (when (= (str (:winner-id r)) winner-id)
104 22 : (some->
105 9 : (:loser-id r)
106 1 : str)))
107 3 : results))]
108 16 : {:winner-id winner-id
109 4 : :loser-id loser-id}))))))
110 :
111 :
112 4 : (defn- desired-pid-for-slot
113 : [outcome {:keys [source-type]}]
114 12 : (case source-type
115 12 : "winner_of" (:winner-id outcome)
116 12 : "loser_of" (:loser-id outcome)
117 : nil))
118 :
119 :
120 4 : (defn- classify-slot
121 : [outcome slot]
122 20 : (let [desired (desired-pid-for-slot outcome slot)
123 64 : current (some->
124 4 : slot
125 : :participant-id
126 2 : str)]
127 29 : (cond (= desired current) :noop
128 3 : desired :promote
129 : :else :revoke)))
130 :
131 :
132 4 : (defn- summarize-slot
133 : [slot pid]
134 33 : {:bracket-match-id (str (:bracket-match-id slot))
135 9 : :slot (:slot slot)
136 26 : :participant-id (some->
137 3 : pid
138 3 : str)
139 9 : :source-type (:source-type slot)
140 48 : :source-match-id (some->
141 3 : slot
142 : :source-match-id
143 3 : str)})
144 :
145 :
146 : ;; ---------------------------------------------------------------------------
147 : ;; Apply
148 : ;; ---------------------------------------------------------------------------
149 :
150 :
151 4 : (defn- apply-slot-change!
152 : "Upserts the slot with the new participant-id and updates the dependent
153 : bracket_match's matches' home/away_participant_id accordingly. Returns
154 : the slot summary or throws on failure to abort transaction."
155 : [repos slot new-pid]
156 15 : (let [next-slot (assoc slot
157 26 : :participant-id (some->
158 3 : new-pid
159 3 : str))
160 18 : [ok? _ err] (bms-repo/upsert! (:bracket-match-slot-postgres-repo repos) next-slot)]
161 12 : (if-not ok?
162 0 : (throw
163 0 : (ex-info
164 : "bracket reconcile: slot upsert failed"
165 0 : {:type :database-error
166 0 : :error err
167 0 : :slot-id (str (:uuid slot))}))
168 3 : (do
169 6 : (match-repo/update-bracket-slot-participant!
170 9 : (:match-postgres-repo repos)
171 15 : (str (:bracket-match-id slot))
172 9 : (:slot slot)
173 26 : (some->
174 3 : new-pid
175 3 : str))
176 24 : (common/reset-bracket-match-results! repos (str (:bracket-match-id slot)))
177 12 : (summarize-slot slot new-pid)))))
178 :
179 :
180 4 : (defn- process-slot!
181 : [repos get-draw-id source-draw-id outcome slot]
182 32 : (let [dependent-draw-id (get-draw-id (str (:bracket-match-id slot)))]
183 24 : (cond (not= source-draw-id dependent-draw-id)
184 2 : (do
185 92 : (t/log!
186 : :warn
187 6 : {:message "bracket reconcile: dependent slot in different draw; skipping"
188 5 : :slot-id (str (:uuid slot))
189 1 : :source-draw-id source-draw-id
190 1 : :dependent-draw-id dependent-draw-id})
191 : nil)
192 :
193 : :else
194 20 : (let [kind (classify-slot outcome slot)]
195 15 : (case kind
196 : :noop nil
197 : :promote
198 15 : (let [pid (desired-pid-for-slot outcome slot)
199 15 : summary (apply-slot-change! repos slot pid)]
200 18 : (when summary [:promoted summary]))
201 :
202 : :revoke
203 12 : (let [summary (apply-slot-change! repos slot nil)]
204 12 : (when summary [:revoked summary])))))))
205 :
206 :
207 : ;; ---------------------------------------------------------------------------
208 : ;; Cascade
209 : ;; ---------------------------------------------------------------------------
210 :
211 :
212 8 : (def ^:private max-cascade-depth
213 : "Upper bound on recursive propagation hops. Brackets are acyclic and far
214 : shallower than this; the guard only protects against corrupt slot data
215 : that forms a source_match_id cycle."
216 : 64)
217 :
218 :
219 4 : (defn- merge-diffs
220 : [a b]
221 33 : {:promoted (into (:promoted a) (:promoted b))
222 24 : :revoked (into (:revoked a) (:revoked b))})
223 :
224 :
225 4 : (defn- propagate!
226 : [repos get-draw-id source-bm-id depth]
227 4 : (let [dependent
228 12 : (filter
229 24 : #(contains? propagating-source-types (:source-type %))
230 24 : (bms-repo/find-by-source-match-id (:bracket-match-slot-postgres-repo repos) source-bm-id))]
231 27 : (cond (empty? dependent) empty-diff
232 :
233 12 : (> depth max-cascade-depth)
234 0 : (do
235 0 : (t/log!
236 : :warn
237 0 : {:message "bracket reconcile: cascade depth exceeded; stopping"
238 0 : :bracket-match-id source-bm-id
239 0 : :depth depth})
240 0 : empty-diff)
241 :
242 : :else
243 16 : (let [source-draw-id (get-draw-id source-bm-id)
244 16 : outcome (compute-source-outcome repos source-bm-id)
245 8 : changes (vec
246 12 : (keep
247 28 : #(process-slot! repos get-draw-id source-draw-id outcome %)
248 4 : dependent))
249 8 : own (reduce
250 4 : (fn [acc [kind summary]]
251 18 : (update acc kind conj summary))
252 4 : empty-diff
253 4 : changes)
254 36 : changed-bm-ids (distinct (map (comp :bracket-match-id second) changes))]
255 : ;; Every changed slot reset its bracket_match's results, so that
256 : ;; match's own outcome may have changed too: keep propagating.
257 8 : (reduce
258 4 : (fn [acc bm-id]
259 30 : (merge-diffs acc (propagate! repos get-draw-id bm-id (inc depth))))
260 4 : own
261 4 : changed-bm-ids)))))
262 :
263 :
264 4 : (defn propagate-from-bracket-match!
265 : "Re-derives every winner_of / loser_of slot that depends on
266 : source-bm-id from its current outcome, then recursively does the same
267 : for every bracket_match whose slot changed (a changed slot resets that
268 : match's results, which invalidates its own winner/loser further down
269 : the bracket — e.g. semifinal → final and 3rd-place match).
270 :
271 : Call this whenever a bracket_match's participants or results change
272 : outside of a result submission. Runs with the given repos and does not
273 : open a transaction: callers inside a transaction pass tx-bound repos.
274 : Returns {:promoted [...] :revoked [...]} slot summaries."
275 : [repos source-bm-id]
276 12 : (let [get-draw-id (memoize
277 4 : (fn [bm-id]
278 16 : (bracket-match->draw-id repos bm-id)))]
279 32 : (propagate! repos get-draw-id (str source-bm-id) 0)))
280 :
281 :
282 : ;; ---------------------------------------------------------------------------
283 : ;; Public entry point
284 : ;; ---------------------------------------------------------------------------
285 :
286 :
287 4 : (defn execute!
288 : "Propagates winner_of / loser_of derivations from a match's bracket_match
289 : to all dependent slots within the same draw, cascading through every
290 : later round whose participants change. Returns
291 : Either<Error, {:promoted [...] :revoked [...] :draw-uuid ...}>."
292 : [{:keys [repos pg]} match-uuid]
293 27 : (let [match (match-repo/find-by-id (:match-postgres-repo repos) (str match-uuid))
294 51 : src-bm-id (some->
295 3 : match
296 : :bracket-match-id
297 3 : str)]
298 15 : (if (nil? src-bm-id)
299 6 : (either/right empty-diff)
300 9 : (let [all-dependent (bms-repo/find-by-source-match-id
301 9 : (:bracket-match-slot-postgres-repo repos)
302 3 : src-bm-id)
303 9 : dependent (filter
304 18 : #(contains? propagating-source-types (:source-type %))
305 3 : all-dependent)]
306 12 : (if (empty? dependent)
307 6 : (either/right empty-diff)
308 12 : (jdbc/with-transaction
309 3 : [tx pg]
310 21 : (let [tx-opts (jdbc/with-options tx {:builder-fn rs/as-unqualified-kebab-maps})
311 12 : tx-repos (stage-helpers/make-tx-repos repos tx-opts)
312 : {:keys [promoted revoked]
313 : :as diff}
314 12 : (propagate-from-bracket-match! tx-repos src-bm-id)]
315 27 : (if (or (seq promoted) (seq revoked))
316 30 : (either/right (assoc diff :draw-uuid (bracket-match->draw-id tx-repos src-bm-id)))
317 3 : (either/right empty-diff)))))))))
|