text
stringlengths
2
132k
source
dict
12.7 Hamilton Cycles Learning Objectives ------------------- **After completing this section, you should be able to:** 1. Calculate the expected value of an experiment. 2. Interpret the expected value of an experiment. 3. Use expected value to analyze applications. The casino game roulette has dozens of different bets that can be made. These bets have different probabilities of winning but also have different payouts. In general, the lower the probability of winning a bet is, the more money a player wins for that bet. With so many options, is there one bet that’s “smarter” than the rest?
{ "page_id": null, "source": 6845, "title": "from dpo" }
What’s the best play to make at a roulette table? In this section, we’ll develop the tools we need to answer these questions. Expected Value -------------- Many experiments have numbers associated with their outcomes. Some are easy to define; if you roll 2 dice, the sum of the numbers showing is a good example. In some card games, cards have different point values associated with them; for example, in some forms of the game rummy, aces are worth 15 points; 10s, jacks, queens, and kings are worth 10; and all other cards are worth 5. The outcomes of casino and lottery games are all associated with an amount of money won or lost. These outcome values are used to find the expected value of an experiment: the mean of the values associated with the outcomes that we would observe over a large number of repetitions of the experiment. (See Conditional Probability and the Multiplication Rule That definition is a little vague; How many is “a large number?” In practice, it depends on the experiment; the number has to be large enough that every outcome would be expected to appear at least a few times. For example, if we’re talking about rolling a standard 6-sided die and we note the number showing, a few dozen replications should be enough that the mean would be representative. Since the probability of each outcome is 1 6 1 6 1 6, we would expect to see each outcome about 8 times over the course of 48 replications. However, if we’re talking about the Powerball lottery, where the probability of winning the jackpot is about 1 292,000,000 1 292,000,000 1 292,000,000, we would need several _billion_ replications to ensure that every outcome appears a few times. Luckily, we can find the
{ "page_id": null, "source": 6845, "title": "from dpo" }
theoretical expected value before we even run the experiment the first time. FORMULA ------- Expected Value: If O O O represents an outcome of an experiment and n(O)n(O)n(O) represents the value of that outcome, then the expected value of the experiment is: ∑n(O)×P(O)∑n(O)×P(O)∑n(O)×P(O) , where Σ Σ Σ is the “sum,” meaning we add up the results of the formula that follows over all possible outcomes. Example 7.37 ------------ ### Finding Expected Values Find the expected values of the following experiments. 1. Roll a standard 6-sided die and note the number showing. 2. Roll two standard 6-sided dice and note the sum of the numbers showing. 3. Draw a card from a well-shuffled standard deck of cards and note its rummy value (15 for aces; 10 for tens, jacks, queens, and kings; 5 for everything else). ### Solution 1. **Step 1:** Let’s start by writing out the PDF table for this experiment. | Value | Probability | | --- | --- | | 1 | 1 6 1 6 1 6 | | 2 | 1 6 1 6 1 6 | | 3 | 1 6 1 6 1 6 | | 4 | 1 6 1 6 1 6 | | 5 | 1 6 1 6 1 6 | | 6 | 1 6 1 6 1 6 | **Step 2:** To find the expected value, we need to find n(O)×P(O)n(O)×P(O)n(O)×P(O) for each possible outcome in the table below. | Value | Probability | n(O)×P(O)n(O)×P(O)n(O)×P(O) | | --- | --- | --- | | 1 | 1 6 1 6 1 6 | 1×1 6=1 6 1×1 6=1 6 1×1 6=1 6 | | 2 | 1 6 1 6 1 6 | 2×1 6=1 3 2×1 6=1 3 2×1 6=1 3 | | 3 | 1
{ "page_id": null, "source": 6845, "title": "from dpo" }
6 1 6 1 6 | 3×1 6=1 2 3×1 6=1 2 3×1 6=1 2 | | 4 | 1 6 1 6 1 6 | 4×1 6=2 3 4×1 6=2 3 4×1 6=2 3 | | 5 | 1 6 1 6 1 6 | 5×1 6=5 6 5×1 6=5 6 5×1 6=5 6 | | 6 | 1 6 1 6 1 6 | 6×1 6=1 6×1 6=1 6×1 6=1 | **Step 3:** We add all of the values in that last column: 1 6+1 3+1 2+2 3+5 6+1=7 2=3.5 1 6+1 3+1 2+2 3+5 6+1=7 2=3.5 1 6+1 3+1 2+2 3+5 6+1=7 2=3.5. So, the expected value of a single roll of a die is 3.5. 2. Back in [Example 7.18]( we made this table of all of the equally likely outcomes ([Figure 7.47]( ![Image 10: A table with 6 rows and 6 columns. The columns represent the first die and are titled, 1, 2, 3, 4, 5, and 6. The rows represent the second die and are titled, 1, 2, 3, 4, 5, and 6. The data is as follows: Row 1: 2, 3, 4, 5, 6, 7. Row 2: 3, 4, 5, 6, 7, 8. Row 3: 4, 5, 6, 7, 8, 9. Row 4: 5, 6, 7, 8, 9, 10. Row 5: 6, 7, 8, 9, 10, 11. Row 6: 7, 8, 9, 10, 11, 12.]( 7.47 **Step 1:** Let’s use [Figure 7.47]( to create the PDF for this experiment, as shown in the following table: | Value | Probability | | --- | --- | | 2 | 1 36 1 36 1 36 | | 3 | 1 18 1 18 1 18 | | 4 | 1 12 1 12 1 12 | | 5 | 1 9 1 9 1
{ "page_id": null, "source": 6845, "title": "from dpo" }
9 | | 6 | 5 36 5 36 5 36 | | 7 | 1 6 1 6 1 6 | | 8 | 5 36 5 36 5 36 | | 9 | 1 9 1 9 1 9 | | 10 | 1 12 1 12 1 12 | | 11 | 1 18 1 18 1 18 | | 12 | 1 36 1 36 1 36 | **Step 2:** We can multiply each row to find n(O)×P(O)n(O)×P(O)n(O)×P(O)as shown in the following table: | Value | Probability | n(O)×P(O)n(O)×P(O)n(O)×P(O) | | --- | --- | --- | | 2 | 1 36 1 36 1 36 | 1 18 1 18 1 18 | | 3 | 1 18 1 18 1 18 | 1 6 1 6 1 6 | | 4 | 1 12 1 12 1 12 | 1 3 1 3 1 3 | | 5 | 1 9 1 9 1 9 | 5 9 5 9 5 9 | | 6 | 5 36 5 36 5 36 | 5 6 5 6 5 6 | | 7 | 1 6 1 6 1 6 | 7 6 7 6 7 6 | | 8 | 5 36 5 36 5 36 | 10 9 10 9 10 9 | | 9 | 1 9 1 9 1 9 | 1 1 1 | | 10 | 1 12 1 12 1 12 | 5 6 5 6 5 6 | | 11 | 1 18 1 18 1 18 | 11 18 11 18 11 18 | | 12 | 1 36 1 36 1 36 | 1 3 1 3 1 3 | **Step 3:** We can add the last column to get the expected value: 1 18+1
{ "page_id": null, "source": 6845, "title": "from dpo" }
6+1 3+5 9+5 6+7 6+10 9+1+5 6+11 18+1 3=7 1 18+1 6+1 3+5 9+5 6+7 6+10 9+1+5 6+11 18+1 3=7 1 18+1 6+1 3+5 9+5 6+7 6+10 9+1+5 6+11 18+1 3=7 . So, the expected value is 7. 3. **Step 1:** Let’s make a PDF table for this experiment. There are 3 events that we care about, so let’s use those events in the table below: | Event | Probability | | --- | --- | | {A} | 1 13 1 13 1 13 | | {10, J, Q, K} | 4 13 4 13 4 13 | | {2, 3, 4, 5, 6, 7, 8, 9} | 8 13 8 13 8 13 | **Step 2:** Let’s add a column to the following table for the values of each event: | Event | Probability | Value | | --- | --- | --- | | {A} | 1 13 1 13 1 13 | 15 | | {10, J, Q, K} | 4 13 4 13 4 13 | 10 | | {2, 3, 4, 5, 6, 7, 8, 9} | 8 13 8 13 8 13 | 5 | **Step 3:** We’ll add the column for the product of the values and probabilities to the table below: | Event | Probability | Value | n(O)×P(O)n(O)×P(O)n(O)×P(O) | | --- | --- | --- | --- | | {A} | 1 13 1 13 1 13 | 15 | 15 13 15 13 15 13 | | {10, J, Q, K} | 4 13 4 13 4 13 | 10 | 40 13 40 13 40 13 | | {2, 3, 4, 5, 6, 7, 8, 9} | 8 13 8 13 8 13 | 5 | 40 13 40 13 40 13 | **Step 4:** We’ll find the
{ "page_id": null, "source": 6845, "title": "from dpo" }
sum of the last column: 15 13+40 13+40 13=95 13≈7.3 15 13+40 13+40 13=95 13≈7.3 15 13+40 13+40 13=95 13≈7.3. Thus, the expected _Rummy_ value of a randomly selected card is about 7.3. Your Turn 7.37 -------------- 1 was just the mean of the numbers on the faces of the die: 1+2+3+4+5+6 6=3.5 1+2+3+4+5+6 6=3.5 1+2+3+4+5+6 6=3.5. This is no accident! If we break that fraction up using the addition in the numerator, we get 1 6+2 6+3 6+4 6+5 6+6 6 1 6+2 6+3 6+4 6+5 6+6 6 1 6+2 6+3 6+4 6+5 6+6 6, which we can rewrite as 1×1 6+2×1 6+3×1 6+4×1 6+5×1 6+6×1 6 1×1 6+2×1 6+3×1 6+4×1 6+5×1 6+6×1 6 1×1 6+2×1 6+3×1 6+4×1 6+5×1 6+6×1 6. That’s exactly the computation we did to find the expected value! In fact,
{ "page_id": null, "source": 6845, "title": "from dpo" }
expected values can always be treated as a special kind of mean called a **weighted mean**, where the weights are the probabilities associated with each value. When the probabilities are all equal, the weighted mean is just the regular mean. Interpreting Expected Values ---------------------------- As we noted, the expected value of an experiment is the mean of the values we would observe if we repeated the experiment a large number of times. (This interpretation is due to an important theorem in the theory of probability called the Law of Large Numbers.) Let’s use that to interpret the results of the previous example. ### Solution 1. If you roll a standard 6-sided die many times, the mean of the numbers you roll will be around 3.5. 2. If you roll a pair of standard 6-sided dice many times, the mean of the sums of the numbers you roll will be about 7. 3. If you draw a card from a well-shuffled deck many times, the mean of the _Rummy_ values of the cards would be around 7.3. Your Turn 7.38 -------------- ( Interpret the expected value of the number showing when you roll a special 6-sided die with faces {1, 1, 2, 3, 5, 8}. ( Interpret the expected value of the number of heads showing if you flip a coin 3 times. ( You are about to play a game
{ "page_id": null, "source": 6845, "title": "from dpo" }
where you flip a coin 3 times. If all 3 flips result in heads, you win $20. If you get 2 heads, you win $10. If you flip 1 or 0 heads, you win nothing. Interpret the expected value of your winnings. Who Knew? --------- ### Pascal’s Wager The French scholar Blaise Pascal (1623–1662) was among the earliest mathematicians to study probabilities, and was the first to accurately describe and compute expected values. In his book _Pensées_ (_Thoughts_), he turned the analysis of expected values to his belief in the Christian God. He said that there is no way for people to establish the probability that God exists, but since the “winnings” on a bet that God exists (and that you then lead your life accordingly) are essentially infinite, the expected value of taking that bet is always positive, no matter how unlikely it is that God exists. Using Expected Value -------------------- Now that we know how to find and interpret expected values, we can turn our attention to using them. Suppose someone offers to play a game with you. If you roll a die and get a 6, you get $10. However, if you get a 5 or below, you lose $1. Is this a game you’d want to play? Let’s look at the expected value: The probability of winning is 1 6 1 6 1 6 and the probability of losing is 5 6 5 6 5 6, so the expected value is $10×1 6+(−$1)×5 6=5 6≈$0.83$10×1 6+(−$1)×5 6=5 6≈$0.83$10×1 6+(−$1)×5 6=5 6≈$0.83. That means, on average, you’ll come out ahead by about 83 cents every time you play this game. It’s a great deal! On the other hand, if the winnings for rolling a 6 drop to $3, the expected value becomes $3×1 6+(−$1)×5 6=−1 3≈−$0.33$3×1 6+(−$1)×5
{ "page_id": null, "source": 6845, "title": "from dpo" }
6=−1 3≈−$0.33$3×1 6+(−$1)×5 6=−1 3≈−$0.33, meaning you should expect to lose about 33 cents on average for every time you play. Playing that game is not a good idea! In general, this is how casinos and lottery corporations make money: Every game has a negative expected value for the player. Who Knew? --------- ### Expected Values in Football In the 21st century, data analytics tools have revolutionized the way sports are coached and played. One tool in particular is used in football at crucial moments in the game. When a team faces a fourth down (the last possession in a series of four possessions, a fairly common occurrence), the coach faces a decision: Run one play to try to gain a certain number of yards, or kick the ball away to the other team. Here’s the interesting part of the decision: If the team “goes for it” and runs the play and they are successful, then they keep possession of the ball and can continue in their quest to score more points. If they are unsuccessful, then they lose possession of the ball, giving the other team an opportunity to score points. If, instead, the team punts, or kicks the ball away, then the other team gets possession of the ball, but in a worse position for them than if the original team goes for it and fails. To analyze this situation, data analysts have generated empirical probabilities for every fourth down situation, and computed the expected value (in terms of points) for each decision. Coaches frequently use those calculations when they decide which option to take! People in Mathematics --------------------- ### Pierre de Fermat and Blaise Pascal In 1654, a French writer and amateur mathematician named Antoine Gombaud (who called himself the Chevalier du Mére) reached out to his
{ "page_id": null, "source": 6845, "title": "from dpo" }
gambling buddy Blaise Pascal to answer a question that he’d read about called the “problem of points.” The question goes like this: Suppose you’re playing a game that is scored using points, and the first person to earn 5 points is the winner. The game is interrupted with the score 4 points to 2. If the winner stood to win $100, how should the prize money be divided between the players? Certainly the person who is 1 point away from victory should get more, but _how much_ more? We have developed tools in this section to answer this question. At its heart, it’s a question about conditional probabilities and expected value. At the time that Pascal first started thinking about it, though, those ideas hadn’t yet been invented. Pascal reached out to a colleague named Pierre de Fermat, and over the course of a couple of months, their correspondence with each other would eventually solve the problem. In the process, they first described conditional probabilities and expected values! Apart from their work in probability, these men are famous for other work in mathematics (and, in Pascal’s case, philosophy and physics). Fermat is remembered for his work in geometry and in number theory. After his death, the statement of what came to be called “Fermat’s Last Theorem” was discovered scribbled in the margin of a book, with the note that Fermat had discovered a “marvelous proof that this margin is too small to contain.” The theorem says that any equation of the form a n+b n=c n a n+b n=c n a n+b n=c n has no positive integer solutions if n≥3 n≥3 n≥3. No proof of that theorem was discovered until 1994, when Andrew Wiles used computers and new branches of geometry to finally prove the theorem! Pascal is remembered
{ "page_id": null, "source": 6845, "title": "from dpo" }
for the “arithmetical triangle” that is named for him (though he wasn’t the first person to discover it; see the section on the binomial distribution, as well as work in geometry. In physics, Pascal worked on hydrodynamics and air pressure (the SI unit for pressure is named for him), and in philosophy, Pascal advocated for a mathematical approach to philosophical problems. Example 7.39 ------------ ### Using Expected Values In the casino game keno, a machine chooses at random 20 numbers between 1 and 80 (inclusive) without replacement. Players try to predict which numbers will be chosen. Players don’t try to guess all 20, though; generally, they’ll try to predict between 1 and 10 of the chosen numbers. The amount won depends on the number of guesses they made and the number of guesses that were correct. 1. At one casino, a player can try to guess just 1 number. If that number is among the 20 selected, the player wins $2; otherwise, the player loses $1. What is the expected value? 2. At the same casino, if a player makes 2 guesses and they’re both correct, the player wins $14; otherwise, the player loses $1. What is the expected value? 3. Players can also make 3 guesses. If 2 of the 3 guesses are correct, the player wins $1. If all 3 guesses are correct, the player wins $42. Otherwise, the player loses $1. What is the expected value? 4. Which of these games is the best for the player? Which is the best for the casino? ### Solution 1. There are 20 winning numbers out of 80, so if we try to guess one of them, the probability of guessing correctly is 20 80=1 4 20 80=1 4 20 80=1 4. The probability of losing is then
{ "page_id": null, "source": 6845, "title": "from dpo" }
3 4 3 4 3 4, and so the expected value is $2×1 4+(−$1)×3 4=−$0.25$2×1 4+(−$1)×3 4=−$0.25$2×1 4+(−$1)×3 4=−$0.25. 2. There are 20 C 2=190 20 C 2=190 20 C 2=190 winning choices out of 80 C 2=3,160 80 C 2=3,160 80 C 2=3,160 total ways to choose 2 numbers. So, the probability of winning is 190 3,160 190 3,160 190 3,160 and the probability of losing is 3,160−190 3,160=2,970 3,160 3,160−190 3,160=2,970 3,160 3,160−190 3,160=2,970 3,160. So, the expected value of the game is $14×190 3,160+(−$1)×2970 3160≈−$0.10$14×190 3,160+(−$1)×2970 3160≈−$0.10$14×190 3,160+(−$1)×2970 3160≈−$0.10. 3. **Step 1:** Let’s start with the big prize. There are 20 C 3=1,140 20 C 3=1,140 20 C 3=1,140 ways to correctly guess 3 winning numbers out of 80 C 3=82,160 80 C 3=82,160 80 C 3=82,160 ways to guess three numbers total. That means the probability of winning the big prize is 1,140 82,160≈0.01388 1,140 82,160≈0.01388 1,140 82,160≈0.01388. **Step 2:** Let’s find the probability of the second prize. The denominator is the same: 82,160. Let’s figure out the numerator. To win the second prize, the player must pick 2 of the 20 winning numbers and one of the 60 losing numbers. The number of ways to do that can be found using the Multiplication Rule for Counting: there are 20 C 2=190 20 C 2=190 20 C 2=190 ways to pick 2 winning numbers and 60 ways to pick 1 losing number, so there are 190×60=11,400 190×60=11,400 190×60=11,400 ways to win the second prize. So, the probability of winning that second prize is 11,400 82,160≈0.13875 11,400 82,160≈0.13875 11,400 82,160≈0.13875. **Step 3:** Since the overall probability of winning is 1,140 82,160+11,400 82,160=12,540 82,160≈0.15263 1,140 82,160+11,400 82,160=12,540 82,160≈0.15263 1,140 82,160+11,400 82,160=12,540 82,160≈0.15263, the probability of losing must be 1−0.15263=0.84737 1−0.15263=0.84737 1−0.15263=0.84737. So, the expected value is $42×0.01388+$1×0.13875+(−$1)×0.84737≈−$0.13$42×0.01388+$1×0.13875+(−$1)×0.84737≈−$0.13$42×0.01388+$1×0.13875+(−$1)×0.84737≈−$0.13. 4.
{ "page_id": null, "source": 6845, "title": "from dpo" }
The bet that’s the best for the player is the one with the highest expected value for the player, which is guessing two numbers. The best one for the casino is the one with the lowest expected value for the player, which is guessing one number. Your Turn 7.39 -------------- The casino game craps involves rolling 2 standard 6-sided dice. While the main game involves repeated rolls of the dice, players can also bet on the outcomes of single rolls. Find the expected values of the following three $1 bets. Then decide which bet is the best for the player and which bet is the best for the casino. 1. Winners get $7 and losers lose $1. WORK IT OUT ----------- ### Make Your Own Lottery By yourself or with a partner, devise your own lottery scheme. Assume you would have access to one or more machines that choose numbers randomly. What will a lottery draw look like? How many numbers are players choosing from? How many will be drawn? Will they be drawn with replacement or without replacement? What conditions must be met for a player to win first or second (or more!) prize? Once you’ve decided that, decide the payoff structure for winners, and how much the game will cost to play. Try to make the game enticing enough that people will want to play it, but with enough negative expected
{ "page_id": null, "source": 6845, "title": "from dpo" }
value that the lottery will make money. Aim for the expected value to be about −0.25 times the cost of playing the game. Check Your Understanding ------------------------ You are about to roll a 20-sided die with faces labeled as follows: 5 faces have a 1, 6 faces have a 3, 4 faces have a 5, 3 faces have a 7, and 2 faces have a 9. ( What is the expected value of the number showing on the die after it’s rolled? ( Interpret your answer. You are about to play a game in which you draw 3 ping-pong balls without replacement from a barrel. The barrel contains 6 green balls and 4 red balls. If all 3 of your selections are green, you win $5. If 2 of the 3 are green, you win $1. If 2 or more of your selections are red, you lose $5. ( What is the expected value of this game? ( Interpret your answer. ( Is it advantageous to you to play the game? How do you know? Section 7.11 Exercises ---------------------- You roll a standard 6-sided die and win points equal to the square of the number shown. 1. What’s the expected value of the number of points you win? 2. Interpret your answer. In the classic board game _The Game of Life_, players have the chance to play the market. A spinner with 10 equally likely spaces is spun to choose a random number. If the result is 3 or less, the player loses $25,000. If the result is 7 or more, the player wins $50,000. If the result is a 4, 5, or 6, the player doesn’t win or lose anything. 3. What is the expected value of playing the market? 4. Interpret the answer. _The Game of Life_ players
{ "page_id": null, "source": 6845, "title": "from dpo" }
also occasionally have the opportunity to speculate. Players choose any 2 of the 10 numbers on the spinner and then give it a spin. If one of their numbers is chosen, they win $140,000; if not, they lose $10,000. 5. What is the expected value of this speculation? 6. Interpret your answer. 7. Which is better for _The Game of Life_ players: playing the market or speculating? How do you know? A charitable organization is selling raffle tickets as a fundraiser. They intend to sell 5,000 tickets at $10 each. One ticket will be randomly selected to win the grand prize of a new car worth $35,000. 8. What is the expected value of a single ticket? 9. Interpret your answer. 10. The organization is worried they won’t be able to sell all the tickets, so they announce that, in addition to the grand prize, they will offer 10 second prizes of $500 in cash. What is the new expected value of a single ticket? 11. Interpret your answer. In the following exercises involve randomly selecting golf balls from a bucket. The bucket contains 4 yellow balls (numbered 1-4) and 6 white balls (numbered 1-6). 12. If you draw a single ball, what is the expected number of yellow balls selected? 13. Suppose you draw 2 balls _with_ replacement. 1. Give a PDF table for the possible outcomes for the number of yellow balls selected. 2. What is the expected number of yellow balls selected? 14. Suppose you draw 2 balls _without_ replacement. 1. Give a PDF table for the possible outcomes for the number of yellow balls selected. 2. What is the expected number of yellow balls selected? 15. Suppose you draw 3 balls _with_ replacement. 1. Give a PDF table for the possible outcomes for the number of
{ "page_id": null, "source": 6845, "title": "from dpo" }
yellow balls selected. 2. What is the expected number of yellow balls selected? 16. Suppose you draw 3 balls _without_ replacement. 1. Give a PDF table for the possible outcomes for the number of yellow balls selected. 2. What is the expected number of yellow balls selected? 17. If you draw a single ball, what is the expected value of the number on the ball? 18. Suppose you draw 2 balls _with_ replacement. 1. Give a PDF table for the possible outcomes for the sum of the numbers on the selected balls. 2. What is the expected sum of the numbers on the balls? 19. Suppose you draw 2 balls _without_ replacement. 1. Give a PDF table for the possible outcomes for the sum of the numbers on the selected balls. 2. What is the expected sum of the numbers on the balls? The following exercises deal with the game “Punch a Bunch,” which appears on the TV game show _The Price Is Right_. In this game, contestants have a chance to punch through up to 4 paper circles on a board; behind each circle is a card with a dollar amount printed on it. There are 50 of these circles; the dollar amounts are given in this table: | Dollar Amount | Frequency | | --- | --- | | $25,000 | 1 | | $10,000 | 2 | | $5,000 | 4 | | $2,500 | 8 | | $1,000 | 10 | | $500 | 10 | | $250 | 10 | | $100 | 5 | Contestants are shown their selected dollar amounts one at a time, in the order selected. After each is revealed, the contestant is given the option of taking that amount of money or throwing it away in favor of the next
{ "page_id": null, "source": 6845, "title": "from dpo" }
amount. (You can watch the game being played in the video Playing "Punch a Bunch." and a color (0 and 00 are both green; the other 36 numbers are evenly divided between black and red). Players make bets on which number (or groups of numbers) they think the marble will land on. The figure shows the layout of the numbers and colors, as well as some of the bets that can be made. ![Image 11: A Roulette table. The table has 12 rows and 3 columns. The first four rows represent the first dozen. The fifth to eighth rows represent the second dozen. The last four rows represent the third dozen.
{ "page_id": null, "source": 6845, "title": "from dpo" }
The columns represent 2 to 1, 2 to 1, and 2 to 1. Two green pockets, 0 and 00 are at the top-right. Six green pockets on the left represent 1 to 18, even, red, black, odd, and 19 to 36. The data from the table row-wise are as follows: 1 (red), 2 (black), 3 (red); 4 (black), 5 (red), 6 (black); 7 (red), 8 (black), 9 (red); 10 (black), 11 (black), 12 (red); 13 (black), 14 (red), 15 (black); 16 (red), 17 (black), 18 (red); 19 (red), 20 (black), 21 (red); 22 (black), 23 (red), 24 (black); 25 (red), 26 (black), 27 (red); 28 (black), 29 (black), 30 (red); 31 (black), 32 (red), 33 (black); 34 (red), 35 (black), and 36 (red).]( Roulette Table (credit: "American Roulette Table Layout" by Film8ker/Wikimedia Commons, Public Domain) 26. If a player makes a $1 bet on a single number, they win $35 if that number comes up, but lose $1 if it doesn’t. What is the expected value of this bet? 27. Interpret your answer to the previous question. 28. Suppose a player makes the $1 bet on a single number in 5 consecutive spins. What is the expected value of this series of bets? (Hint: use the Binomial Distribution.) 29. Interpret your answer to the previous question. 30. If a player makes a $10 bet on first dozen, they win $20 if one of the numbers 1–12 comes up but lose $10 otherwise. What is the expected value of this bet? 31. Interpret your answer to the previous question. 32. Suppose a player makes the $10 bet on first dozen in 4 consecutive spins. What is the expected value of that series of bets? 33. Interpret your answer to the previous question. 34. If a player makes a $10 basket bet,
{ "page_id": null, "source": 6845, "title": "from dpo" }
they win $60 if 0, 00, 1, 2, or 3 come up but lose $10 otherwise. What is the expected value of this bet? 35. Interpret your answer to previous question. 36. Which is better for the player: a $10 first dozen bet or a $10 basket bet? How do you know? [Previous]( [Order a print copy]( Citation/Attribution This book may not be used in the training of large language models or otherwise be ingested into large language models or generative AI offerings without OpenStax's permission. Want to cite, share, or modify this book? This book uses the [Creative Commons Attribution License]( and you must attribute OpenStax. **Attribution information** * If you are redistributing all or part of this book in a print format, then you must include on every physical page the following attribution: Access for free at * If you are redistributing all or part of this book in a digital format, then you must include on every digital page view the following attribution: Access for free at [ **Citation information** * Use the information below to generate a citation. We recommend using a citation tool such as [this one]( * Authors: Donna Kirk * Publisher/website: OpenStax * Book title: Contemporary Mathematics * Publication date: Mar 22, 2023 * Location: Houston, Texas * Book URL: [ * Section URL: [ © Oct 8, 2024 OpenStax. Textbook content produced by OpenStax is licensed under a Creative Commons Attribution License . **The OpenStax name, OpenStax logo, OpenStax book covers, OpenStax CNX name, and OpenStax CNX logo are not subject to the Creative Commons license and may not be reproduced without the prior and express written consent of Rice University.** Our mission is to improve educational access and learning for everyone. ----------------------------------------------------------------------- OpenStax is part of Rice University, which is
{ "page_id": null, "source": 6845, "title": "from dpo" }
a 501(c)(3) nonprofit. [Give today]( and help us reach more students. ### Help * [Contact Us]( * [Support Center]( * [FAQ]( ### OpenStax * [Press]( * [Newsletter]( * [Careers]( ### Policies * [Accessibility Statement]( * [Terms of Use]( * [Licensing]( * [Privacy Policy]( * Manage Cookies © 1999-2025, Rice University. Except where otherwise noted, textbooks on this site are licensed under a [Creative Commons Attribution 4.0 International License]( Advanced Placement® and AP® are trademarks registered and/or owned by the College Board, which is not affiliated with, and does not endorse, this site. * []( * []( * []( * []( * [![Image 12: Rice University logo](blob:
{ "page_id": null, "source": 6845, "title": "from dpo" }
Title: URL Source: Markdown Content: DISTRIBUTED ALGORITHMS 2015/2016 # Exercise Session 3 - Solutions Causal and Total Order Broadcast # Exercise 1 Can we devise a broadcast algorithm that does not ensure the causal delivery property but only its nonuniform variant: no correct process pi delivers a message m2 unless pi has already delivered every message m1 such that m1 → m2? The answer is no . Assume by contradiction that some algorithm does not ensure the causal delivery property but ensures its nonuniform variant. This means that the algorithm has some execution in which some process p delivers some message m without delivering a message m′ that causally precedes m.Given that we assume a model where processes do not self-destruct, p might as well be correct, in which case it violates even the nonuniform variant. # Exercise 2 Suggest an optimization of the garbage collection scheme of Algorithm 1’ (slide 24). When removing a message m from the past, we can also remove all the messages that causally precede this message — and then recursively those that causally precede these. This means that a message stored in the past must be stored with its own distinct past. # Exercise 3 Why the condition on slide 30 is VC [pk ] ≥ VC x [pk ] and not just VC [pk ] = VC x [pk ]? Can you construct an execution where the local vector clock is greater than the received local clock for one place? The greater or equal condition is important in order to handle old, non-causal messages. Just consider the case when in the beginning all processes send a message. Each message will carry a vector clock with all zeroes. When a process delivers one such message, the vector clock of the process gets incremented
{ "page_id": null, "source": 7318, "title": "from dpo" }
at a position matching the rank of the sender. During the next iteration, the process needs to deliver a message containing all zeroes in its vector clock, while the process has a non-zero value in at least one position. # Exercise 4 Can we devise a best-effort broadcast algorithm that satisfies the causal delivery property without being a causal broadcast algorithm, i.e., without satisfying the agreement property of a reliable broadcast? The answer is no. Assume by contradiction that some broadcast algorithm ensures the causal delivery property and is not reliable but best-effort; define an instance co of the corresponding abstraction, where processes co -broadcast and co -deliver messages. The only possibility for an algorithm to ensure the properties of best-effort broad- cast but not those of reliable broadcast is to violate the agreement property: there must be some execution of the algorithm where some correct process p co -delivers a message m that some other process q does not ever co -deliver. 1/3 DISTRIBUTED ALGORITHMS 2015/2016 Because the algorithm is best-effort, this can only happen if the process s that co -broadcasts the message is faulty. Assume now that after co -delivering m, process p co-broadcasts a message m’ . Given that p is correct and that the broadcast is best-effort, all correct processes, including q, will co -deliver m’ . Given that m precedes m’ in causal order, q must have co-delivered m as well, a contradiction. Hence, any best-effort broadcast that satisfies the causal delivery property satisfies agreement and is, thus, also a reliable broadcast. # Exercise 5 The Uniform Reliable Broadcast Algorithm requires a process to receive an acknowledgment from all nonfaulty processes before it can deliver a message. The acknowledgment is needed because when a process invokes the underlying best-effort broadcast and then crashes, all
{ "page_id": null, "source": 7318, "title": "from dpo" }
components of the process are affected and stop (including the best- effort broadcast module and any further underlying modules, such as the modules that may implement perfect links). The unit of failure is a process, not a module. For this exercise only, consider an idealized and nonrealistic system model, where some component may invoke infallible lower-level components. In this model, the unit of failure is not a process but a module. Describe an implementation of uniform reliable broadcast that uses an infallible perfect point-to-point links abstraction in this idealized model. Do not use failure detectors of any kind. Hint: You may get some inspiration from the solution to last week’s exercise 2. Suppose an “IdealPerfectPointToPointLinks” module is available in this idealized system model. In the following algorithm, the sender sends the broadcast message to itself over the ideal perfect links; upon delivering a message m over the ideal perfect links that has not been delivered yet, it resends m to all processes and urb -delivers it. Implements :UniformReliableBroadcast, instance urb . Uses :IdealPerfectPointToPointLinks, instance idealpl . upon event do delivered := ∅; upon event do trigger ; upon event do if m 6 ∈ delivered then delivered := delivered ∪ (m); forall q ∈ Π trigger ; trigger ;The uniform agreement property holds because every process sends m with the infallible point-to-point links primitive before it urb -delivers m. The infallible underlying module does not crash in this idealized model. If a process crashes, only the broadcast module crashes. Any urb -delivered message will never be forgotten by the ideal link module and will consequently be urb -delivered by every correct process. 2/3 DISTRIBUTED ALGORITHMS 2015/2016 # Exercise 6 Would it make sense to add the total-order property to the best-effort broadcast? The resulting abstraction would not make much sense
{ "page_id": null, "source": 7318, "title": "from dpo" }
in a failure-prone environment, as it would not preclude the following scenario. Assume that a process p broadcasts several messages with best-effort properties and then crashes. Some correct processes might end up delivering all those messages (in the same order) whereas other correct processes might end up not delivering any message. # Exercise 7 What happens in our consensus-based total order broadcast algorithm if the set of messages decided on is not sorted deterministically a) after the decision but is sorted prior to the proposal, If the deterministic sorting is done prior to proposing the set for consensus, instead of a posteriori upon deciding, the processes would not agree on a set but on a sequence of messages. But if they to-deliver the messages in decided order, the algorithm still ensures the total order property. b) neither a priori nor a posteriori? If the messages, on which the algorithm agrees in consensus, are never sorted deterministically within every batch (neither a priori nor a posteriori ), then the total order property does not hold. Even if the processes decide on the same batch of messages, they might to-deliver the messages within this batch in a different order. In fact, the total order property would be ensured only with respect to batches of messages, but not with respect to individual messages. We thus get a coarser granularity in the total order. 3/3
{ "page_id": null, "source": 7318, "title": "from dpo" }
Title: URL Source: Markdown Content: # Contents 1 Introduction 7 1.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71.2 Aims and Objective . . . . . . . . . . . . . . . . . . . . . . . 81.3 Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81.4 Dissertation Overview . . . . . . . . . . . . . . . . . . . . . . 91.5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 2 Background 11 2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2.2 The need for distribution . . . . . . . . . . . . . . . . . . . . 11 2.3 Motivational Scenario . . . . . . . . . . . . . . . . . . . . . . 12 2.4 Distributed Agreement Problems . . . . . . . . . . . . . . . . 14 2.5 Distributed Computing Models . . . . . . . . . . . . . . . . . 17 2.5.1 Degree of Synchrony . . . . . . . . . . .
{ "page_id": null, "source": 7318, "title": "from dpo" }
. . . . . . . . 19 2.5.2 Failure Model . . . . . . . . . . . . . . . . . . . . . . . 20 2.6 Recurring Agreement Problems in Distributed Computing . . 22 2.6.1 Reliable Broadcast . . . . . . . . . . . . . . . . . . . . 22 2.6.2 Consensus . . . . . . . . . . . . . . . . . . . . . . . . . 24 2.6.3 Atomic Commit . . . . . . . . . . . . . . . . . . . . . 25 2.7 Circumventing Impossibility Results for Asynchronous Systems 26 2.7.1 Partial Synchrony . . . . . . . . . . . . . . . . . . . . 26 2.7.2 Randomization . . . . . . . . . . . . . . . . . . . . . . 26 2.7.3 Failure Detectors . . . . . . . . . . . . . . . . . . . . . 27 2.8 Fault Tolerant Systems . . . . . . . . . . . . . . . . . . . . . . 29 2.9 Distributed Programming Languages . . . . . . . . . . . . . . 30 12.9.1 Erlang . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 2.9.2 Programming in the presence of failures . . . . . . . . 32 2.9.3 The strength
{ "page_id": null, "source": 7318, "title": "from dpo" }
of Erlang . . . . . . . . . . . . . . . . . . 33 2.9.4 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 35 3 Implementation Framework 36 3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 3.2 Distributed Computing Abstractions . . . . . . . . . . . . . . 36 3.2.1 Processes . . . . . . . . . . . . . . . . . . . . . . . . . 37 3.2.2 Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 3.2.3 Communication Links . . . . . . . . . . . . . . . . . . 38 3.2.4 Failure Detectors . . . . . . . . . . . . . . . . . . . . . 39 3.3 A Common Structure for all Algorithms . . . . . . . . . . . . 39 3.3.1 Types of event triggering . . . . . . . . . . . . . . . . 41 3.3.2 Predicate-triggered events . . . . . . . . . . . . . . . . 42 3.4 Module Composition . . . . . . . . . . . . . . . . . . . . . . . 43 3.5 Delving deeper .
{ "page_id": null, "source": 7318, "title": "from dpo" }
. . . . . . . . . . . . . . . . . . . . . . . . . 44 3.5.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . 44 3.5.2 Atoms . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 3.5.3 Comments . . . . . . . . . . . . . . . . . . . . . . . . . 45 3.5.4 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 3.5.5 Pattern Matching . . . . . . . . . . . . . . . . . . . . . 45 3.5.6 Sending and Receiving messages . . . . . . . . . . . . 46 3.6 An Implementation in Erlang . . . . . . . . . . . . . . . . . . 46 3.6.1 Process structure . . . . . . . . . . . . . . . . . . . . . 47 3.6.2 Local Processes Interaction . . . . . . . . . . . . . . 50 3.6.3 A Design Pattern for all modules . . . . . . . . . . . 51 3.6.4 Working with Single Assignment . . . . . . . . . . . . 56 3.7 Conclusion . . . . . . . .
{ "page_id": null, "source": 7318, "title": "from dpo" }
. . . . . . . . . . . . . . . . . . . . 56 4 Reliable Broadcast 57 4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 4.2 Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 4.3 Best Effort Broadcast . . . . . . . . . . . . . . . . . . . . . . 58 24.3.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . 58 4.3.2 Specification . . . . . . . . . . . . . . . . . . . . . . . 58 4.3.3 Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . 58 4.3.4 Erlang Implementation . . . . . . . . . . . . . . . . . 59 4.3.5 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . 60 4.4 Regular Reliable Broadcast . . . . . . . . . . . . . . . . . . . 61 4.4.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . 61 4.4.2 Specification
{ "page_id": null, "source": 7318, "title": "from dpo" }
. . . . . . . . . . . . . . . . . . . . . . . 61 4.4.3 Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . 61 4.4.4 Erlang Implementation . . . . . . . . . . . . . . . . . 65 4.4.5 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . 66 4.5 Uniform Reliable Broadcast . . . . . . . . . . . . . . . . . . . 67 4.5.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . 67 4.5.2 Specification . . . . . . . . . . . . . . . . . . . . . . . 67 4.5.3 Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . 67 4.5.4 Dissecting the Algorithm . . . . . . . . . . . . . . . . 70 4.5.5 Erlang Implementation . . . . . . . . . . . . . . . . . 71 4.5.6 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . 72 4.6 Causal Order Broadcast . . . . . . . . . . . . . . . . . . . . .
{ "page_id": null, "source": 7318, "title": "from dpo" }
73 4.6.1 Specification . . . . . . . . . . . . . . . . . . . . . . . 74 4.6.2 Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . 75 4.6.3 Erlang Implementation . . . . . . . . . . . . . . . . . 78 4.6.4 Implementation Optimisations . . . . . . . . . . . . . 79 4.6.5 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . 79 4.7 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 5 Consensus 81 5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 5.2 Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 5.3 A Slight change . . . . . . . . . . . . . . . . . . . . . . . . . . 82 5.4 Regular Consensus . . . . . . . . . . . . . . . . . . . . . . . . 82 5.4.1 Overview . . . . . . . . . . . . . . . . . . . . .
{ "page_id": null, "source": 7318, "title": "from dpo" }
. . . . 82 5.4.2 Specification . . . . . . . . . . . . . . . . . . . . . . . 83 5.4.3 Flooding Algorithm . . . . . . . . . . . . . . . . . . . 83 35.4.4 Hierarchical Algorithm . . . . . . . . . . . . . . . . . . 93 5.5 Uniform Consensus . . . . . . . . . . . . . . . . . . . . . . . . 98 5.5.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . 98 5.5.2 Specification . . . . . . . . . . . . . . . . . . . . . . . 98 5.5.3 Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . 98 5.5.4 Erlang Implementation . . . . . . . . . . . . . . . . . 101 5.5.5 Implementation Optimizations . . . . . . . . . . . . . 101 5.5.6 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . 101 5.6 Total Order Broadcast . . . . . . . . . . . . . . . . . . . . . . 103 5.6.1 Overview . . . . . . . . . . . . . . . . . . . .
{ "page_id": null, "source": 7318, "title": "from dpo" }
. . . . . 103 5.6.2 Specification . . . . . . . . . . . . . . . . . . . . . . . 103 5.7 Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 5.8 Erlang Implementation . . . . . . . . . . . . . . . . . . . . . . 107 5.9 Implementation Optimisations . . . . . . . . . . . . . . . . . 108 5.10 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 5.11 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 6 Atomic Commit 110 6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 6.2 Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 6.3 Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 6.4 Synchronous Approaches . . . . . . . . . . . . . . . . . . . . . 111 6.4.1 Two
{ "page_id": null, "source": 7318, "title": "from dpo" }
Phase Commit Algorithm . . . . . . . . . . . . . 112 6.4.2 Three Phase Commit Algorithm . . . . . . . . . . . . 115 6.5 Asynchronous Consensus Based Algorithm . . . . . . . . . . . 120 6.5.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . 120 6.5.2 Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . 122 6.5.3 Erlang Implementation . . . . . . . . . . . . . . . . . 125 6.5.4 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . 125 6.6 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 7 Testing and Case-Study 127 7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 7.2 Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 47.2.1 Test Strategy . . . . . . . . . . . . . . . . . . . . . . . 128 7.2.2 Function Testing . . . . . . . . . . . . . .
{ "page_id": null, "source": 7318, "title": "from dpo" }
. . . . . . . 128 7.2.3 Module Testing . . . . . . . . . . . . . . . . . . . . . . 130 7.2.4 System Testing . . . . . . . . . . . . . . . . . . . . . . 132 7.2.5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 133 7.3 Case-Study . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 7.3.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . 133 7.3.2 Description of the p2pfs filesystem . . . . . . . . . . . 133 7.3.3 Assumptions and Considerations . . . . . . . . . . . . 134 7.4 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . 137 7.5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 8 Evaluation 141 8.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 8.2 Benefits Achieved . . . . . . . . . . . . . . . . . . . . .
{ "page_id": null, "source": 7318, "title": "from dpo" }
. . . . 141 8.2.1 Separation of Concerns . . . . . . . . . . . . . . . . . 141 8.2.2 Shorten development time . . . . . . . . . . . . . . . . 142 8.2.3 Structured Code . . . . . . . . . . . . . . . . . . . . . 142 8.2.4 Agreement Algorithm Abstractions . . . . . . . . . . . 143 8.2.5 Code Reuse . . . . . . . . . . . . . . . . . . . . . . . . 143 8.2.6 Simplifies testing . . . . . . . . . . . . . . . . . . . . . 144 8.2.7 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . 144 8.3 Assessing the Implementation Framework . . . . . . . . . . . 144 8.3.1 Bridging Theory and Practice . . . . . . . . . . . . . . 144 8.3.2 Code Reuse . . . . . . . . . . . . . . . . . . . . . . . . 145 8.3.3 Structured and Maintainable Code . . . . . . . . . . . 145 8.4 Evaluating the usage of Erlang . . . . . . . . . . . . . . . . . 145 8.5 How practical are the algorithms? . . . . . . . . . . . . . . . 147 8.5.1 Network Requirement
{ "page_id": null, "source": 7318, "title": "from dpo" }
. . . . . . . . . . . . . . . . . . 147 8.5.2 Memory Requirement . . . . . . . . . . . . . . . . . . 149 8.6 Assessing the failure detector implemented . . . . . . . . . . . 150 8.7 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 9 Conclusion and Future Work 152 59.1 Alternative Failure Detector . . . . . . . . . . . . . . . . . . . 152 9.2 Approaching the indefinite growing of the state . . . . . . . . 152 9.3 Different Failure Model . . . . . . . . . . . . . . . . . . . . . 154 9.4 Analyse further specifications and agreement problems . . . . 154 9.5 Relevance of work done . . . . . . . . . . . . . . . . . . . . . 154 9.6 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 A Using the protocol suite 156 A.1 Prerequisites: . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 A.2 Setting Up . . . . . . . . . . . . . . . . . . . . . . . . . . . .
{ "page_id": null, "source": 7318, "title": "from dpo" }
. 156 A.3 Starting a shell . . . . . . . . . . . . . . . . . . . . . . . . . . 157 A.3.1 Explanation . . . . . . . . . . . . . . . . . . . . . . . . 157 A.4 Initializing the Suite of protocols . . . . . . . . . . . . . . . . 157 6Chapter 1 # Introduction # 1.1 Overview Writing correct concurrent code is no easy feat. It is very difficult to get an unflawed design for a reasonably sized concurrent program - in par-ticular, most analysts and programmers, are not accustomed to deal with numerous threads or processes potentially modifying data in parallel and unordered manner. Moreover, testing such applications also provides an extra challenge to concurrent software development. Due to the massive number of possible code executions, debugging concurrent code tends to fail to expose all the possible bugs in a system . This results in systems which are unstable when in production environment. Distributed system design is at least as challenging as concurrent system de-sign, with different kinds of failures threatening to make the job of producing correct code even harder. Some of the problems incurred with distributed systems are process failures , link failures , lost messages and varying message arrival delays . Dealing with these problems in real life and ensuring that the code prevails any of these conditions, is and active area of research. Lately, there seems to be an overall interest in shifting towards a decentral-ized paradigm for distributed computing. This paradigm forms the basis of various recent architectures and technologies including Web2.0, Cloud-computing and Peer-to-peer technologies. In the context of
{ "page_id": null, "source": 7318, "title": "from dpo" }
Distributed 7Programming, this means that systems have to be programmed from a local observers view which handles all interactions autonomously, without the need of a global coordinator. Such an approach overcomes the issue of single point of failure, nevertheless brings about various intricacies which need to be resolved to ensure the correctness of the distributed algorithms. # 1.2 Aims and Objective The aim of this dissertation is to investigate various decentralised distributed computing problems and study their applicability and possible implemen-tation. The distributed system model will be analysed and the underlying difficulties when attempting to program in such a model will be explored. A number of assumptions about this model shall be made. These assump-tions are very much identical to those followed by alternative work on pro-gramming distributed systems . In this context, different approaches to distributed programming will be assessed. In this dissertation, some of the most popular distributed agreement classes will be investigated. Different specifications, for each class shall be presented and established algorithms will then be studied. Following this, a common framework for implementing these algorithms should be developed in Erlang. This framework shall be built on top of Erlang’s existing modules and built in characteristics. This way, we attempt to provide a practical implementation framework, for these algorithms. A number of algorithms will be implemented in a reusable manner, in Er-lang. Together, these will form a suite of algorithms, which abstracts away the intricacies involved in these algorithms, yet providing their functionality in a reusable form. Finally, a test case application will be implemented, so as to assess the applicability of this implemented suite of algorithms. # 1.3 Approach The work taken throughout this project was organised in a particular struc-ture. In particular, towards the early stages, we dealt more with research and attempted to
{ "page_id": null, "source": 7318, "title": "from dpo" }
get accustomed to the notion of distributed programming. Following this, we dealt more with the actual implementation of the project 8itself. The various stages involved in this project were: 1. Performing research on distributed computing systems and the prob-lems associated with programming is such systems. 2. Performing research on Distributed Agreement Problems. 3. Familiarizing ourselves with Erlang, and implementing some of the algorithms studied, for localized environment. 4. Developing an framework, with which to build the actual distributed algorithms, on top of Erlang’s features. 5. Implementing and testing the distributed algorithms themselves using the developed framework. 6. Building a simple test case scenario which uses the algorithms devel-oped as its core. # 1.4 Dissertation Overview The content of this report is divided into the following sections: Chapter 2, lays out the background which is a prerequisite for this project. In introduces distributed systems and various other aspects dealing with distributed programming. In particular, the system model is outlined. Here, Agreement problems and the main classes of these problems are outlined. Different distributed programming approaches and languages are evaluated, and Erlang’s strengths and advantages are pointed out. Chapter 3 gives out a common framework for implementing the distributed agreement algorithms, in Erlang. This chapter attempts to bridge the theory and practice. It shows how we built on top of existing mechanisms in Erlang, so as to achieve this framework. In Chapter 4 we start our study of the agreement algorithms. This chap-ter studies the Reliable Broadcast problem. Different specifications of this problem, are outlined and established algorithms are studied. An overview of the actual implementation in Erlang is given. 9In Chapter 5, the Consensus class of agreement problems is studied. This chapter investigates different specifications and algorithms, and also gives details about the implementation in Erlang. In Chapter 6, the Atomic
{ "page_id": null, "source": 7318, "title": "from dpo" }
commit class of agreement problems is investi-gated. Once again, here different algorithms are studied, and are imple-mented in Erlang. Chapter 7 provides the details of the testing which was required for the system. It gives out the testing strategy followed for the implementation of the developed suite of algorithms. It also outlines the implemented test case application. In Chapter 8 evaluates various aspects of this project. In particular, the usage of the algorithm suite, for the development of the test case, is inves-tigated. The choice of Erlang, is also evaluated. In Chapter 9, we conclude this work and propose suggestions for future work. # 1.5 Conclusion This project aims to provide the basic building blocks, which make the development of robust distributed systems easier. A number of recurrent distributed problems are outlined and studied in depth, in the light of process failures. Techniques for safe distributed programming, failure detection and fault tolerance are also investigated. A suite of protocols, providing solutions to the distributed problems outlined, is built. Finally this suite is tested and evaluated in a real world distributed scenario. 10 Chapter 2 # Background # 2.1 Introduction This chapter provides an overview of the background for this project. Pri-marily, it attempts to motivate the use of distributed system. It presents a simple, yet realistic, example of a distributed system. A number of recur-rent distributed problems are then introduced in the light of this example. All relevant terminology is defined and all design choices are explained and justified. In particular, an implementation language is chosen after being contrasted with other ’candidate’ languages. # 2.2 The need for distribution In the context of computer systems, a Distributed System consists of a number of nodes operating together in a coordinated manner. Distributed computing is not a novel field. In fact, it
{ "page_id": null, "source": 7318, "title": "from dpo" }
has been around since the early days of networking and the internet. In reality, the need for such a system was felt since the early days of computing, but throughout recent years, their applications increased drastically. Often computer systems have to deal with resources which are remotely located. These resources may vary from computing resources, to machinery and or even human resources. A distributed system would be needed to ensure communication amongst users and the sharing of these resources. As an example, the bank ATM systems may be considered. At the outer level, clients see a terminal were they can access banking services, but in reality 11 these consist of a distributed computing systems, consisting of a number of resources. Distribution is needed when a continuous operation needs to be guaran-teed. In general, for a system to be failure proof, it needs to be replicated in different locations and when one component fails, the other takes over . Moreover, distribution might also be needed to offer load balancing of core services - if a server is heavily loaded, one might consider to split the computation over a number of processors. Finally, in today’s world, where internet access is becoming more and more widespread, distributed systems have become part of every day life. Differ-ent computing devices nowadays access remote services for their operation, providing us with the instant and up to date information. # 2.3 Motivational Scenario One of the main problems with centralized systems, is their susceptibility to central point of failure - if this central node fails, service stalls. Clearly, overcoming this problem requires some form of distribution. This section presents a simple distributed, peer-to-peer filesystem p2pF s and presents typical problems incurred in such a distributed environment. This dis-tributed system is used as a running example throughout this
{ "page_id": null, "source": 7318, "title": "from dpo" }
document - to clearly demonstrate instances of distributed problems being studied. p2pF s is a simple distributed file system, p2pFs with the following proper-ties: 1. Decentralized There is no central overall leader coordinating the filesystem. 2. Consistent At a particular time, all files appear the same from all nodes This file system provides basic handling operations: 1. File Creation: Files can be created and are immediately available for other nodes. 2. File Access: Files can be read and written concurrently and reliably. 3. File Deletion: Files can be safely deleted. 12 Throughout this chapter, reference will be made to a particular setup of the p2pF s . For the sake of simplicity, this setup consists of just four servers: N orth , South , East and W est . These four servers are interconnected to-gether, however the underlying details of these connections are irrelevant to us - what is important is that a message sent from a server, can ultimately be received by the destination server. Figure 2.1 (a) shows the basic layout of this example. Figure 2.1: (a) A distributed system using p2pfs. (b) Node compo-sition When a node sends a message, this message is given to the underlying network to be delivered. It is assumed that the underlying network will eventually transf er the message with the same content as sent, to the des-tination (yet this message may take arbitrarily long to arrive). When a message is transferred to a node, it is said that the message is received by that node. Note, that here a distinction is made between a node and the underlying application (in this case p2pF s ) - despite that the node received a message, p2pF s still does not know anything about this message and of its existence. When the message is
{ "page_id": null, "source": 7318, "title": "from dpo" }
passed to the application to which it is intended ( p2pF s ), the message is said to be delivered (refer Figure 2.1 (b) ). Note that we are hence introducing the existence of a layer between the node and the application itself - which might decide that the message should not be delivered to the application, despite being received by the node. Alternatively this layer might decide that it needs to receive more messages before deciding to deliver this message or not. It is noted that such a file system has very simple semantics, yet the intrica-cies can be very subtle. For example, how can a node ensure that updating a file will result in all nodes having the same version of the file? What if multiple nodes try to update it at once? What if some nodes fail after 13 transferring their updates to only half of the nodes? What if a file is deleted while it is being updated by some node? Such problems are yet another instance of agreement problems in a dis-tributed system. This work, investigates and analyses different solutions to these problems. Ultimately these solutions are used to build a reliable version of the p2pFs, as described here. # 2.4 Distributed Agreement Problems Fault-tolerant distributed systems present various challenges which make this area of computer science an active area of research. An number of problems are recurrently dealt with when attempting to perform distributed computation. Such problems explore different situations of data exchange, in a way to keep the overall systems consistent, despite the unreliability of the processes themselves and the interconnecting links. These set of problems are more commonly known as Agreement Problems . Here, a brief overview of these problems is given, and an example in the light of the dis-tributed scenario
{ "page_id": null, "source": 7318, "title": "from dpo" }
being studied, is outlined. These problems will be studied in depth later. 1. Reliable Broadcast Reliable Broadcast deals with the safe transfer of a message to a number of nodes, despite the eventuality of having nodes which fail during this process - including the sender itself. For example, in the p2pF s scenario outlined, consider the case where the W server wants to send an update a to all other servers. However, it might happen that it succeeds in sending the update to N and E,but crashes exactly before sending it to S (as shown in Figure 2.2) Clearly this leaves the system in an inconsistent state since server S does not get the update. A Reliable Broadcast protocol would be rather handy in this situation to ensure that a message is safely broadcast under all possible eventualities. Hence, if a reliable broadcast proto-col is followed, all correct nodes should have a consistent view of the system. 2. Consensus Consensus deals with agreement within a group of pro-cesses, in the presence of failures. Processes propose to each other and finally each process should decide on the values it received. In the 14 Figure 2.2: Failure of simple broadcast mechanisms: Node S only manages to broadcast to part of the system. end all decisions should be consistent. For example, assume that across the nodes there are different files with the same name. This is shown in figure 2.3 below, where a file with the same name (named A), is present on all nodes. Note also, that the size of file A is indi-cated at each node. Such a situation can occur when the distributed filesystem is initialised for the first time. If node W requests to open file A, which version should it open? Figure 2.3: Failure of Node
{ "page_id": null, "source": 7318, "title": "from dpo" }
E after submitting its version of the file to S, but before submitting to the rest, results in an inconsistent system. A simple solution might be everyone broadcasting his version of the file to oneanother and the receiver nodes always keeping the file which has a largest filesize . However, similar to the reliable broadcast scenario, if say node E crashes after sending its 6b version of file A to node S but before even sending the file to the rest, then node E will keep the 6b version of the file, whereas the other nodes will keep the 4 b version of file A since this is the version of A with the largest filesize, they get 15 to see. Clearly this is a problem and hence the p2pF s requires some consensus protocol to ensure that all nodes agree on the same version of the file. 3. Atomic Commit The Commit problem deals with having a number of processes which try to perform some action together. This action should be aborted and rollbacked, if any of the processes disagrees to carry out this action, or crashes. Figure 2.4: S tries to delete a file from all nodes, however, node W cannot accomplish this operation because the file is open. Now consider that a delete operation on file A is issued from node S.This operation is broadcast to all other nodes (assume any a reliable broadcast), as seen in figure 2.4. However, the file is deleted from nodes N and E but is currently open at node W , and hence can not be deleted from node W . Again this would leave the system in an inconsistent state. An atomic commit would ensure that either all files are deleted or else no file is deleted until it
{ "page_id": null, "source": 7318, "title": "from dpo" }
can be deleted from all nodes. These problems have been the basis of various research . A number of results have been established which identify limitations on the solutions to these problems, in various contexts of time and failures. Nevertheless, since these problems are central in the design of fault-tolerant distributed systems, various approaches have been proposed to go around these limitations in a well defined manner. 16 2.5 Distributed Computing Models This section will outline various computational models, which are relevant when investigating a distributed system. Such models can be used to analyse the correctness and bounds of the problem being studied. 2.5.0.1 Programming Distributed Systems There exist two main schools of thought when programming for a distributed architecture. These are the Shared-Memory Model and the Message-Passing Model : Shared-Memory Model In the Shared-Memory model, processes inter-act by using common resources such as memory pages and registers. Higher level shared structures can also be composed on top of these structures, such as shared queues or stacks. Access to the shared objects is one classical in-stance of the Critical Section problem - it might be safe to have multiple readers but not multiple writers or a mixture of readers and writers access-ing the shared object. Various solutions to the Critical Section Problem have been proposed. The main ones are: • Semaphores and Mutexes : These are constructs which restrict the number of processes executing within a Critical Section. In a nutshell, mutexes allow just one process to execute its Critical section at a time whereas semaphores allow an arbitrary number of processes to execute their Critical Section concurrently, depending on the initial value of the semaphore. Simply put, these lock constructs are a memory barrier. When a process tries to access a Critical Section, it waits until it acquires a
{ "page_id": null, "source": 7318, "title": "from dpo" }
lock. Contention on the locking depends on the underlying fairness of the lock and the scheduling algorithm. Having acquired the lock, a process executes its Critical Section and releases the lock. Despite being rather straight-forward, lockful programming gives rise to various caveats including deadlock, livelock, priority inversion and the convoy effect. Moreover, lockful algorithms are not suitable for SMP because of their scalability limitations. • Lock-free and Wait-free Programming : In an attempt to over-come the problems related to lockful programming, hardware man-17 ufactures started providing atomic primives such as Test-And-Set , Compare-And-Swap , Load Linked and Store Conditional operations. Such operations allow algorithms to be devised which despite avoiding the usage of locks, guarantee correct access to the shared resources for all possible histories of an algorithm. This requires the algorithm to be proven correct for all possible interleavings. This is gener-ally a streneous task, and despite that there are proven algorithms for some common data structures, more complex data strucutures and custom/hybrid data structures will, of course, have no guarantee of correctness. Moreover, lock-free code is note guaranteed to remain correct across different architectures (example if an assignment takes more than one CPU instruction). Wait-free programming goes a step further from Lock-Free programming, by giving timing constraints on the execution of the algorithm. • Transactional Memory : An emerging field with Shared Memory Programming, is that of Transactional Memory. Transactional Mem-ory provides the programmer with an atomic construct for coarse grained atomic actions, which allows code within it to be executed concurrently in a safe manner. The approach is analogous to that of transactions in a database system: start executing the atomic code, if some other process interferes with this process’ execution, then roll-back the changes made and ensure that the processes execute in a con-sistent manner. This
{ "page_id": null, "source": 7318, "title": "from dpo" }
approach, especially the field of Software Trans-actional Memory started gaining ground, however as systems starts getting larger and the amount of concurrent atomic actions start to escalate. In particular, lots of processes start interfering, and more memory needs to be copied to allow for the reversing of its contents - degrading performance substantially. Moreover, such a system is sometimes deemed unsuitable for everyday computing, because most system calls, such as read () and write () are not easily reversible (es-pecially if these access external resources such as the network). Despite the severe performance problems outlined, lockful code seems to be the mainstream, possibly because of its programming ease and compu-tational correctness. In order to overcome this problem, some programming languages, usually provide optimised libraries for common data structures 18 based on lock-free and wait-free algorithms. Message-Passing Model In a Message-Passing architecture, processes communicate by exchanging messages over some interconnecting link. Pro-cesses in this model, have local memories (distributed memory), which can be acted upon depending on the messages received. This model is also re-ferred to as the actor model - processes can be seen as actors which interact with each other solely through the exchange of messages. Message Passing architectures can be classified as either Asynchronous Message Passing and Synchronous Message Passing . In Asynchronous Message Passing, send-ing messages is non-blocking, whereas in Synchronous Message Passing the sender blocks until the receiver delivers the message. 2.5.1 Degree of Synchrony One other distinguishing attribute in distributed systems is the degree of synchrony - whether the system is synchronous or asynchronous. In sec-tion 2.7 , partially synchrony is also analysed as a way to circumvent the limitations of the problems outlined. A system is synchronous if it obeys the following properties: 1. A known upper bound exists on the message delivery delay.
{ "page_id": null, "source": 7318, "title": "from dpo" }
2. A known upper bound exists on the time between execution steps of a process. 3. A known upper bound exists on the clock drifts of the interacting processes. On the other hand, the asynchronous distributed system model does not provide any timing bounds on its operations. The asynchronous model is more general but algorithms are harder to design in this model due to the lack of timing bounds. Yet this model is very attractive since it has simple semantics, its algorithms are easier to adapt to real life applications due to the lack of any strict timing constraints and such algorithms are guaranteed to work with arbitrary timing bounds. The agreement problems outlined in 2.6 have been proven not solvable in an asynchronous model with crash failures, nevertheless these are solvable in 19 the synchronous model. The impossibility result for asynchronous systems revolves on the impossibility of distinguishing between failed processes and slow processes due to the lack of timing constraints. It might be tempting to define reasonable upper-bounds in an asynchronous system, to be able to reason synchronously about the system. However, the aim of these models of synchrony, is to provide means of being able to prove properties about the system and there is no way to guarantee that such bounds will hold deterministically. Nevertheless, such approach has to be taken when all other measures fail . 2.5.2 Failure Model During an execution, a component is said to have failed , if its behaviour differs from that specified by the underlying algorithm. On the other hand, correct components are ones which abide by the behaviour specified by their respective algorithm. A Failure Model specifies to what degree, this be-haviour is tolerated to deviate, for the study of some underlying algorithm. 2.5.2.1 Process Failures Figure 2.5: Types
{ "page_id": null, "source": 7318, "title": "from dpo" }
of Process Failures. (source ) A process is said to have failed, when it deviates from the algorithm which describes it. Upon failure, any other components under direct control of this failed process are assumed to also fail - and remain in this state unchangingly. Figure 2.5, gives a diagramatic classification of different kinds of Process Failures .The most general of these failures, are the Byzantine Failures . Such failures are denoted by arbitrary behaviour by the failed processes - processes can exhibit incorrect behaviour by sending incorrect messages or ommitting 20 messages which should be sent. Likewise, such failed processes can react non-deterministically to received messages. Such abstraction can be seen as a process operating maliciously either intentionally or unintentionally -example due to miswritten code or user error. Byzantine Failures were first defined in the seminal paper , where the Byzantine Generals Problem is defined. Crash Recoveries happen in processes whose operation is transient - such processes fail, remain in the failed state for some time and then go back to correct operational state. A process can continuously and repeatedly experi-ence this behaviour. Processes which are transient failure resilient, generally store their internal state in some reliable storage medium. Whenever such processes recover, apart from consulting the stored state, the current state of the system is requested from the interacting peers of the distributed system. Ommission failures occur when a process fails to send or receive a mes-sage. Such failures can be caused by link failures and also due to network congestion. Crash failures Crash failures (or fail-stop failures ) occur when a process fails and remains unchangingly in the failed state. A process can experience a crash failure in an arbitrary stage of execution, however under such model, no invalid messages are sent (in real life this is
{ "page_id": null, "source": 7318, "title": "from dpo" }
generally handled by transport layer protocols). In this work, we will focus mainly on Crash Failures . . 2.5.2.2 Link Failures An interconnecting link may be considered as nonoperational if messages get garbled or are lost. The former case can be handled trivially with check-sums. Lost messages on the other hand can be somewhat more difficult to handle. From the point of view of processes, link failures appear as ommission failures - link failures may be the reason why certain messages are ommitted . In particular, in the case of network partition, such situation can give rise to various problems. For example consider a link failure causes a partition of network into two parts A and B. Processes in part A will think that all processes in part B have failed whereas processes in part B will think that all processes in part A have failed - yet both sets of processes will continue to operate in isolation. Link Failures can be transient - certain messages are successfully delivered 21 whereas others are lost. In practice, this happens due to router convergence delays. When abstracting about process communication, it is common to assume a direct link between every communicating peer. In general, this direct link is most of the times an abstraction of the networking system which incorporates various other devices such as routers, switches, bridges, cables etc. The underlying networking system provides higher protocols with point to point communication seemless of the complexities involved. Moreover transport layer protocols (such as TCP) also handle convergence delays upto a limit - through mechanisms such as retransmission and windowing. On the other hand, a sender can ensure that a message was delivered by continuously retransimitting until an acknowledge is received. In this work, only Process failures are considered. Links are assumed to
{ "page_id": null, "source": 7318, "title": "from dpo" }
be perfect. # 2.6 Recurring Agreement Problems in Distributed Computing Earlier on in this chapter, a number of recurring distributed problems were outlined. In this section we will study these problems in further detail. 2.6.1 Reliable Broadcast Reliable Broadcast truly is a term which captures a number of broadcast primitives - different abstractions for reliably sending messages to a group of processes. Broadcast abstractions provide different degrees of reliability: Regular Re-liable Broadcast ensures that all correct processes deliver the same set of messages, Uniform Reliable Broadcast ensures broadcast agreement between both fault and non-faulty processes, Total Order Broadcast further ensures that all processes in the system deliver the messages in the same order whereas Terminating Reliable Broadcast further ensures that a process will not keep waiting to receive a message if no process has ever seen that mes-sage. The Regular Reliable Broadcast algorithm, ensures that all correct processes agree on the message to deliver. A regular reliable broadcast algorithm satisfies the following properties : 22 • Validity : If a correct process p broadcasts a message m, then p even-tually delivers m. • Agreement : If a correct process delivers a message m, then all correct processes eventually deliver m. • Integrity : For any message m, every process delivers m at most once, and only if it was previously broadcast. Regular reliable broadcast ensures agreement amongst all non-faulty pro-cesses. However, there can be a situation where the sender manages to send a message to one process and fails. The sender then fails without man-aging to deliver the process to any other process. Immediately afterwards the unique receiver of the message fails too, without having the opportu-nity to propagate the message it has received to the other nodes. In such a situation, there is inconsistency amongst the faulty and correct
{ "page_id": null, "source": 7318, "title": "from dpo" }
processes. Such a situation can be detrimental in certain situations and hence the Uni-form Reliable Broadcast fixes this anomaly by strengthening the broadcast specification with the following property : • Uniform Agreement : If a message m is delivered by some process pj (correct or faulty), then m is eventually delivered by every correct process pi Moreover, it is sometimes desirable to ensure that all broadcast messages (involving different senders) are delivered in the same order, globally by all processes. For example in the context of the p2pfs, consider the situation where one process alters the first character of a file, whereas another process tries to change the first character to uppercase. Clearly reordering the two operations, yields different results - hence it should be ensured that broad-cast updates to files on the p2pfs are totally ordered . Total Order Broadcast ensures all process do not just agree on the set of messages received, but also the sequence of these messages. It also satisfies the following property : • Total order : If correct processes p and q both deliver messages m and m′, then p delivers m before m′ if and only if q delivers m before m′.23 2.6.2 Consensus The consensus abstraction deals with having nodes in a network trying to agree on a common value. The nodes themselves, initially propose values to one another and after that the consensus algorithm terminates, all nodes should have decided on the same value. The most basic consensus abstraction is the Regular Consensus . A regular consensus algorithm satisfies the following properties : • Agreement : No two correct processes decide differently. • Validity : If a process decides v, then v was proposed by some process. • Integrity : No process decides twice. • Termination : Every correct process eventually
{ "page_id": null, "source": 7318, "title": "from dpo" }
decides on some value. Again as with the case of Regular Reliable Broadcast , there can be a situ-ation where faulty processes decide differently (before failing), than correct processes. In order to restrict this situation, Uniform Reliable Broadcast satisfies another property : • Uniform Agreement : No two processes (correct or faulty) decide differently. The problems with achieving reliable consensus is that of having processes which fail at any point during the consensus algorithm - processes can end up having different views of the set to be agreed upon. In , an impossibility result on the solvability of consensus in an asynchronous system, is given. This result states that even with simple crash failures, no algorithm can deterministically solve consensus in an asynchronous system. Nevertheless, in real life there are various ways of circumventing this limitation (refer 2.7). In a synchronous system, consensus is solvable for the crash failure model but with a lower bound on the number of rounds - a round can be seen as an exchange of messages between the various nodes of the system. It is shown in , that if there are at most t failures, then consensus is solvable after t + 1 rounds. 24 2.6.3 Atomic Commit The Atomic Commit problem deals with having a group of processes in a distributed system agreeing to perform an action consistently. Such an abstraction is particularly used in the domain of distributed database trans-actions - transactions may either be committed together or aborted together. In a commit operation, the coordinator (the node initiating the commit operation), will request to perform a commit. All nodes attempt to perform the associate action and send Yes or No indicating whether this associated action succeeded or failed. If the coordinator sees that all nodes succeeded then it send a request
{ "page_id": null, "source": 7318, "title": "from dpo" }
to commit the result, otherwise it sends a request to abort the commit. The first Commit abstraction which is considered is the Blocking Commit .This abstraction satisfies the following properties : • Agreement : No two processes decide to take different actions • Validity :1. If any process votes No , then abort is the action which will be done. 2. If all processes vote Yes , and there is no failure, then commit is the action which will be done. • Weak Termination: If there is no failure, then all processes eventually decide. This abstraction, is said to be Blocking because if the coordinator fails on particular stages in the algorithm, then the other nodes will not be able to decide whether to commit or abort This problem is overcome by the Non-blocking commit protocol. This ab-straction replaces the Weak Termination property with the following prop-erty : • Non-Blocking Termination : All processes eventually decide. It has been proven in , that Atomic Commit is unsolvable in asynchronous systems, whereas the t + 1 lower bounds on the number of rounds, is still applicable for synchronous systems. 25 2.7 Circumventing Impossibility Results for Asyn-chronous Systems Despite the fact that the agreement problems outlined here are unsolvable in asynchronous systems, such problems tend to crop up so often, that ways around these limitations had to be devised. In general, the correctness requirements are relaxed, the synchrony parameter is strengthened, or both . There are three main techniques which are used: Partial Synchrony , Failure Detectors and Randomisation . 2.7.1 Partial Synchrony Partially Synchronous systems attempt to strengthen properties of asyn-chronous systems, to obtain solutions to these distributed computing prob-lems. A Partially Synchronous model lies somewhere in between of a synchronous and an asynchronous model. Such a model has bound ∆
{ "page_id": null, "source": 7318, "title": "from dpo" }
on the message delay and bound φ on the relative speeds of the processes (slowest process takes at most φ multiplied by time taken by fastest process to perform the same action). Partially synchronous systems try to strengthen the bounds of asynchronous systems in some way. For example, a partially synchronous system may assume that the timing bounds do exist but are unknown. Al-ternatively, these bounds are also given a value which only applies after some time. Such restrictions are not found in asynchronous system, yet are far from those of totally synchronous systems . 2.7.2 Randomization Randomization techniques allow processes to make probabilistic choices such that the properties of the abstraction are satisfied with some known prob-ability. Processes make use of random oracles to determine what action to take at various points throughout their execution. Even though ran-domization gives no full correctness guarantees, sometimes it is the only practical way to avoid the limitations of the fully synchronous and asyn-chronous models. However, despite not providing full reliability guarantees, this model guarantees that the algorithms will eventually terminate. Two important algorithms which solve consensus with randomization are 26 the Ben-Or algorithm and the Rabin algorithm. The Rabin algorithm uses a shared oracle, whereas the Ben-Or Algorithm uses truly distributed oracles. 2.7.3 Failure Detectors Failure Detectors are distributed components which provide processes with information regarding which processes have failed and which are still running at a particular point in time. A failure detector is said to be unreliable if it can suspect that a process is crashed, when in reality this process is still running. However, these failure detectors can remove a suspected process p from their failed set, as soon as a p is detected not to have crashed. Each process in the system has its own private failure
{ "page_id": null, "source": 7318, "title": "from dpo" }
detector, and at any point in time, their output (set of suspected processes) can be different - however eventually these failure detectors are expected to converge their suspected processes sets. A Failure Detector is defined by a pair ( c, a ): • c: A Completeness property specifying that all failed processes should be eventually detected • a: An Accuracy property restricts the number of mistakes made by the Failure Detector .Chandra and Toueg in , define two completeness and four accuracy prop-erties. The Completeness properties are: • Strong Completeness : Every process that crashes is eventually per-manently suspected by every correct process. • Weak Completeness : Eventually every process that crashes is per-manently suspected by some correct process. The Accuracy Properties are: • Strong Accuracy : No process is suspected before it crashes. • Weak Accuracy : Some correct process is never suspected. • Eventual Strong Accuracy : There is a time after which correct processes are not suspected by any correct process. 27 Figure 2.6: Tabulating the failure detector properties into eight classes (taken from ) • Eventual Weak Accuracy : There is a time after which some correct process is never suspected. Note that properties such as Weak Completeness and Eventual Weak Accu-racy require that some property will hold permanently. In practice, this is never achievable because no process runs forever. Hence it is enough if such properties are satisfied for times which are ”long enough” for the algorithm to make progress. Figure 2.6, shows a taxonomy given in showing different failure detector classes according to the properties of accuracy and completeness. In , Chandra and Toueg further show that a failure detector in any class of this Taxonomy can be used to solve consensus. It is interesting to note that the weakest 1
{ "page_id": null, "source": 7318, "title": "from dpo" }
failure detector class W in this taxonomy, can also be used to solve consensus. It is shown that W is guaranteed to solve consensus only if n > 2f where n is the number of processes and f is the number of failed processes - there is a majority of correct processes. Furthermore, in a related paper , it is proven that W is the weakest failure detector class to solve consensus - that no weaker failure detector class can solve consensus in an asynchronous system. This is done by formalizing reducability of failure detectors and showing that any failure detector which solves consensus, is reducible to W . It is also shown that if a failure detector solves consensus with n 1A Failure Detector class is said to be weaker in specification than another Failure Detector class, if it can capture a larger number of failure detectors 28 ”liveness but not the safety” of the underlying algorithm. For example, a specifically written consensus solving algorithm utilizing such a failure de-tector, should result in nodes which never agree but never in nodes which agree inconsistently. Failure detectors are quite an elegant approach to fault tolerant distributed systems. However, ultimately, how can failure detectors be sure that a pro-cess failed since they are still operating in an asynchronous environment? Quoting directly from : ”Since we specify failure detectors in terms of abstract properties, we are not committed to a particular implementation. For instance, one could envision specialised
{ "page_id": null, "source": 7318, "title": "from dpo" }
hardware to support this ab-straction. However, most implementations of failure detectors are based on timeout mechanisms” . This paper goes on to show a failure detector which works with timeouts. Every time a process is detected to have been sus-pected wrongly, its timeout is increased. The paper then states that despite this not being exactly the accuracy property of W , in most practical system such a scheme would eventually ensure that there is a correct process which is not suspected ( Weak Accuracy of W ) - recall that it is enough for such a property to hold for periods which are ”long enough” for the algorithm to be able to make progress. # 2.8 Fault Tolerant Systems Fault Tolerance is a property which specifies the degree by which systems continue to operate reliably in the presence of failures. In the context of distributed computing, fault-tolerance requires some form of replication amongst at least two physically separate nodes. In his paper, Why do Com-puters stop and what can be done about it? , Jim Gray points out that systems should be decomposed into units, which when fail, they do not affect the operation of other units. It is further pointed out processes are the ideal concurrent elements (as opposed to threads) since these do not share state amongst them and hence fully satisfy this requirement. Processes should then communicate with ”copy messages” such that all interaction is message oriented and there is no shared state amongst processes. Schneider in , points out various properties which an individual processor should have for fault-tolerant operation. Processors satisfying these properties are called Fail Stop processors. The properties satisfied by fail stop processors 29 are: • Halt on Failure : Upon failing, a processor should cease operation immediately • Failure Status Property
{ "page_id": null, "source": 7318, "title": "from dpo" }
: Processors should be notified when an-other processor fails, and given a reason for this failure. • Stable Storage Property : Processors should be able to store data in some reliable medium which persists a node failure. Furthermore, in , Gray applies this idea of fail stop processors to pro-cesses which is referred to as fail fast . Gray states that through defensive programming (such as checking all parameters, intermediate results and data structures), one can detect instantly detect failures. Upon such eventuality, the process should signal failure and stop. Such mechanism would avoid further damage caused by the errors and ensure slow latency on detecting errors. Renzel in , stresses this point even further by stating that the higher the latency time between the occurence of the fault and the existence of the error , the more complicated it becomes to perform a backward analysis of the error. # 2.9 Distributed Programming Languages A distributed programming language is any language which can be used to develop software which runs and controls a distributed system. This class of programming languages, can be subdivided into two subclasses -1) ’traditional’ sequential programming languages augmented with libraries for distributed programming and 2) concurrent languages with distributed programming support. The first type of languages are popular because these basically extend on languages to which programmers are accustomed. On the other hand, concurrent languages have gained popularity in the last few years because of their inherent support of constructs for communicating processes. Such languages utilize either of the two memory models outlined earlier: shared-memory or distributed-memory (message-passing). When programming distributed systems, message passing models have been found to be generally more appropriate because the programmer does not need to know where the other processes are located. Distributed processes can 30 even live on heterogeneous architectures
{ "page_id": null, "source": 7318, "title": "from dpo" }
- and all this does not affect the programmer of the system itself. In the past few years, a number of distributed programming languages each implementing its own flavour of message passing distribution, have been proposed. Andrews in suggests that these languages should be com-pared according to their basic communication mechanism. Two classes of languages are identified according to their communication mechanism: • Send/Receive communication The languages rely on send and re-ceive primitives for communications. Languages with send/receive communication differ in the way in which communication is synchro-nized. For example Occam and PFX for .NET (Parallel Extension Framework) 2 use synchronous communication with blocking send and receive. Another distributed language with send/receive communica-tion, is Erlang. Erlang uses asynchronous message passing with mail-box style concurrency - messages are delivered to the application not in the same way as they are received (or even sent), but in the order that they are requested by the application. • Remote Procedure Call Remote procedures call (RPC) languages try to provide an abstraction of a normal procedure call. With such languages, a process can call a procedure or function which executes on another computer. After that this function terminates, it returns the result back to the caller. One such implementation is Remote Method Invocation (RMI) in Java. However, there are various argu-ments against RPC’s. Steve Vinoski and Joe Armstrong argue that wrapping a remote operation and making it look as if it were local, will lead to problems because the failure modes of local and remote operations are completely different. Not being able to determine whether a call is local or remote is also problematic when trying to optimize the code. Though when it comes to computational power, both models are equally powerful, in practice every distributed language provides its own develop-ment techniques
{ "page_id": null, "source": 7318, "title": "from dpo" }
for solving distributed programming problems (such as cop-ing failure). Moreover, in languages such as Erlang, it is rather easy to > 2These two languages are not really distributed languages - rather these are concurrent languages. 31 ”mimic” RPC’s with custom behaviour . 2.9.1 Erlang Erlang is a functional programming language designed from ground up with a concurrency model in mind. Erlang follows the asynchronous message passing model but it also provides various other features resulting in a novel way to program reliable concurrent and distributed systems. 2.9.2 Programming in the presence of failures The primary goal of this project is to provide basic building blocks for re-liable distributed systems. Most of the distributed programming languages mentioned leave the job of failure detection and failure handling to the hands of the programmer. Moreover, no language takes into consideration software errors which might be caused by the programmer forgetting to handle cer-tain types of data. One language which stands up against such arguments is Erlang, which as Joe Armstrong states, its purpose was to provide a mechanism by which to ”program systems which behave in a reasonable manner in the presence of software errors” . Fault-tolerant distributed systems require careful design and Erlang’s primary aim is to address this requirement. Whereas Erlang does not directly solve the agreement prob-lems outlined in section 1.2, Erlang does provide a language which by design eliminates most classical problems incurred in distributed programming, fa-cilitates the structuring of code to avail from the natural concurrency of the underlying application and also provides a runtime environment with advanced distributed operating systems capabilities. Moreover, Erlang also helps overcoming problematic cases of unhandled datatypes, thanks to its dynamic typing system which can, according to Armstrong, helps han-dling instances which the programmer misses to explicitly handle in the code. These features
{ "page_id": null, "source": 7318, "title": "from dpo" }
set apart Erlang from other concurrent languages (such as Occam) and concurrent/distributed libraries for traditional programming languages (such as OpenMP for C++ and Parallel Extensions Framework for .Net). In fact, these languages fail to define explicitly behaviour under failure. 32 2.9.3 The strength of Erlang In his Phd thesis, Joe Armstrong identifies the major requirements for a fault-tolerant system and later on specifies how each of these requirements are met in Erlang . These requirements are derived from the requirements outlined by Gray, Schneider and Renzel (see section 2.8). These requirements are discussed in the context of Erlang in . The fol-lowing is a subset of these requirements which are directly related to this project: • Concurrency : Erlang processes are very lightweight and the Erlang runtime supports thousands of concurrent processes. Processes inter-act by exchanging messages. In this project, the suite of Erlang be-haviours will serve as an intermediate layer between user applications and the system, hence fast turnaround is definitely a requirement. • Seamless Parallel and Distributed Portability : Erlang abstracts the distributed model into just mere parallelization. Processes com-municating and interacting on a multicore machine, work well when distributed amongst several nodes. This will help us structure the test-ing and evaluation of code for this project - the libraries can first be test as a parallel program (on a single machine) and then distributed amongst a number of nodes. • Failure Detection and Fault Identification : When a process fails, all linked processes are notified with the failure and given a reason for this failure. This will form the basis of failure detection in this project. Moreover, Erlang also adheres with fail fast specifications of Schneider and Renzel Erlang processes immediately stop with a reason when a function is called with incorrect arguments. Erlang was built to
{ "page_id": null, "source": 7318, "title": "from dpo" }
target robust code. The functional syntax of Erlang might be a repelling feature for, however it reduces the amount of code re-quired between four to ten times . Generally, more code means more bugs and hence these are suppressed as well. Moreover, thanks to the requirement of non mutable state functions, Erlang cuts down on the shared state night-mares of deadlock and race conditions - this is because functions have no internal mutable state due to single assignment. These problems can only occur when interacting with the external world or when poorly handling 33 asynchronous messages (example receiving messages out of order or when assigning wrong priority). Erlang also boasts a number of industry strength characteristics. The Erlang runtime machine provides advanced operating systems features such as automatic memory management and distribution of processes between nodes . The Erlang runtime is also very robust with uninterrupted uptime. Moreover, Erlang comes with OTP (Open Telecom Platform) which provides standard patterns (or Behaviours) to extend fault tolerant code. This library includes behaviours for: Supervisors, Generic Servers, Generic State Machines and Event Logging . Though not being a mainstream language, support for Erlang is not hard to find. It is very easy to interface Erlang with other languages. So, for example, Erlang can be used to code a robust server core, whereas the application layer compo-nents can be written in another language, with which developers are more confident, and ultimately plugged in to form one system. Finally, there is growing community of users which actively improves the whole Erlang environment with libraries, documentation and even ports of the runtime machine to different operating systems - highlighting the fact that Erlang is actually gaining ground after twenty years from its inception. Most, if not all, of these features are clearly missing in alternative
{ "page_id": null, "source": 7318, "title": "from dpo" }
con-current languages or frameworks - making Erlang the natural language of choice for various distributed projects. Among the various systems which are running Erlang code underneath the hoods, one finds: the Facebook’s chat server, Wings 3D - a 3D graphics engine and modeller, Amazon’s distributed database SimpleDB and an on demand distributed computing routing mesh at Heroku. Erlang is usually criticized for its ”odd” syntax and programming style. Re-cently, various clones of Erlang started emerging (such as Scala and Retlang library for .Net) and are proposing to overcome this problem. However, in doing so, these break the immutability Erlang boasts. For this project, the protocol suite will be coded in Erlang. This will ensure that its code is availing itself from the benefits and robustness of Erlang. The application logic will then simply attach to this code - this need not even be written in Erlang itself. Erlang will serve as the layer which robustly performs critical and recurrent tasks, which then interfaces with the user’s code. 34 2.9.4 Conclusion This section served to introduce the main concepts behind this project. Var-ious aspects of distributed computing have been outlined. In particular, a number of recurrent problems were outlined. These problems are the ba-sis for the proposal in the next section. The requirements of distributed programming languages for reliable code and robustness in the presence of failures, where then outlined. Finally, Erlang is chosen as the implementa-tion language for this project. 35 Chapter 3 # Implementation Framework # 3.1 Introduction Various literature exists on the subject of Distributed Agreement Protocols .In particular, different algorithms have been proposed as a solution to the main distributed agreement problems (outlined in the previous chapter). In this thesis, various established algorithms are studied and implemented. These algorithms are adaptations of the work of Nancy Lynch
{ "page_id": null, "source": 7318, "title": "from dpo" }
, Leslie Lamport , Toueg and Chandra , Guerraoui and Rodrigues . In this chapter, a common framework for the implementation of such al-gorithms in Erlang, is outlined. This chapter builds on Erlang’s features, to achieve a framework which provides the necessary environment for the implementation of such algorithms. In particular, this chapter proposes a way on how the agreement algorithms shall be implemented, so as to bridge the gap between theory and practice. # 3.2 Distributed Computing Abstractions Distributed computing consists of a number of hardware and software enti-ties which compose the distributed system itself. From a conceptual view, processes communicate to one another, however there are various other en-tities which need to be considered such as nodes, failure detectors, links and the network itself. In practice, these are all depend on the deployment envi-ronment, so in this project an abstraction for these entities is done. These abstractions are mainly influenced by the way Erlang deals with these enti-36 ties and the interface it presents to the programmer. 3.2.1 Processes A distributed system is composed of a number of elements each performing some form of computation. In this project, any computational element is abstracted with the notion of a process . A process is assumed to be characterised by: • Thread of Execution : Every process consists of the execution of some code. Though no assumption is made on execution time, it is assumed that there is no unjustified indefinite waiting, but processes run to completion. • Local Memory : Every process consists of a set of local variables. The value of all these variable at a particular point, make up the state of the process. • Unique Identifier : Every process can be identified by a process iden-tifier (PID). It is assumed that no ambiguity exists with
{ "page_id": null, "source": 7318, "title": "from dpo" }
processes identification - that is despite the distributed environment, no two processes (not even on distributed nodes) can have the same PID. Note that this is a fair assumption to make because Erlang guarantees such a property is true by encoding data about the node identifica-tion in the PID itself. Another way by which to identify processes, is through a global identifier . A global identifier is a systemwise unique name, which is an alternative to using PID’s. Of course, with global names, the responsibility of appointing unique names is on developer himself. • Mailbox : Processes can communicate by sending messages to PID’s or global identifiers . When these messages are eventually posted to the process’ mailbox - a storage place for these messages. The process can then fetch these messages and read their content. 3.2.2 Nodes It is probably best to think of a node as a distinct interacting computer. However in reality, a node can consist of cluster of computers. Alternatively 37 multiple node environments can interact on the same physical machine, with-out the need for any message to touch the network . So it is better to think of a node as any form of replicated set of processes which together form this single entity - the node. In this project, every Erlang’s runtime environment (or shell), is considered as a node. Every shell, hosts a number of Erlang processes. Multiple Erlang shells can be opened on the same machine, or else every shell can be hosted on a different machine. A node is taken as the unit of failure - if a process crashes, all other processes together in that node would crash. In terms of Erlang, this means that all processes within a shell are linked, and the failure of one process, would lead
{ "page_id": null, "source": 7318, "title": "from dpo" }
to the abrupt termination of all the other processes in that shell. 3.2.3 Communication Links Interconnecting distributed nodes involves various infrastructure such as routers and switches. This setup varies greatly depending on the underlying network architecture. In this project, all this infrastructure is captured by the link abstraction. A link exists between two nodes if a message can even-tually be delivered between the two. This connectivity is the responsibility of lower level protocols such as routing protocols. In practise, a link might exist between two processes, but messages could be lost in transmission. Hence, network communication is assumed to be unreliable. Note that however, the network is assumed not to generate messages on its own. A simple workaround is used to overcome the problem of unreliable commu-nication. Whenever a process Pi sends a message to Pj , this message can be repeatedly sent by Pi until it receives an acknowledgement from Pj . Such a mechanism would guarantee eventual delivery the message, given that none of the two processes actually crashes. Moreover, so as to avoid that Pi blocks until the message is actually delivered by Pj , this repetitive sending could be done by a separate process. Note that such a mechanism, does not guarantee that every message sent by Pi will reach Pj - it could happen that a message Pi sent is lost and Pi crashes before resending the message again. Such a mechanism is typically handled by lower level protocols such as TCP. Erlang makes use of such protocols , and hence the usage of such 38 a mechanism is implied. Note also that links are assumed not to create message erroneous message on their own ( no creation ). 3.2.4 Failure Detectors In the previous chapter, the notion of failure detectors was explained. These
{ "page_id": null, "source": 7318, "title": "from dpo" }
provide information as to which processes it detects as having crashed. Fail-ure detector can only give information as to whether a process is alive or not, but does not give information about the state of the processes (such as its point of execution). Moreover, in this project a Perfect Failure Detector is assumed. This means that the failure detector classifies a process as having crashed, then that process really did crash ( accuracy ). Moreover, it will eventually detect all crashed processes ( completeness ). When this Perfect Failure Detector clas-sifies a process as having crashed, it triggers a crash event. The prototype of this event is given in listing in figure 3.1 below: Figure 3.1: Prototype of the Perfect Failure Detector crash event The failure detector triggers this event on all modules which utilize it. With this event, it returns an argument Who , which denotes the name of the process which crashed. # 3.3 A Common Structure for all Algorithms This section will present the overall structure of agreement algorithms imple-mented. This structure serves as a common way to present these algorithms in this project. Moreover, various syntactical details will be outlined and briefly described. Later on in this chapter, an actual Erlang implementation of this proposed layout, is presented. The algorithms presented here will follow an Asynchronous Event-handling Model . Basically all algorithms here will have the format of an event and its handler . The template for algorithms given in this presentations is given below: 39 Figure 3.2: Structure of algorithms given in this presentation As can be seen in figure 3.2, algorithms consist of three main sections: a State definition, a number of helper functions and a number of event han-dlers. Prior to these there is also a module name and behaviours imple-mented. All these
{ "page_id": null, "source": 7318, "title": "from dpo" }
are explained in detail below: • Module Name : The module definition defines the name of the mod-ule. It is used when external modules need to call functions or trigger events locally defined in this module. • Behaviours implemented : This concept comes directly from the Erlang behaviours. In Erlang, a behaviour is a guarantee that this module will implement a number of functions which are requested by the behaviour module. Typically the behaviour module will then callback these functions during its operation. • State Definition : This State definition outlines the constituent ele-ments of the State record. Simply put, the state record is a globally available record which contains data stored by the algorithm until some particular point in time. In practice, due to Erlang’s program-ming methodology, internally this state is passed as a parameter to 40 the handler function or to the message handling loop. • Helper Functions : Helper functions are common routines which are either used extensively, or which help structure the code better. These functions are invoked from within the event handlers or from other helper functions. These functions can take arguments and return a value to its caller. • Event Handlers : Event handlers define the actions which need to be taken when an event is triggered. These actions are invoked in isolation and each handler needs to be non blocking. Event handlers are essentially what makes up the algorithm itself. These can be seen as the entry points to the algorithm. In a nutshell, every algorithm is presented as a sequence of responses to particular events. During an execution of the algorithm, events received are queued in chronological order. The program will then repeatedly dequeue an event and execute the corresponding handler or wait for more events to be triggered. Event handling is
{ "page_id": null, "source": 7318, "title": "from dpo" }
carried out asynchronously. 3.3.1 Types of event triggering Events can be triggered in two ways. Firstly, an event may be directly-triggered by some module through the use of the trigger keyword. The other type of event triggering is predicate triggered event triggering. Such events will be triggered when a particular conditional expression becomes true. 3.3.1.1 Directly-triggered events Directly-triggered events can be triggered from any module. Conceptually, these can be seen as function calls which have asynchronous message han-dling semantics - an event is triggered in a similar fashion to a function call, however, the process handle them sequentially, even if multiple processes trigger events to this process, at the same time. As an example of directly triggered events refer to the listing in figure 3.3. The event header is given on line 1, preceded by the upon directive. The upon directive essentially helps create a distinction between normal helper functions and event han-dlers. The remaining code, after the event header is the handler code. As an 41 example of the directly-triggered event notation, a sample triggering is done on line 4. This notation for triggering an event (and even external helper functions) is identical to the MFA (Module Function Arguments) notation of Erlang ( Module name : function name( arguments...) ). Note that the trigger keyword is used to signify that the event is invoked asynchronously as opposed to a function call. Figure 3.3: Syntax of direct triggered events and event handlers. 3.3.2 Predicate-triggered events Predicate triggered events are triggered when some particular conditional predicate becomes true. These are like runtime monitors for a particular state (or sub-state) to be reached. When this happens, a local event is trig-gered. As an example of predicate-triggered events, refer to the listing in figure 3.4. Listing 3.4a shows the template code for a
{ "page_id": null, "source": 7318, "title": "from dpo" }
predicate triggered event handler. On line 1, preceded by the upon keyword, there is the pred-icate condition which will trigger this event. As an example, listing 3.4b shows an event which is triggered when a set (Colours) gets an element with value blue. Figure 3.4: Syntax of predicate triggered events. 42 3.4 Module Composition The suite of Erlang behaviours given here is composed of a number of mod-ules, each implementing some particular algorithm. Moreover, much of these modules build on one another; several modules extend the functionalities of other modules. This can be achieved rather easily through the use of be-haviours. Essentially this creates a layered stack of modules which interact with each other through well defined interfaces. These interfaces are simply well defined events which may be triggered or which can be handled by the module. Hence an interface for a module will consist of: • External Events Handled : These are events, which can be triggered by some external module and for which an event handler resides within the module. These can be seen as asynchronous requests which can be posted to the module. • Callbacks Expected : A callback is an event which is triggered and is expected to be handled by the user of this module. Typically these events are triggered at ”milestone” points during the execution, and signify that some operation requires attention. For example, a module may invoke a callback when it has processed or received some form of data. Through these well defined interfaces, modules can extend and interact with each other much like with interfaces and inheritance in Object Oriented Programming. This is done by having modules which trigger events in other modules. This latter module performs some processing and then it triggers an event in the first module in the form
{ "page_id": null, "source": 7318, "title": "from dpo" }
of a callback. As an example, consider a module for broadcasting messages called broad-caster . This module is able send out messages, by handling the broad-cast(Data) event. Moreover, when a message is received, it callbacks the deliver(Data) event. Now consider, a module called namer , which is used to send and receive names to other processes. It handles the send name(Name) event when a name is to be sent and callbacks the received name(Name) event, when a name is received. For the sake of the example, assumed that the namer module, does some additional processing on the Name before broadcasting it. 43 Figure 3.5: An example of module layering Figure 3.5 gives a possible composition of the two modules. The namer mod-ule, makes use of the broadcaster module to transmit and receive names, and perform additional processing on them. It should be noticed that the namer module, not only requires to trigger the right event on the broadcaster mod-ule, but also needs to implement the necessary callback function, expected by the broadcaster module. # 3.5 Delving deeper In this section, a brief overview of various elements which make up the language will be given. The essential constructs used throughout this pre-sentation as well as standard notations, will be outlined. Note that this is merely an overview and not a complete explanation of these tools or tech-niques being used in this presentation. Most of these techniques are directly borrowed from Erlang (or functional programming in general). The reader is expected to be familiar with functional programming techniques. 3.5.1 Variables As with any programming language, this language will have variables. Vari-ables identifiers consist of an alphanumeric string starting with an uppercase alphabetic character. In order to keep algorithms concise, in this presenta-tion the single assignment is relaxed - state variables can be
{ "page_id": null, "source": 7318, "title": "from dpo" }
assigned mut-liple values. However in section 3.2.4, a method to convert to pure single 44 assignment, as used in Erlang, is described. 3.5.2 Atoms Atoms are simply symbols (identifiers) which can be assigned. As an exam-ple, yellow in Listing 3.4, is an example of an atom. Atoms are different from enumerated variables, in that two atoms with different names, can never match. Atoms are identifiers starting with a lowercase alphabetic character. Atoms are one of the main elements of Erlang. 3.5.3 Comments Comments can be written anywhere in the code by preceding the comment with a % character. This comment will span until the first newline which is encountered. 3.5.4 Tuples Tuples are a way in which data elements can be grouped together as a single entity. These are very much like records in conventional programming languages. These can be used to group together different data elements, and pass them together as a single variable. 3.5.5 Pattern Matching Pattern Matching is a technique widely used in functional programming. Simply put, pattern matching will ensure that a particular action is taken, when data of a particular format is to be processed. Pattern matching can be used in most of the constructs including if and case statements, and also for function execution itself. A function can be declared with a particular data pattern in the header. This function will only be executed when that pattern matches the data at runtime (and no other function has pattern matched). Putting a Variable, in the place of a pattern, will match all data patterns. Although understanding pattern matching in practice, can be rather straight forward, giving a complete explanation of this subject would require a lengthy explanation. For this reason, for a complete explanation of pattern matching please refer to . 45 3.5.6 Sending and
{ "page_id": null, "source": 7318, "title": "from dpo" }
Receiving messages Since this project deals with distribution over remote nodes, there must be a way for communication amongst these nodes to take place. This is done by using message sending and receiving constructs. These constructs are taken directly from the Erlang language. Sending messages is done through the use of the ! construct. This construct has the following structure: ! ACTION PATTERN2 -> ACTION ... [ELSE -> ACTION] end. The receive construct waits until a message is available and then invokes an action corresponding to the message type. Since a message can have different types, pattern matching is done on the messages received to determine what action to take. # 3.6 An Implementation in Erlang The various notions which have been outlined so far need to be implemented in Erlang. This section gives an overview of the mapping between the ab-stractions given here and how these were implemented in Erlang. 46 3.6.1 Process structure Every distributed node contains a particular organisation of Erlang processes which together form the orchestration layer of every node. These processes have structure shown in figure 3.6 below: Figure 3.6: Organisational structure of processes in distributed nodes. 3.6.1.1 Inter-node Communication Every node contains one Main process . The aim of this process is to serve as an incoming message gateway: all messages coming from external nodes will be received by this process and forwarded to the associated receiver module. It can be noted that for a process to be able to send a message to another 47 node, it must know the PID of the receiver. This means that if it requires to communicate with all processes, it would require to store all PID’s for the processes from all nodes (even though such communication pattern is rarely required). However, in the approach taken with the
{ "page_id": null, "source": 7318, "title": "from dpo" }
Main process, only the PID of the Main processes is required to be known. Sender processes will send their messages to the Main process of the destination node, which will in turn take care of ”forwarding” the message to the corresponding receiver process. But how does the main process know which process is the intended receiver of the message? Here some pure Erlang techniques come into play. Since it is assumed that this suite is replicated on all nodes, the set of processes for this suite is the same on every node. Moreover, as explained earlier, Erlang provides a way by which to register process names - giving names to processes which can be used for communication in the place of the PID. Hence, each process can be given a pre-defined name and the same names are used on all the nodes. Now in order for the sender to indicate to the Main process, which process is the intended receiver, it can send the pre-defined process name of the receiver as part of the payload. In Erlang, this is achieved by sending the message data which was originally intended to be sent, together with the pre-defined name of the process, as a single tuple. When the Main process, at the destination node, receives this message, it can read the registered name of the process directly from the message, and forward it the original message. The actual ”forwarding” of this message will occur by triggering an event. The event triggered is the received event. Its prototype is given below in the listing in figure 3.7: Figure 3.7: received event prototype So now, if a process receives a message, a received event will automatically be triggered. This means that the process does not need to block and wait for some messages to
{ "page_id": null, "source": 7318, "title": "from dpo" }
be received, but rather when the message is received, this event handler will be triggered. 48 3.6.1.2 Utilizing the Erlang Failure Detector A lot of emphasis has been made on the use of failure detectors as means by which to abstract knowledge about failures. However, in figure 3.6, these do not seem to have a directly associated process. The reason for this is because here we are building on top of Erlang’s existing failure detector. Erlang provides means by which to monitor processes for liveness. This is done by link ing processes together and setting up processes to trap EXIT signals. When a process crashes, all the other processes will be notified with this EXIT message. The handling of the EXIT messages sent by Erlang’s failure detector are handled in the Main process. The Main process is linked to all other remote Main processes in the system. It also traps EXIT messages and triggers a crash event to all processes on the node. Internally, the Erlang’s failure detector uses a heartbeat mechanism to de-tect failures. In terms of failure detectors as presented by Chandra and Toueg in , this has the following implications: • Completeness : Given that if a process crashes, it will not send out any heartbeats and so, given that these messages could only originate from the failed node itself, all monitoring nodes will detect its failure. This is known as Strong Completeness . • Accuracy : A heartbeat mechanism is, however, prone to network delays especially when there is a network overload . This could lead to a situation where the failure detector would classify a process as faulty, when in reality it is still alive. Moreover, Erlang’s failure detector will not attempt to reassess the liveness status of a process which is detected as failed
{ "page_id": null, "source": 7318, "title": "from dpo" }
- once a process is suspected to be failed, it will not be classified as alive (unless the process is manually re link ed). This violates the accuracy property because it causes processes to be falsely detected as having failed. Hence Erlang’s failure detector can be merely seen as performing any spe-cial failure detection. However, as limited as it is, it still helps separating concerns about failure and failure detection from the rest of the code. More-over, studying and devising reliable algorithms to ensure the strength of the failure detector, would be another research project on its own. 49 For this reason, it was chosen to work with the existing failure detector and propose the extension of this failure detector for future work. In order to partially ’patch’ this shortcoming, in this project, a simple approach was taken - any process which is detected as failed will be sent a KILL message to truly kill itself and broadcast that failure message to all other processes. This technique ensures that the accuracy property is now satisfied, despite inaccuracies due to network delays. Note that however, the process which is detected as having failed, keeps doing its execution until it receives the KILL message. During this period, it may even take conflicting actions with what the process which detected it expects. This might break certain properties of the algorithm. In this work, examples of where this might happen are pointed out. 3.6.2 Local Processes Interaction Figure 3.6 indicates that every node houses at least three other processes, apart from the Main process. These are Reliable Broadcast , Consensus and Atomic Commit . In reality, these are the classes of algorithms which are implemented in this project - each class contains a number of algorithms. Essentially, these are each handled by a separate
{ "page_id": null, "source": 7318, "title": "from dpo" }
process which maintains the state of that particular algorithm. These algorithms were each implemented in separate modules. This mod-ule, essentially, handles events it receives and changes the state accordingly. Below is a list of all the modules implemented: • Reliable Broadcast 1. be rb : Best-Effort Reliable Broadcast 2. r rb : Regular Reliable Broadcast 3. u rb : Uniform Reliable Broadcast 4. c rb : Causal Reliable Broadcast 5. to rb : Total Order Broadcast • Consensus 1. rf c : Regular Flooding Consensus 2. rh c : Regular Hierarchical Consensus 50 3. uf c : Uniform Flooding Consensus • Non-Blocking Atomic Commit 1. nb3p ac : Three Phase Commit 2. cb ac : Consensus Based Commit Each of these modules will be explained in detail in the coming chapters. 3.6.3 A Design Pattern for all modules All processes maintain an internal state by having a recursive function which waits for new events, handles them and recurses with the new state. If this is to be done in Erlang, it would look something like the code in figure 3.8. Figure 3.8: Maintaining an internal state through recursive pro-cesses in Erlang Here, a loop function is defined. This function takes one argument - the State. It waits until a message is received. The corresponding handler is invoked depending on the message type. Note that the handler will update the State (line 6) and then recurse with the new state. The new State is function of the old state and the message received. Note that generally the state consists of a tuple with a number of data values. A more generic form of this design pattern, has been implemented as part of Erlang/OTP modules. This is known as the gen server behaviour, which is an implementation of a generic server. The
{ "page_id": null, "source": 7318, "title": "from dpo" }
gen server is written to make 51 code more scalable and maintainable . It also gives way to easier debug-ging and easily provides features such as dynamic upgrades. Moreover, by using the generic server, the code will be structured in a ’standard’ way -making it easier for external programmer to understand and work with the code. In this project, all processes are implementations of the gen server be-haviour. As mentioned, all algorithms listed in 3.6.2 have an associated process. This process implements the gen server behaviour. Moreover, these processes can be seen as a real-world implementation of the template for all algorithms described here (refer to figure 3.2). The gen server provides the roadmap from this template code to actual Erlang code. The following section present another process template - this time, it shows how everything discussed in this chapter can be implemented in Erlang. 3.6.3.1 Putting everything together In order to present everything together, a template depicting the organi-sational structure of source code, as implemented in Erlang, was devised. In this section, various parts of this template will be discussed, and their mapping with what has been discussed in this chapter, will be outlined. Listing 3.9 shows the first part of this template code. Apart from the export declarations (lines 7 to 11), this code is very similar to that in figure 3.2. In fact, here the module name, behaviours implemented and state record are defined. Here the gen server behaviour (line 4) and failure detector behaviour (line 5) are implemented. The export statement on line 9 is used to list out the functions which other modules can call to ’trigger an event’. These exports are given as a list of function names followed by their arity: so here two events are being published ( some event1 and some
{ "page_id": null, "source": 7318, "title": "from dpo" }
event2 ). The export on line 12, lists the functions which act as the callbacks implemented for other modules. The crash event is triggered by the failure detector and should be implemented by all processes using the failure detector. Thus, in terms of code, an event is simply a function call defined in a module. That function call will, however, not handle the event itself. Listing 3.10 gives a definition of the two example events exported and also of the crash callback. These consist (lines 26, 29 and 32) of just a gen server cast . A gen server cast is simply an asynchronous request to a gen server 52 Figure 3.9: Template with code for all algorithms implemented (Part 1) Figure 3.10: Template with code for all algorithms implemented (Part 2) 53 which is not expected to return anything back. Here a cast is sent to the gen server started by this module (identified by the ?MODULE macro). No-tice that in the cast, the second parameter is a tuple with all the parameters of this event and an atom identifying the event. This tuple is the request to be handled asynchronously by the gen server . The reason for not handling these directly here is twofold. Firstly because at this point we have no ac-cess to the State and secondly is to ensure that all requests are processed sequentially. Figure 3.11: Template with code for all algorithms implemented (Part 3) But where are these gen server casts handled? The gen server will invoke a handle cast callback whenever a cast can be handled. Listing 3.11 defines the handle cast for this process. Note that the handle cast function takes two arguments (lines 66, 71 and 76): the first one is the request which was cast ed to the server,
{ "page_id": null, "source": 7318, "title": "from dpo" }
whilst the second one is the State of the server. Note that this function uses function pattern matching to choose which of the functional clauses to invoke. Internally this handler will perform the algorithmic action required to handle the request. Notice that this function returns a tuple which holds the updated state. This state will be the one stored internally by the gen server and which will be passed to the subsequent handle cast .In the handle cast handlers, one can note that exactly before returning the new state, a call to check predicates is made. This call is used as part of the implementation of predicate triggered events (refer 3.3.2). Since there is nothing like predicate triggered events in Erlang, a check is made exactly at 54 the end of every gen server cast handler. Figure 3.12: Template with code for all algorithms implemented (Part 4) Listing 3.12, shows how predicate triggered events are implemented. The check predicates() function (line 50 onwards), takes the State as a parame-ter. Here two predicate checks are made by calling predicate check1() and predicate check2() - these internally check whether a predicate is satisfied, and if so perform the associated action and return with the new state. Note that here, there is a little subtlety involved: it could be that after check-ing the predicates, an action is taken, however, at this point, the second predicate check action could have caused the first predicate to be satis-fied once again. This requires that the checks should be made again until none of the predicates matches. This is handled on line 55, where the final state after checking all the predicates is compared with the initial state of the check predicates() function. If there a change in the State , then this function recurses to recheck
{ "page_id": null, "source": 7318, "title": "from dpo" }
the predicates. Otherwise, the passed State is returned. 55 3.6.4 Working with Single Assignment Being a functional language, Erlang has single assignment of variables. Es-sentially this means that every variable can only be assigned a value once. However, the algorithms presented in literature, never assume they are work-ing with such a paradigm. However, as explained, every algorithm will be implemented with the concept of a module which maintains an internal state. In order to be able to change part of the state, it is required to create a new variable with the new values, and copy the unchanged values from the previ-ous state. This, however, does make the code longer and less readable, and for this reason, the internal code of every event handler in this dissertation, will not be presented using this single assignment. # 3.7 Conclusion The aim of this chapter was to gradually bridge the gap from theory to practice - and propose how various concepts were implemented in reality. It gave us the techniques by which all algorithms shall be described here and finally showed, to some extent, how these can be implemented in reality in Erlang. The following three chapters will outline various algorithms for solving Reli-able Broadcast, Consensus and Atomic Commit problems. These algorithms are the core of this project and this chapter presented the techniques which serve as a means to implementing these algorithms. 56 Chapter 4 # Reliable Broadcast # 4.1 Introduction The first class of agreement algorithms studied in this project, are Reliable Broadcast algorithms. These algorithms deal with the transmission of mes-sages which need to be delivered by all processes, including the sender itself. These algorithms study this problem, whilst keeping process failures into consideration. The algorithms presented here, assume the system model outlined so far. In this chapter, various
{ "page_id": null, "source": 7318, "title": "from dpo" }
Reliable Broadcast specifications are presented, each having its own set of properties and characteristics. For each specification, an algorithm attempting to achieve these specifications, is outlined. For all algorithms, first the basic goal it attempts to achieve, is explained. Following this, the algorithms are explained in further detail, and any subtle intricacies are investigated. All of these algorithms are implemented in the framework presented in the previous chapter. # 4.2 Interface All reliable broadcast algorithms, follow this interface: • External Events Handled – init() Initializes the algorithm. 57 – broadcast(Msg) Sends Msg to all other processes. • Callbacks Expected – deliver( From, Msg ) Indicates that Msg was received from the process whose PID is From . # 4.3 Best Effort Broadcast 4.3.1 Overview The Best Effort Broadcast is the weakest reliable broadcast specification to be studied. It is a form of broadcast which does not provide any fault toler-ance guarantees and is consistent as long as the sender does not crash whilst broadcasting. Implementations for this broadcast specification is typically found in non-fault tolerant code; however, this broadcast will be the basis for various stronger algorithms, which wrap logic around it to address its shortcomings. 4.3.2 Specification The Best Effort Broadcast abstraction is a form of Reliable Broadcast which only guarantees consistent delivery if and only if the sender remains alive throughout the whole of the sending process. A Best Effort Broadcast ab-straction should satisfy the following properties: • Validity : If a correct process p broadcasts message m, this eventually gets delivered by all correct processes in the system. • Integrity : For any message m, every process delivers m at most once, and only if it was previously broadcast. 4.3.3 Algorithm Figure 4.1 gives an algorithm which implements the Best Effort Broadcast specification. This algorithm is known
{ "page_id": null, "source": 7318, "title": "from dpo" }
as the Basic Broadcast algorithm. The algorithm consists of just two event handlers. The broadcast event 58 Figure 4.1: Basic broadcast algorithm handler (line 9) is triggered by the user of this module, and it initiates a best effort broadcast. It iterates through all the processes in the system (denoted by Π on line 10) and sends them the passed message. Notice that a helper function send to() is used, which sends the PID of the sender (returned by self() function on line 5) together with the message itself. The received event (line 13), is triggered whenever a new message is received (as explained in section 3.6.1.1). This event indicates that some other pro-cess has broadcasted a message which is returned to the user by triggering a callback beb deliver . 4.3.4 Erlang Implementation Despite being very short, there are still some points which are worth out-lining. Firstly, a list with all PID’s (as required in line 10) can be returned by calling node utils:get all peers() which returns a list with all the PID’s of the Main process on each node. Having this list, it is worth noticing that the predicate on line 10, can be neatly implemented using lists:foreach/2 .This function takes the list of all processes and the send to() function, as a higher order function, which is almost identical to that on line 10. 4.3.4.1 Implementation Optimisations There are not many performance considerations to be made for this simple algorithm; however, one simple tweak was to use a failure detector, and 59 avoid wasting resources to send to processes which are known to be crashed. 4.3.5 Evaluation The suggested algorithm meets the Best Effort Broadcast specifications due to the properties of links taken in consideration in this project (refer 3.2.3). The message broadcasted, should eventually reach
{ "page_id": null, "source": 7318, "title": "from dpo" }
the destination, and since this is sent to all processes, the validity property is satisfied. Moreover, the integrity property, follow directly from the no creation and no duplication properties of links (refer 3.2.3). The Basic Broadcast algorithm, however, only guarantees agreement if the sender is not faulty. Figure 4.2: Violation of agreement with the basic broadcast algo-rithm with a faulty sender Figure 4.2, gives a run of this algorithm. At point A, Process P1 starts a broadcast, but crashes without managing to send messages to all processes. As can be seen, processes P2 and P 3, do receive and deliver the message, however, process P4 does not. This could possibly leave the system in an inconsistent state.. In terms of performance, in general the algorithm suggested requires |Π| messages to be transferred over the network with every broadcast event. 60 4.4 Regular Reliable Broadcast 4.4.1 Overview The Regular Reliable Broadcast protocol strengthens the specifications of the Best-effort Broadcast by taking into consideration process failures and taking the appropriate measure to ensure that the system still remains consistent. Regular Reliable Broadcast is resilient to sender crash failures: it ensures that either all processes get the message broadcasted, or that none at all gets the message. 4.4.2 Specification The Regular Reliable Broadcast guarantees that the all correct processes are consistent with respect to the broadcast abstraction. Note that this protocol does not, however, provide any guarantees on the state of the crashed pro-cesses. A Regular Reliable Broadcast protocol satisfies the same validity and integrity properties as the Best Effort Broadcast specification. In addition to these it also guarantees an agreement property, as follows: • Agreement : All correct processes deliver the same set of broadcast messages. • Validity : If a correct process p broadcasts message m, this eventually gets delivered by
{ "page_id": null, "source": 7318, "title": "from dpo" }
all correct processes in the system. • Integrity : For any message m, every process delivers m at most once, and only if it was previously broadcast. 4.4.3 Algorithm One particular implementation of the Regular Reliable Broadcast is the Lazy Reliable Broadcast algorithm, given in the listing in figure 4.3. This algo-rithm builds up on the Best-Effort Broadcast protocol to ensure that the Agreement property is satisfied. It utilizes a failure detector (line 4) to en-sure that correct processes will take over when a sender crashes. The notion of the algorithm is that every correct receiver should broadcast the mes-sages it received from some process which is detected to have crashed. In this sense, a process which receives a message from a faulty process becomes 61 Figure 4.3: Lazy reliable broadcast algorithm 62 a Relay for all the previously sent messages by that process. Hence every process must keep track of the messages it received from all processes, in order to be able to relay these messages when their sender crashes. These are held in a map data structure, called From .A basic run of this algorithm is given in the process/time diagram in fig-ure 4.4. Figure 4.4: A run of the lazy reliable broadcast algorithm with faulty sender In figure 4.4, process P1 starts a regular reliable broadcast (Point A) and crashes shortly afterwards, in a way that the message is only actually sent to process P2. Process P2 receives and delivers the message (point B). At this stage, the system is in an inconsistent stage, because process P2 delivered a message which processes P3 and P4 did note even receive. However, because of the failure detector, process P2 knows or will eventually know that process P1, the sender of the message, is dead. At this point, process P2
{ "page_id": null, "source": 7318, "title": "from dpo" }
will relay the message to the other processes in the system. In this run of the algorithm, only one process ( P2) was lucky enough to be sent the message before the death of the sender. If more processes were sent this message, more than one process would become a relay of the sender process. Since the job of the relay process is to retransmit the message to all other processes, having multiple relays would signify that the processes would receive the message multiple times. But due to the fact that this is the same message being received multiple times, the algorithm should only callback the rrb deliver() event once. In order to solve this problem, the Delivered , a set containing all the mes-sages which have been delivered Delivered , is kept. Before triggering rrb deliver() ,63 a check is made to determine whether the message has already been deliv-ered (is an element of Delivered ). This event will be triggered only when the message has not already been delivered. 4.4.3.1 Dissecting the Algorithm In the listing in figure 4.3, the state of the algorithm is given in lines 7 to 11. This state holds the set of correct processes, Correct and the set of messages which have been received and delivered, Delivered . It also contains a map between all processes and the messages received from each process. The initial state is defined in lines 15 to 17 as a handler to the init() event. Initially, the Delivered set is empty, the Correct Set holds all the processes, and all the sets in the From map are empty. Broadcasting a message is the same as the broadcast event of the best effort broadcast specification. This is shown in broadcast handler (lines 19 and 20), where a best effort
{ "page_id": null, "source": 7318, "title": "from dpo" }
broadcast event is triggered. It is important to note that the content of the message being broadcasted is a tuple with the following structure: { Sender, Message} The Sender contains the PID of the initial sender: because the message may be relayed by other processes; however, these do not change this sender field. The Message contains the data passed with the broadcast() event. When a beb deliver event is callback ed (line 22), the message received is en-tered in the Delivered set and a regular reliable broadcast deliver ( rrb deliver )event is triggered (line 25). This can only happen if this message has not been previously delivered; that is if it is not a member of the Delivered set (line 23). The message is also added to the From map to the set of messages originating from the relay process. So far no fault tolerant measures were taken. The remaining pieces of code deal with the fault tolerant characteristics of the algorithm. First, however, it is important to outline two scenarios which encapsulate the way failures are detected and handled. Consider a system with a sender process which broadcasts a message which crashes whilst broadcasting. There are two ways in which a receiver process, which has been sent the message, detects the failure: 1. The receiver process detects it has crashed before receiving the broad-casted message. 64 2. The receiver process detects it has crashed after receiving the broad-casted message. These two cases stem from the fact that no assumption with regards to message ordering, is made. The algorithm being outlined here handles both scenarios. The first case is handled by lines 27 to 28 where after delivering a message, the relay process of that message is checked to ensure that it still makes part of the Correct processes.
{ "page_id": null, "source": 7318, "title": "from dpo" }
If this is not so, then it might be that this process was one of the (lucky) processes who managed to get the message. Hence, this message should be broadcast ( best effort broadcast) to the other processes - so as to ensure that all other processes managed to get the message despite that the sender crashed. The second scenario is handled in the callback of the failure detector (ie the crash() event handler in lines 30 to 33). In line 32, all messages received from the crashed process, are relayed to the other processes. This set of messages is fetched from the From map. All histories of failures can be classified as any of these two scenarios or of a third scenario in which the sender process does not live long enough to actually send the original message to any other process. The latter scenario would still leave the system in a consistent state and its effect the same as if the regular reliable broadcast event was not even triggered at all. 4.4.4 Erlang Implementation The Regular Reliable Broadcast algorithm contains a number of elements which will reappear in subsequent algorithms and require some attention in their implementation. Particularly, one should notice that there are a number of sets being used. These were implemented in Erlang by using the sets module. This module provides routines to perform the common set access and comparison operations required. One important consideration deals with having a process broadcasting the same message. If this happens, the algorithm given here would simply not trigger a deliver event except for the first broadcast. In order to go around this problem, a unique number is appended with the message. This way, if the user actually rebroadcasts the same message, this number will have a different value and
{ "page_id": null, "source": 7318, "title": "from dpo" }
the algorithm would not think it has already delivered 65 this message. However, in the case when multiple relay processes broadcast the same message, this number is not altered and hence the receiver would determine that it has received a message which has already been delivered. Another important consideration is the implementation of the map data structure, used for the From map. This is implemented through the use of the dict Erlang module. A dict provides a map (or dictionary) data structure in Erlang. 4.4.4.1 Implementation Optimisations The main aspect of the algorithm which entails further investigation, is definitely the storage requirements of the algorithm. The Delivered and From structures continue to get populated with every message which gets delivered. It can be noted that, for the Delivered structure, it is not necessary to store the whole message; a hash of the message would suffice. In this project, the message is hashed with an md5 algorithm available in the Erlang crypto module. Nevertheless, this set still grows indefinitely and even worse, this techniques cannot be used with the From structure. One attempt to solve this problem might be that of having each process which delivers a message, acknowledge one another. When a process detects that a message was delivered by all other processes, it can remove this message from these sets. It turns out, however, that this method is prone to network message reordering which would lead to inconsistencies in the system. In order to solve this issue, it would be necessary to study the use of timestamps for such system. This idea is suggested as part of the future work and is outlined in section 9. 4.4.5 Evaluation The Lazy Reliable Broadcast Algorithm meets the Regular Reliable Broad-cast properties. It satisfies the integrity and validity properties due to the
{ "page_id": null, "source": 7318, "title": "from dpo" }
underlying usage of the Best Effort Broadcast . It satisfies the Agreement property because once a sender crashes, if a receiver exists, its failure detec-tor will eventually cause a crash event and the message will be sent to the other nodes. The Regular Reliable Broadcast provides fault tolerant prop-erties which ensure a consistent state amongst all correct processes. It is also rather efficient in terms of network utilization. The best case, when 66 no failures occur, it requires |Π| message exchanges. Once a sender crashes, the message will be sent by all receivers, to the remaining processes which are alive, by all receivers. Hence, in the worst case, the number of messages exchanged is in the order of |Π|2. # 4.5 Uniform Reliable Broadcast 4.5.1 Overview The Regular Reliable Broadcast protocol outlined in the previous section provides a fault tolerant broadcast mechanism which guarantees agreement amongst all correct processes. This, however, means that some process might deliver the message and crash, without sending the message to the other nodes. This can create problems if the delivery of such a message in-volves interaction with some outer system, leaving an inconsistent side effect. The Uniform Reliable Broadcast abstraction ensures that there is agreement on the delivered message between both correct and faulty processes. 4.5.2 Specification The Uniform Reliable Broadcast protocol ensures that the set of messages delivered by faulty processes is subset or equal to the set of messages de-livered by correct processes. This will result in changing the agreement property of the reliable broadcast , into a uniform agreement property. The uniform reliable broadcast specification guarantees the following properties: • Uniform Agreement : Every message delivered by a process (correct or faulty), will be delivered by all correct processes. • Validity : If a correct process process p broadcasts message m,
{ "page_id": null, "source": 7318, "title": "from dpo" }
this eventually gets delivered by all correct processes in the system. • Integrity : For any message m, every process delivers m at most once, and only if it was previously broadcast. 4.5.3 Algorithm An algorithm to implement the Uniform Reliable Broadcast abstraction needs to ensure that all nodes have received the message before actually 67 delivering the message. By analyzing the algorithm given for the Regular Reliable Broadcast (going back to figure 4.3), it can be noted that the uni-form agreement is not guaranteed because the message is delivered (line 25) before checking whether this needs to be sent to the other nodes (lines 27-27). A naive patch may be to simply move the delivery of the message to be done after checking whether this needs to be sent to the other nodes - ie putting line 25 after line 28. However, this still is not correct as a process may crash before detecting that a sender process has crashed, but after that it delivers a message - possibly violating Uniform Agreement .Another approach may be to always relay the messages immediately and then deliver the message after that all messages have been sent. There is still a subtle problem with such an approach: just because a message is sent, it does not mean that it will get delivered. Referring to section 3.2.3, it was noted that messages might be lost, and eventual delivery could only be guaranteed if the sender does not crash. Hence, in this case, if the deliver event is triggered after sending to all, and then the process crashed, it could be that some other process still does not receive the message broadcast. This would violate the uniform agreement property. In order to solve this problem, a process should only deliver a message, when it
{ "page_id": null, "source": 7318, "title": "from dpo" }
is sure that all other processes received it. Listing 4.5 presents the All-Ack Uniform Reliable Broadcast algorithm which is an implementation of the Uniform Reliable Broadcast protocol. The Al-gorithm ensures that the messages has reached all processes before actually delivering it. This is done by having each process immediately rebroad-cast each message. Moreover, since every process will broadcast the same message, every process also keeps note of the processes from which it has received the message. Whenever a process, determines that it has received the message from all other correct processes, then it can deliver the message - since now the process knows that all other processes have received the message. A basic run of this algorithm is given in figure 4.6. This run consists of three correct processes performing a uniform reliable broadcast . Process P1 starts the broadcast by sending the message to the other participants. When P2 and P3 receive the message, they also broadcast the message to the other processes. In the run given here, process P2 would have received the message from the rest of the processes at point marked A. At this stage, it can deliver 68 Figure 4.5: Uniform Reliable Broadcast algorithm 69 Figure 4.6: A run of the all-ack algorithm for uniform reliable broad-cast the message. Process P3 receives the message from all nodes at point B, and the same happens for process P1 at point A. 4.5.4 Dissecting the Algorithm In the algorithm in figure 4.6 the state contains a Delivered set and a Correct set, whose purpose is the same as in the regular reliable broadcast . It also contains two other data items: Pending and Ack . Pending is a set containing messages which have not yet been received from all processes and hence cannot be delivered. Ack is
{ "page_id": null, "source": 7318, "title": "from dpo" }
a mapping between messages and a set with processes from which that message was received. As hinted earlier, this algorithm delivers a message only when it has been received from all other processes. The can deliver() helper function (lines 15 to 16) checks whether the Correct set is a subset or equal to the set of processes from whom this process have received a particular message. This checksly whether a message has been received from all correct processes. It should be noted that this algorithm requires three distinct structures to hold messages: the Pending and Delivered sets and the Ack map. It is worth analysing whether each of these serves a purpose - yields some information which cannot be inferred from the other structures. The necessity of the Ack map is rather obvious: to determine the processes from which the message has not yet been received. The requirement for two different sets Delivered and Pending , is more subtle to analyze. However, it is important to note that the message will only be delivered when it is received from all process. When the message is received for the first time, it needs to be broadcast to all other processes. The Pending set is used to determine whether the message 70 is being received for the first time or not (line 31). This information can also be acquired from the Ack set. However, the Pending set is also used in the predicate check in line 38, to test whether its elements can be delivered or not. Here, without this set, it would not be possible to determine which are the undelivered message which need to be tested. On the other hand, the Delivered set is used to avoid having a process, deliver the same message more than once. The true necessity
{ "page_id": null, "source": 7318, "title": "from dpo" }
of this set can be seen in histories such as the run shown in figure 4.7. Here P1 starts the broadcast. Process P2 receives this message and rebroadcasts it, however it crashes shortly afterwards. Note that since here a totally asynchronous network is assumed, process P3’s failure detector can determine that process P2 crashed, before actually receiving the message which was previously sent from P2. In fact, at point A in figure 4.7, process P3 delivers the message because it has been received from all correct processes. However, some time after, at point B the message from process P2 is received, and unless the Delivered set exists, it would not be possible to determine that this message has already been delivered. The Delivered set hence, avoids the problem of erroneously redelivering the same message. Figure 4.7: Requirement of the Deliver set 4.5.5 Erlang Implementation The Erlang implementation of this algorithm, uses the same techniques as those presented in the algorithm of the Regular Reliable broadcast specifica-tion. The sets module is used to implement the Delivered and Pending sets. The Ack map is implemented using the Erlang Dict module. Note that in line 23 of listing 4.5, all sets in the Ack map are initialised to empty set. This initialisation is impossible to do in reality as it is impossible to initialize the 71 map for all possible messages. However, in practice, if the entry in the Ack map being accessed is not found, then it is taken as if it contains an empty set. 4.5.5.1 Implementation Optimisations As described in and as hinted earlier, the storage requirements for this algorithm can be greatly reduced. The algorithm given thus far does not eliminate any messages from any of the Ack , Pending or Delivered structures. However, it can be noted
{ "page_id": null, "source": 7318, "title": "from dpo" }
that once a message can be delivered, then it can be removed from the Pending set. Moreover its associated set from the Ack map can also be freed. This tweak will prevent the Pending and Ack sets from growing indefinitely. However, the message cannot be removed from the Delivered set. The ne-cessity of the Delivered set was explained in section 4.5.4. Given that now messages in the Pending and Ack will be removed immediately as all cor-rect processes acknowledge, then identical messages can only be received if a node crashed (one particular scenario is the run in figure 4.7). But problems can be easily prevented if messages are only allowed from correct processes. Hence, when a message is received, first the state of the sender is checked (in the Correct set), and the message will be ”processed” only if it comes from a correct process; otherwise it will be dropped. This would now curb the need to keep a Delivered set, whilst still preventing messages to be delivered multiple times. 4.5.6 Evaluation The algorithm given here meets the Uniform Reliable Broadcast specifica-tion. The integrity and validity properties are satisfied since these are pro-vided by the Best Effort Broadcast . It satisfies the Uniform Agreement prop-erty because every process only delivers the message once it receives it from all correct processes - which means that there cannot be faulty processes which deliver messages which are not delivered by correct processes. In the best case (when there are no failures), the algorithm takes two com-munication steps (one to send to all and one to receive from all), and ex-changes |Π|2 messages. The worst case occurs when all senders crash in sequence, each managing to send the message to just one participant. This 72 would require |Π| + 1 steps. # 4.6 Causal
{ "page_id": null, "source": 7318, "title": "from dpo" }
Order Broadcast In all the broadcast specifications outlined so far, the focus was on the guaranteeing properties within a single broadcast operation and not on its possible interaction with other broadcasts already taking place. In partic-ular, due to the asynchrony of the network, a process could perform two consecutive broadcasts with the receivers delivering the message from the second broadcast before delivering the one preceding it. In certain systems, such reordering may cause inconsistencies and hence must be prevented. The reason is because such a delivery is said to break the causal order of events - the second broadcast, may be an effect of the first one, however the delivery of the messages violate such an ordering. Figure 4.8: An example illustrating violation of causal ordering with regular reliable broadcast Figure 4.8 gives illustrates such a scenario (with regular reliable broadcast )where the causal ordering is broken. Process P1 issues two consecutive reliable broadcasts but process P2 delivers the message of the first broadcast before the first. If say, the two broadcasts are associated with an operation which is non commutative, process P2 will be in a different state than the other two processes. The example illustrated, is just one case of causal ordering. In fact, the causal order relation m1 → m2, indicating that message m1 could have caused the submission of m2 is valid in any of these cases : 1. m1 and m2 were broadcast by the same process with m1 being broad-cast before m2 (refer figure 4.9a) 73 2. m1 was broadcast by process Pi and m2 by process Pj after the delivery of m1 (refer figure 4.9b) 3. ∃m′ such that m1 → m′ and m′ → m2 (refer figure 4.9c) Figure 4.9: Examples of Causal Ordering The causal order broadcast will ensure that the
{ "page_id": null, "source": 7318, "title": "from dpo" }