gitoria

kunibert

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit6aa653536aa65353Records: jukebox connected, first reviewmre6aa65353/lib/queue.hl

11.7 KB

  1. import { tryReadFile, writeFile, mkDir } from 'hl:fs'
  2. import { now, timestamp } from 'hl:time'
  3. import RunJob from './run-job.hl'
  4. \\ ONE process owns all jobs: no cross-process lock needed. State = <dataDir>/queue.json
  5. \\ and <dataDir>/deliveries.json (delivery id -> epoch ms, pruned after 7 days).
  6. \\ queue.json: jobs (one per PR key "<repo.id>#<number>"), closed (PR key -> { time, state, removeSession }),
  7. \\ pendingThreads (PR key -> thread updates waiting for the next run), lastHead (PR key -> head of the last run), seq.
  8. \\ A Hybrid copies on assignment: every change reads a job (find), changes it and writes it back (put).
  9. \\ job.status: queued | running | failed.
  10. String dataDir = ''
  11. Number maxTries = 3
  12. Number backoffSeconds = 30
  13. Number keepDeliveryDays = 7
  14. Hybrid repos = null
  15. String hybriel = 'hybriel'
  16. Number timeoutSeconds = 900
  17. String runnerData = ''
  18. String ticketsBase = ''
  19. String ticketsTokenFile = ''
  20. String reviewUser = ''
  21. String codexBin = 'codex'
  22. String workDir = ''
  23. busy = false
  24. jobs = []
  25. closed = {}
  26. pendingThreads = {}
  27. lastHead = {}
  28. seq = 0
  29. seen = {}
  30. running = null
  31. lastError = null
  32. runner = null
  33. load = () => {
  34. mkDir(dataDir)
  35. runner = new RunJob(dataDir = dataDir, =repos, =hybriel, =timeoutSeconds, runnerData = runnerData == '' ? dataDir + '/runner' : runnerData, =ticketsBase, =ticketsTokenFile, =reviewUser, =codexBin, =workDir)
  36. q = tryReadFile(dataDir + '/queue.json')
  37. if (q != null) {
  38. state = JSON.parse(q)
  39. jobs = state.jobs
  40. closed = state.closed
  41. pendingThreads = state.pendingThreads
  42. lastHead = state.lastHead
  43. seq = state.seq
  44. \\ a job that was running when the process died is queued again
  45. for (let i = 0; i < jobs.length; i = i + 1) {
  46. if (jobs[i].status == 'running') {
  47. let j = jobs[i]
  48. j.status = 'queued'
  49. j.next = null
  50. jobs[i] = j
  51. }
  52. }
  53. }
  54. d = tryReadFile(dataDir + '/deliveries.json')
  55. if (d != null) { seen = JSON.parse(d) }
  56. pruneDeliveries()
  57. }
  58. saveQueue = () => {
  59. writeFile(dataDir + '/queue.json', JSON.stringify({ =jobs, =closed, =pendingThreads, =lastHead, =seq }))
  60. }
  61. saveSeen = () => {
  62. writeFile(dataDir + '/deliveries.json', JSON.stringify(seen))
  63. }
  64. wasSeen = (String id) => {
  65. return seen[id] != null
  66. }
  67. markSeen = (String id) => {
  68. seen[id] = now()
  69. saveSeen()
  70. }
  71. pruneDeliveries = () => {
  72. limit = now() - keepDeliveryDays * 86400 * 1000
  73. let kept = {}
  74. let dropped = 0
  75. for (id in seen) {
  76. if (seen[id] >= limit) { kept[id] = seen[id] } else { dropped = dropped + 1 }
  77. }
  78. if (dropped > 0) {
  79. seen = kept
  80. saveSeen()
  81. }
  82. return dropped
  83. }
  84. indexOf = (String key) => {
  85. for (let i = 0; i < jobs.length; i = i + 1) { if (jobs[i].key == key) { return i } }
  86. return -1
  87. }
  88. remove = (String key) => {
  89. let kept = []
  90. for (j of jobs) { if (j.key != key) { kept.push(j) } }
  91. jobs = kept
  92. }
  93. \\ fold a change into a job; returns the new job. Newest head wins by time; flags and lists merge.
  94. \\ A job stays threadReplyOnly only while every change in it is a reply without a new head.
  95. fold = (Hybrid job, Hybrid c) => {
  96. let j = job
  97. if (j.time == null || c.time == null || c.time >= j.time) {
  98. j.head = c.head
  99. j.time = c.time
  100. j.pull = c.pull
  101. j.repo = c.repo
  102. }
  103. if (c.force) { j.force = true }
  104. if (c.reset) { j.reset = true }
  105. for (t of c.threads) { j.threads.push(t) }
  106. for (n of c.notes) { j.notes.push(n) }
  107. j.events.push(c.event)
  108. j.updated = timestamp()
  109. return j
  110. }
  111. newJob = (Hybrid c, String key) => {
  112. seq = seq + 1
  113. let threads = []
  114. if (pendingThreads[key] != null) {
  115. threads = pendingThreads[key]
  116. delete pendingThreads[key]
  117. }
  118. return { =key, =seq, status = 'queued', tries = 0, notBefore = 0, repo = c.repo, number = c.number, head = null, time = null, pull = null, force = false, reset = false, threadReplyOnly = true, =threads, notes = [], events = [], created = timestamp(), updated = timestamp(), next = null, lastError = null }
  119. }
  120. \\ the head a thread-reply change is compared with: the job's own head, else the last head that was run
  121. baselineHead = (String key, Number i) => {
  122. if (i >= 0) { return jobs[i].head }
  123. return lastHead[key]
  124. }
  125. \\ a review change -> { action: 'queued'|'updated'|'follow-up'|'ignored', key, threadReplyOnly }
  126. enqueue = (Hybrid c) => {
  127. key = c.repoId + '#' + c.number
  128. mark = closed[key]
  129. if (mark != null) {
  130. if (c.event == 'pull_request.reopened' || c.event == 'pull_request.opened') {
  131. if (c.time == null || c.time >= mark.time) { delete closed[key] }
  132. }
  133. if (closed[key] != null) {
  134. saveQueue()
  135. return { action = 'ignored', reason = 'pr closed', =key }
  136. }
  137. }
  138. i = indexOf(key)
  139. \\ replies bring no new head when the head equals the baseline; everything else is a full review
  140. replyOnly = c.replyCandidate && c.head == baselineHead(key, i)
  141. let j = null
  142. if (i < 0) { j = newJob(c, key) } else { j = jobs[i] }
  143. if (i >= 0 && j.status == 'running') {
  144. if (j.next == null) { j.next = newJob(c, key) }
  145. n = fold(j.next, c)
  146. if (!replyOnly) { n.threadReplyOnly = false }
  147. j.next = n
  148. jobs[i] = j
  149. saveQueue()
  150. return { action = 'follow-up', =key, threadReplyOnly = n.threadReplyOnly }
  151. }
  152. j = fold(j, c)
  153. if (!replyOnly) { j.threadReplyOnly = false }
  154. if (j.status == 'failed') {
  155. j.status = 'queued'
  156. j.tries = 0
  157. j.notBefore = 0
  158. }
  159. if (i < 0) { jobs.push(j) } else { jobs[i] = j }
  160. saveQueue()
  161. let act = 'queued'
  162. if (i >= 0) { act = 'updated' }
  163. return { action = act, =key, threadReplyOnly = j.threadReplyOnly }
  164. }
  165. \\ review_thread resolved/unresolved: NO review. Merge the flip into the queued job, else store it for the next run.
  166. recordThread = (Hybrid c) => {
  167. key = c.repoId + '#' + c.number
  168. if (closed[key] != null) { return { action = 'ignored', reason = 'pr closed', =key } }
  169. i = indexOf(key)
  170. if (i >= 0 && jobs[i].status != 'running') {
  171. let j = jobs[i]
  172. for (t of c.threads) { j.threads.push(t) }
  173. j.updated = timestamp()
  174. jobs[i] = j
  175. saveQueue()
  176. return { action = 'thread-merged', =key }
  177. }
  178. let list = []
  179. if (pendingThreads[key] != null) { list = pendingThreads[key] }
  180. for (t of c.threads) { list.push(t) }
  181. pendingThreads[key] = list
  182. saveQueue()
  183. return { action = 'thread-stored', =key }
  184. }
  185. \\ closed/merged: drop the queued job and any stored thread flips, mark the PR closed and ITS SESSION FOR REMOVAL
  186. \\ (the runner acts on closed[key].removeSession). A running job is dropped when it ends.
  187. close = (Hybrid c) => {
  188. key = c.repoId + '#' + c.number
  189. closed[key] = { time = c.time, state = c.pull.state, removeSession = true, repo = c.repo }
  190. delete pendingThreads[key]
  191. delete lastHead[key]
  192. let dropped = false
  193. let kept = []
  194. for (j of jobs) {
  195. if (j.key != key) {
  196. kept.push(j)
  197. } else if (j.status == 'running') {
  198. let r = j
  199. r.next = null
  200. r.dropWhenDone = true
  201. kept.push(r)
  202. } else { dropped = true }
  203. }
  204. jobs = kept
  205. saveQueue()
  206. return { action = 'closed', =key, =dropped }
  207. }
  208. \\ the oldest startable job: queued, backoff over; null when none or one is running
  209. nextJob = () => {
  210. if (running != null) { return null }
  211. t = now()
  212. let best = null
  213. for (j of jobs) {
  214. if (j.status != 'queued' || j.notBefore > t) { continue }
  215. if (best == null || j.seq < best.seq) { best = j }
  216. }
  217. return best
  218. }
  219. \\ settle a job after runJob: success (remove, or the follow-up takes its place), or failure (retry/backoff, then failed)
  220. settle = (Hybrid job, r) => {
  221. let j = job
  222. i = indexOf(j.key)
  223. if (i < 0) { return null }
  224. if (j.dropWhenDone) {
  225. remove(j.key)
  226. console.log(timestamp() + ' worker: ' + j.key + ' closed while running, dropped')
  227. return null
  228. }
  229. if (r != null && r.ok) {
  230. console.log(timestamp() + ' worker: done ' + j.key)
  231. lastHead[j.key] = j.head
  232. if (j.next != null) {
  233. let n = j.next
  234. n.status = 'queued'
  235. n.seq = j.seq
  236. jobs[i] = n
  237. console.log(timestamp() + ' worker: follow-up for ' + j.key + ' queued: head=' + n.head)
  238. } else { remove(j.key) }
  239. return null
  240. }
  241. j.tries = j.tries + 1
  242. let err = 'runJob failed'
  243. if (r != null && r.error != null) { err = r.error }
  244. j.lastError = err
  245. lastError = j.key + ': ' + err
  246. if (j.next != null) {
  247. j = fold(j, j.next)
  248. j.next = null
  249. }
  250. if (j.tries >= maxTries) {
  251. j.status = 'failed'
  252. console.log(timestamp() + ' OPERATOR: job ' + j.key + ' FAILED after ' + j.tries + ' tries: ' + err)
  253. } else {
  254. j.status = 'queued'
  255. let wait = backoffSeconds * 1000
  256. for (let k = 1; k < j.tries; k = k + 1) { wait = wait * 2 }
  257. j.notBefore = now() + wait
  258. console.log(timestamp() + ' worker: ' + j.key + ' failed (' + err + '), try ' + j.tries + '/' + maxTries + ', retry in ' + (wait / 1000) + 's')
  259. }
  260. jobs[i] = j
  261. return null
  262. }
  263. \\ the job's child ended (or was killed): settle the stored copy of the job. This is the completion call.
  264. done = (String key, Hybrid res) => {
  265. running = null
  266. busy = false
  267. i = indexOf(key)
  268. if (i >= 0) {
  269. \\ the job may have changed while it ran (follow-up, close): settle on the stored copy
  270. settle(jobs[i], res)
  271. }
  272. saveQueue()
  273. return key
  274. }
  275. \\ a closed PR whose session is still to be removed and which has no job any more
  276. dropCandidate = () => {
  277. for (k in closed) {
  278. if (closed[k].removeSession && indexOf(k) < 0) { return k }
  279. }
  280. return null
  281. }
  282. \\ one timer tick: start ONE thing and return at once: the session removal of a closed PR, else the oldest job.
  283. \\ The result arrives later through done() / the drop callback.
  284. tick = () => {
  285. if (busy) { return null }
  286. let dk = null
  287. if (repos != null) { dk = dropCandidate() }
  288. if (dk != null) {
  289. busy = true
  290. parts = dk.split('#')
  291. num = parts[parts.length - 1]
  292. console.log(timestamp() + ' worker: removing the session of closed ' + dk)
  293. runner.dropSession(closed[dk], num, (r) => {
  294. busy = false
  295. if (r.ok) {
  296. let m = closed[dk]
  297. m.removeSession = false
  298. m.removed = timestamp()
  299. closed[dk] = m
  300. console.log(timestamp() + ' worker: session of ' + dk + ' removed, mark cleared')
  301. } else { console.log(timestamp() + ' worker: removing the session of ' + dk + ' failed: ' + r.error) }
  302. saveQueue()
  303. return null
  304. })
  305. return dk
  306. }
  307. j = nextJob()
  308. if (j == null) { return null }
  309. let r = j
  310. r.status = 'running'
  311. r.next = null
  312. jobs[indexOf(r.key)] = r
  313. running = r.key
  314. busy = true
  315. saveQueue()
  316. console.log(timestamp() + ' worker: start ' + r.key + ' head=' + r.head + ' try=' + (r.tries + 1))
  317. k = r.key
  318. runner.runJob(r, (res) => { return done(k, res) })
  319. return r.key
  320. }
  321. countSeen = () => {
  322. let n = 0
  323. for (id in seen) { n = n + 1 }
  324. return n
  325. }
  326. health = () => {
  327. let queued = 0
  328. let failed = 0
  329. for (j of jobs) {
  330. if (j.status == 'failed') { failed = failed + 1 } else { queued = queued + 1 }
  331. }
  332. let pending = 0
  333. for (k in pendingThreads) { pending = pending + 1 }
  334. let toRemove = []
  335. for (k in closed) { if (closed[k].removeSession) { toRemove.push(k) } }
  336. return { jobs = jobs.length, =queued, =failed, =running, =lastError, deliveries = countSeen(), pendingThreadPrs = pending, sessionsToRemove = toRemove }
  337. }

Branches

Latest commits

  • 6aa65353Records: jukebox connected, first reviewmre
  • ad8011cfRecords: neutral ticket rule, jukeboxmre
  • ca5f31dfPrompt: neutral reviewer identitymre
  • b241d9c8Records: Anton tryParse noteKunibert
  • 42cc1bc0Records: K12 doneKunibert
  • 9e6039eeRecords: gates K11, K12Kunibert
  • 59b8fe83Use Hybriel day39 helpersKunibert
  • c2e393a2Records: K12 startedKunibert
  • 00696678Records: Anton day39 notemre
  • 070e01a4Records: parkmre
  • bf8af0dcRecords: v1.4 checkedmre
  • 44af321bRecords: contract v1.4mre
  • 310f3fd0Records: outdated semanticsmre
  • 268ebfe6Records: #11 proven live and closedmre
  • 88e8aad3Records: K11 verified and deployedmre
  • cd4cb09cNo review and status error when the model's tools did not run (kunibert#11)Kunibert
  • a6b54efaStatus updatemre
  • 5a72268eRecords: #4-#10 done, #11 started, review package on #1mre
  • 194c7da6Records: real proof greenmre
  • cdfa94a9Records: AppArmor profile for the review sandboxmre