             incomplete-tasks)))
 
 (defn sort-tasks-by-peer-count [sync tasks]
-  (sort-by #(n-peers sync (extensions/bucket sync :peer-state)
-                     % #{:active :acking :sealing}) (sort tasks)))
+  (sort-by
+   (fn [task]
+     (let [peers (n-peers sync task)]
+       (+ (:acking peers) (:active peers) (:sealing peers))))
+   (sort tasks)))
 
 (defn next-active-task [sync job-node]
   (let [incomplete-tasks (find-incomplete-concurrent-tasks sync job-node)]

  (let [states (extensions/bucket sync :peer-state)]
    (filter
     (fn [task]
       (>= (n-peers sync states task #{:active :acking :sealing}) 1))
     tasks)))

(defn next-inactive-task [sync job-node]

  (let [node-data (extensions/read-node sync exhaust-node)
        state-bucket (extensions/bucket sync :peer-state)
        task-node (:task-node node-data)
        peers (n-peers sync task-node)
        n (+ (:acking peers) (:active peers) (:waiting peers) (:sealing peers))
        state-path (extensions/resolve-node sync :peer-state (:id node-data))
        peer-state (:content (extensions/dereference sync state-path))
        same-task? (= (:task-node peer-state) task-node)
        complete? (task-complete? sync task-node)
        state (if (and (>= (:waiting peers) (dec n))
                       (zero? (:sealing peers))
                       (= (:state peer-state) :active))
                (assoc peer-state :state :sealing)
                (assoc peer-state :state :waiting))]
