Algorithm Search⌘K

Algorithmcore

Contract net protocol

Also called CNP.

Smith's protocol in which a manager announces a task, contractors bid, and the manager awards the contract to the best bid.

Time
O(r t^2) totalO(r t) per_round
Space
O(r + t) extra
Counts
messages O(r t^2) full_windowmessages O(r t) one_task_window
Where
r = the number of robots; t = the number of tasks
Properties
deterministiconlinenot randomized
Origin
Reid G. Smith, 1980

The contract net protocol assigns tasks to agents by announcement, bid and award. The agent that holds a task acts as its manager: it announces the task, the idle agents that can do it reply with a bid, and the manager gives the contract to the best bid. Reid Smith designed it in 1980 for distributed problem solving, and robot teams use it as the simplest market for multi-robot task allocation. Unlike the auction algorithm it never revises an award, and unlike the consensus-based bundle algorithm it gives one task per robot through managers that hear all bids, so it is fast but greedy, and its total cost has no bound against the optimum.

In plain words

A robot team has jobs to do. For each job, someone shouts "who can do this, and at what cost?" Every free robot that can do the job answers with its cost, but a robot answers only for the job it likes best, so it never promises two jobs at once. The one who shouted picks the cheapest answer and tells that robot "the job is yours". The winner is now busy. The others wait for the next call.

This is quick, because each robot only has to price a few jobs and send a few short notes. It is also short-sighted: the cheapest robot for the first job may be the only robot that could do a later job well, and the protocol never takes such a choice back.

The problem

The model. There are rr robots and tt tasks. Robot ii has a cost cijc_{ij} for task jj, in any unit (seconds, meters or energy), or no cost if it cannot do the task. Each robot does at most one task, and each task needs one robot: this is the single-task robot, single-robot task, instantaneous class (ST-SR-IA) of Gerkey and Matarić (2004). Every task has a manager, which can be a robot or an operator console. The communication graph is complete: an announcement reaches every robot, and a bid or an award is one message to one agent. Time is synchronous, in rounds of announce, bid and award.

Input. The costs cijc_{ij}, the order in which the managers announce, and the window size: how many open tasks are announced in each round (all of them, or one at a time).

Output. An assignment of tasks to robots, the total cost, the number of rounds, and the messages sent.

How it differs from close pages. Multi-robot task allocation is the problem, and market-based task allocation is the general method of auctions; the contract net is the oldest concrete protocol of that method, with one item per auction and no re-trading. The consensus-based bundle algorithm has no managers: each robot claims a bundle of tasks and the team agrees by message passing between neighbors, with a 50 percent bound under diminishing marginal gain. The auction algorithm of Bertsekas raises prices over many rounds and reaches an optimal assignment within ε\varepsilon, which the contract net does not. The Hungarian algorithm solves the same assignment exactly, but centrally.

The algorithm

  1. CONTRACT-NET(c, order, k)
  2. 1open ← the tasks in announcement order; idle ← all robots
  3. 2while open ≠ ∅ do
  4. 3W ← the first k tasks of open (or all of open); each manager of a task in W announces it to every robot
  5. 4each idle robot i sends one bid (c_ij, i) for its cheapest eligible task j in W
  6. 5if no robot sent a bid then remove W from open; continue
  7. 6for each task j in W that received bids do
  8. 7award j to the bid with the smallest (c_ij, i); remove j from open and the winner from idle
  9. 8return the awards

Line L3 is the task announcement. Line L4 is the bid: a robot bids only once per round, on the task it likes best, so it can never win two tasks in one round, which is what keeps robots single-task. Ties go to the smaller task index. Line L7 is the award, with ties to the smaller robot index. Robots that lost stay idle and bid again in the next round. Line L5 closes the window only when nobody bid at all: then no idle robot can do any task of the window, and since robots never become idle again, nobody ever will.

With k=1k = 1 each round is one sealed-bid auction of one task, so the protocol is a sequence of single-item auctions in the announcement order. With the full window all managers announce at once and the robots choose between the offers.

Example

Three robots and two tasks, with costs in seconds:

task 0 task 1
robot 0 1 2
robot 1 10 3
robot 2 1.5 2.5

Full window. Round 1: both tasks are announced to 3 robots, 6 messages. Robot 0 bids 1 on task 0, robot 1 bids 3 on task 1, and robot 2 bids 1.5 on task 0. Task 0 goes to robot 0 and task 1 to robot 1. The total cost is 1+3=41 + 3 = 4 s after 1 round, with 6 announcements, 3 bids and 2 awards.

One task per round. Round 1 announces task 0: the bids are 1, 10 and 1.5, and robot 0 wins. Round 2 announces task 1 to the idle robots 1 and 2: the bids are 3 and 2.5, and robot 2 wins. The total cost is 1+2.5=3.51 + 2.5 = 3.5 s after 2 rounds, with 6 announcements, 5 bids and 2 awards.

The minimum cost assignment, found by brute force over all assignments, costs 3.5 s. In this case the slower protocol is better, because robot 2 was free when task 1 came up and robot 1 was not forced on it.

No bound on the cost. With two robots, two tasks and costs c00=1c_{00} = 1, c01=2c_{01} = 2, c10=2c_{10} = 2, c11=Mc_{11} = M, both robots bid on task 0 in round 1 and robot 0 wins, so robot 1 must take task 1. The protocol pays 1+M1 + M, but the other assignment pays 2+2=42 + 2 = 4. For M=100M = 100 the ratio is 101/4=25.25101 / 4 = 25.25, and it grows with MM.

Correctness

The proof shows four facts, all theorems for the synchronous model above. The awards are always a valid assignment: no robot has two tasks and no task has two robots. The protocol stops within tt rounds, because each round removes at least one task from the open list. At the end no idle robot can do a task without an award, so the assignment is a maximal matching in the graph of eligible pairs, and it covers at least half as many tasks as a maximum matching. With the full window, the cheapest eligible pair is always awarded in round 1. The cost of the assignment has no constant factor bound, by the example above.

Proof: The contract net protocol for single-task robots gives a valid assignment in at most t rounds that is maximal, so it awards at least half as many tasks as possible, but its cost can be arbitrarily far from the optimumfull

There are rr robots and tt tasks. cijc_{ij} is the bid of robot ii for task jj; it is a number, or it is missing when robot ii cannot do task jj. Robot ii is eligible for task jj when cijc_{ij} is not missing. Each robot does at most one task. Time is synchronous and runs in rounds. Lines L1 to L8 refer to the pseudocode on the contract net protocol page. In a round, the managers announce a window WW of open tasks (all open tasks, or the first kk of them), each idle robot sends one bid for its cheapest eligible task in WW (ties to the smaller task index), and each manager that got bids awards its task to the lowest bid (ties to the smaller robot index). If no robot bids at all, the tasks of WW are closed without an award.

Invariant. At the start of each round: (a) the awards made so far form a partial assignment, that is, no task has two robots and no robot has two tasks; (b) a robot is idle exactly when it has no task; (c) every task that was closed without an award has no eligible idle robot.

Lemma 1. The invariant holds at the start of every round.

Proof. At the start, no task is awarded, all robots are idle and no task is closed, so (a) to (c) hold. Suppose they hold at the start of a round. Each idle robot sends at most one bid, so in line L7 each robot can win at most one task in this round, and it wins only if it was idle, so by (b) it had no task before. Each task gets at most one award, and an awarded task leaves the open list, so it is never awarded again. The winner leaves the idle set. So (a) and (b) hold after the round. For (c): tasks are closed in line L5 only when no idle robot sent a bid. An idle robot sends a bid whenever it is eligible for some task in WW, so no idle robot is eligible for any task of WW. The idle set never grows, so this stays true in later rounds, also for the tasks closed earlier. □\square

Theorem 1 (termination). The protocol stops after at most tt rounds.

Proof. In each round, either some robot bids, and then at least one task gets an award in line L7 and leaves the open list, or no robot bids, and then all tasks of the nonempty window leave the open list in line L5. So the open list loses at least one task per round, and it starts with tt tasks. □\square

Theorem 2 (maximality). When the protocol stops, no idle robot is eligible for a task without an award.

Proof. At the end the open list is empty, so every task without an award was closed in line L5. Apply (c) of Lemma 1. □\square

Consider the bipartite graph with an edge from robot ii to task jj when ii is eligible for jj. By Lemma 1 the awards are a matching MM in this graph, and by Theorem 2 the matching is maximal: no edge has both ends free.

Corollary 3 (half of the maximum number of tasks). ∣M∣≥12∣M∗∣|M| \ge \frac12 |M^*| for every matching M∗M^*, in particular for a maximum one.

Proof. Every edge of M∗M^* has an end that MM covers, by maximality. Each edge of MM covers two ends, and two edges of M∗M^* never share an end. So ∣M∗∣≤2∣M∣|M^*| \le 2 |M|. □\square

Theorem 4 (the cheapest pair). With the full window, the eligible pair (i,j)(i, j) with the smallest bid cijc_{ij} (ties to the smaller task, then to the smaller robot) is awarded in the first round.

Proof. In round 1 all tasks are open and all robots are idle. Robot ii's cheapest task is jj, so it bids on jj. Every other bid on jj is at least cijc_{ij}, and a tie goes to the smaller robot index, which is ii by the choice of the pair. So the manager of jj awards it to ii. □\square

Theorem 5 (no bound on the cost ratio). For every M>2M > 2 there is an instance with r=t=2r = t = 2 on which the protocol, with the full window or with a window of one task, returns cost 1+M1 + M, while the minimum cost assignment of both tasks costs 44.

Proof. Let c00=1c_{00} = 1, c01=2c_{01} = 2, c10=2c_{10} = 2, c11=Mc_{11} = M. With the full window, in round 1 both robots find task 0 cheapest and bid on it, and robot 0 wins it with bid 1. In round 2 robot 1 bids MM on task 1 and wins it. The total is 1+M1 + M. With a window of one task the rounds are the same. The other assignment, robot 0 to task 1 and robot 1 to task 0, costs 2+2=42 + 2 = 4. □\square

So the protocol is a greedy heuristic for the cost. When the robots can do any task and r≥tr \ge t, every task gets an award by Theorem 2, but the total cost has no constant factor bound. The test test_ratio_to_optimum_is_unbounded checks the instance above, and test_cost_at_least_optimum_and_all_tasks_awarded compares the cost with a brute force minimum over all assignments.

Messages. An announcement of one task goes to all rr robots. In a round with window WW there are r∣W∣r |W| announcement messages, at most rr bids and at most min⁡(r,∣W∣)\min(r, |W|) awards. With a window of one task, each round handles exactly one task, so there are exactly tt rounds, rtr t announcements, at most rtr t bids and at most min⁡(r,t)\min(r, t) awards. With the full window, the window shrinks by at least one task per round, so the announcements are at most r(t+(t−1)+⋯+1)=rt(t+1)/2r (t + (t - 1) + \dots + 1) = r t (t + 1) / 2, and the bids at most rtr t.

Window of one task. With a window of one task, round kk is a sealed-bid auction of the kk-th task in the given order among the idle eligible robots, won by the lowest bid. So the protocol is the same as a sequence of single-item auctions, and the test test_batch_one_equals_sequential_auctions checks this.

Complexity

  • Rounds (theorem). At most tt; exactly tt with a window of one task.
  • Messages (theorem). A round with window WW sends r∣W∣r |W| announcements, at most rr bids and at most min⁡(r,∣W∣)\min(r, |W|) awards. With a window of one task the total is rtr t announcements, at most rtr t bids and at most min⁡(r,t)\min(r, t) awards. With the full window the announcements are at most rt(t+1)/2r t (t + 1) / 2.
  • Work (theorem). In a round each idle robot scans the window, O(r∣W∣)O(r |W|) operations in the real RAM model, so O(rt2)O(r t^2) in total with the full window and O(rt)O(r t) with one task per round.
  • Memory. A robot keeps its own costs and its state; a manager keeps the bids of one round, at most rr numbers.

Properties

  • Decentralized decisions. Each manager decides only its own task, and each robot prices only its own work. No agent needs the whole cost matrix.
  • Greedy and final. Awards are never taken back, so a bad early award stays. This is why the cost ratio is unbounded.
  • Maximal. Every task that some idle robot could do gets an award (theorem).
  • Order dependent. With one task per round, the result depends on the announcement order, as in the example.
  • Online. A task that appears later is announced in a later round, and the protocol needs no change.
  • Deterministic with the fixed tie rules above.

Variants and improvements

  • Sequential single-item auctions. The window of one task, used by many robot systems, for example MURDOCH of Gerkey and Matarić; see market-based task allocation.
  • Re-auction and trading. A robot may sell a task it holds when a cheaper robot appears; TraderBots and other market systems in the survey of Dias et al. (2006) do this, which removes some bad early awards (heuristic).
  • Bundles. Robots bid on sets of tasks, as in the consensus-based bundle algorithm or in combinatorial auctions, when the cost of a task depends on the other tasks of the robot.
  • Optimal assignment. When the costs are known and one robot or one server can collect them, the Hungarian algorithm gives the minimum cost in O(n3)O(n^3) time with n=max⁡(r,t)n = \max(r, t), and the auction algorithm reaches it within ε\varepsilon by distributed bidding.
  • Lost messages and time-outs. Smith's protocol has expiration times on announcements and bids, so a manager that hears nothing can announce again.

When to use it

Use the contract net when tasks arrive over time, robots know their own costs best, and a quick valid assignment matters more than the optimal one. It suits teams with a reliable broadcast channel and a few tens of robots. Do not use it when the total cost must be near optimal, or when the value of a task depends on the other tasks of the robot; then use an optimal assignment or a bundle method.

Pitfalls

  • Double awards. If a robot may bid on several tasks in one round, two managers can award it at the same time. Bid on one task per round, as in line L4, or let robots refuse an award.
  • Closing tasks too early. A task with no bid in one round may get a bid later from a robot that lost elsewhere. Close the window only when no robot bid on anything.
  • Expecting a cost bound. Maximality bounds the number of tasks, not the cost (theorem); the ratio to the optimum can be arbitrarily large.
  • Order effects. With one task per round, the order of announcements changes the result. Announce the most constrained tasks first if you know them (heuristic).
  • Stale costs. A bid is a promise based on the robot's state at bid time. If the robot moves before the award, the cost is no longer true.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

contract_net_protocol.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/contract-net-protocol/. The authors are listed in prov/JAEWRV.jsonl.

"""Contract net protocol (Smith 1980) for single-task robots, in synchronous rounds.

Robots are 0..r-1 and tasks are 0..t-1. cost[i][j] is the bid of robot i for
task j, a number, or None when robot i is not eligible for task j. Each task has
a manager that announces it, collects bids and awards it. Each robot does at most
one task (single-task robots), and in each round an idle robot bids only on the
announced task it likes best, so it can never win two tasks at once.

The function counts the messages: an announcement goes to every robot (r
messages per announced task), a bid is one message, and an award is one message.
"""

from typing import Optional, Sequence


def contract_net(
    cost: Sequence[Sequence[Optional[float]]],
    batch: Optional[int] = None,
    order: Optional[Sequence[int]] = None,
) -> dict:
    """Run the protocol until every task is awarded or cannot be awarded.

    batch is the number of open tasks announced in each round (None means all
    of them). order is the order in which the managers announce their tasks
    (default 0..t-1). With batch=1 the protocol is a sequence of single-item
    auctions in the given order.

    Returns a dict with award (task -> robot), the total cost, the number of
    rounds and the message counts.
    """
    r = len(cost)
    t = len(cost[0]) if r else 0
    order = list(range(t)) if order is None else list(order)
    if sorted(order) != list(range(t)):
        raise ValueError("order must be a permutation of the tasks")
    open_tasks = list(order)  # @line L1
    idle = set(range(r))
    award = {}
    msgs = {"announce": 0, "bid": 0, "award": 0}
    rounds = 0
    while open_tasks:  # @line L2
        rounds += 1
        window = list(open_tasks if batch is None else open_tasks[:batch])
        msgs["announce"] += r * len(window)  # @line L3
        bids = {}
        for i in sorted(idle):  # @line L4
            best = None
            for j in window:
                c = cost[i][j]
                if c is not None and (best is None or (c, j) < best):
                    best = (c, j)
            if best is not None:
                bids.setdefault(best[1], []).append((best[0], i))
                msgs["bid"] += 1
        if not bids:  # @line L5
            # No idle robot is eligible for any task in the window. Robots
            # never become idle again, so these tasks can never be awarded.
            open_tasks = [j for j in open_tasks if j not in window]
            continue
        for j in window:  # @line L6
            if j in bids:
                c, i = min(bids[j])  # @line L7
                award[j] = i
                msgs["award"] += 1
                idle.discard(i)
                open_tasks.remove(j)
    total = sum(cost[i][j] for j, i in award.items())
    return {"award": award, "cost": total, "rounds": rounds, "messages": msgs}  # @line L8
test_contract_net_protocol.py 156 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/contract-net-protocol/. The authors are listed in prov/JAEWRV.jsonl.

import itertools
import random
from fractions import Fraction

from contract_net_protocol import contract_net


def random_costs(rng, r, t, gaps=False):
    cost = []
    for _ in range(r):
        row = []
        for _ in range(t):
            if gaps and rng.random() < 0.35:
                row.append(None)
            else:
                row.append(Fraction(rng.randint(1, 50)))
        cost.append(row)
    return cost


def brute_min_cost_all_tasks(cost):
    """Brute force: the cheapest way to give every task to a different robot."""
    r, t = len(cost), len(cost[0])
    best = None
    for robots in itertools.permutations(range(r), t):
        cs = [cost[robots[j]][j] for j in range(t)]
        if any(c is None for c in cs):
            continue
        total = sum(cs)
        if best is None or total < best:
            best = total
    return best


def brute_max_matching(cost):
    """Brute force: the largest number of tasks that robots can do, one each."""
    r, t = len(cost), len(cost[0])
    best = 0
    for choice in itertools.product(range(-1, r), repeat=t):
        used = [i for i in choice if i >= 0]
        if len(used) != len(set(used)):
            continue
        if all(i < 0 or cost[i][j] is not None for j, i in enumerate(choice)):
            best = max(best, len(used))
    return best


def sequential_auctions(cost, order):
    """Reference: announce one task at a time; the cheapest idle robot wins."""
    idle = set(range(len(cost)))
    award = {}
    for j in order:
        bids = [(cost[i][j], i) for i in idle if cost[i][j] is not None]
        if bids:
            c, i = min(bids)
            award[j] = i
            idle.discard(i)
    return award


def check_valid(cost, award):
    robots = list(award.values())
    assert len(robots) == len(set(robots))
    for j, i in award.items():
        assert cost[i][j] is not None


def test_hand_example_parallel_and_sequential():
    cost = [[1, 2], [10, 3], [Fraction(3, 2), Fraction(5, 2)]]
    par = contract_net(cost)
    assert par["award"] == {0: 0, 1: 1}
    assert par["cost"] == 4
    assert par["rounds"] == 1
    assert par["messages"] == {"announce": 6, "bid": 3, "award": 2}
    seq = contract_net(cost, batch=1)
    assert seq["award"] == {0: 0, 1: 2}
    assert seq["cost"] == Fraction(7, 2)
    assert seq["rounds"] == 2
    assert seq["messages"] == {"announce": 6, "bid": 5, "award": 2}
    assert brute_min_cost_all_tasks(cost) == Fraction(7, 2)


def test_ratio_to_optimum_is_unbounded():
    for big in (10, 99, 10**6):
        cost = [[1, 2], [2, big]]
        res = contract_net(cost)
        assert res["award"] == {0: 0, 1: 1}
        assert res["cost"] == 1 + big
        assert brute_min_cost_all_tasks(cost) == 4


def test_cost_at_least_optimum_and_all_tasks_awarded():
    rng = random.Random(7)
    for _ in range(150):
        r = rng.randint(1, 6)
        t = rng.randint(1, r)
        cost = random_costs(rng, r, t)
        res = contract_net(cost)
        check_valid(cost, res["award"])
        assert len(res["award"]) == t
        assert res["cost"] >= brute_min_cost_all_tasks(cost)
        assert res["rounds"] <= t


def test_batch_one_equals_sequential_auctions():
    rng = random.Random(11)
    for _ in range(200):
        r = rng.randint(1, 6)
        t = rng.randint(1, 6)
        cost = random_costs(rng, r, t, gaps=True)
        order = list(range(t))
        rng.shuffle(order)
        res = contract_net(cost, batch=1, order=order)
        assert res["award"] == sequential_auctions(cost, order)


def test_maximal_and_half_of_maximum():
    rng = random.Random(3)
    for _ in range(200):
        r = rng.randint(1, 5)
        t = rng.randint(1, 5)
        cost = random_costs(rng, r, t, gaps=True)
        res = contract_net(cost)
        award = res["award"]
        check_valid(cost, award)
        busy = set(award.values())
        for i in range(r):
            for j in range(t):
                if i not in busy and j not in award:
                    assert cost[i][j] is None
        assert 2 * len(award) >= brute_max_matching(cost)
        assert res["rounds"] <= t
        msgs = res["messages"]
        assert msgs["award"] == len(award)
        assert msgs["bid"] <= r * res["rounds"]


def test_cheapest_pair_always_awarded():
    rng = random.Random(5)
    for _ in range(100):
        r = rng.randint(1, 6)
        t = rng.randint(1, 6)
        cost = random_costs(rng, r, t)
        c, j, i = min((cost[i][j], j, i) for i in range(r) for j in range(t))
        res = contract_net(cost)
        assert res["award"][j] == i


def test_no_robots_or_no_eligible_robot():
    assert contract_net([[None, None], [None, None]])["award"] == {}
    res = contract_net([[None, 4]], batch=1)
    assert res["award"] == {1: 0}
    assert res["rounds"] == 2

History

Reid Smith proposed the contract net in his work on distributed problem solving, and published the protocol with its message formats in 1980. Randall Davis and Smith described it in 1983 as negotiation between managers and contractors. In robotics, auction protocols built on the contract net appeared around 2000, and Gerkey and Matarić (2004) analyzed them in their taxonomy of task allocation. Dias, Zlot, Kalra and Stentz (2006) surveyed the market-based methods that grew from it.

References

  1. Reid G. Smith, The contract net protocol, high-level communication and control in a distributed problem solver, IEEE Transactions on Computers C-29(12), 1980, pages 1104 to 1113 (task announcement, bid, award and the message formats)
  2. Brian P. Gerkey and Maja J. Mataric, A formal analysis and taxonomy of task allocation in multi-robot systems, International Journal of Robotics Research 23(9), 2004, pages 939 to 954 (the single-task, single-robot, instantaneous class and the analysis of greedy auction methods)
  3. M. Bernardine Dias, Robert Zlot, Nidhi Kalra and Anthony Stentz, Market-based multirobot coordination, a survey and analysis, Proceedings of the IEEE 94(7), 2006, pages 1257 to 1270 (single-item auctions and the contract net in robot teams)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.per_round
  • a full proof of time.total
  • a full proof of space.extra
  • a full proof of messages.full_window
  • a full proof of messages.one_task_window
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example