scalding
ee2d5928a494
Refactor the cascading planning code out of Grouped (#1670)
P. Oscar Boykin
4 days ago
* Refactor the cascading planning code out of Grouped * simplify ReduceStep a bit

50 51 52 53 54 55 56 57 58 59 60 50 51 52 53 54 55 56 57 58 59 60
newK.register(classOf[com.twitter.algebird.Moments], new MomentsSerializer) newK.addDefaultSerializer(classOf[com.twitter.algebird.HLL], new HLLSerializer) // Don't serialize Boxed instances using Kryo. newK.addDefaultSerializer(classOf[com.twitter.scalding.serialization.Boxed[_]], new ThrowingSerializer) newK.addDefaultSerializer(classOf[com.twitter.scalding.typed.TypedPipe[_]], new SerializeAsUnit)
newK.addDefaultSerializer(classOf[com.twitter.scalding.typed.ReduceStep[_, _]], new SerializeAsUnit)
newK.addDefaultSerializer(classOf[com.twitter.scalding.typed.ReduceStep[_, _, _]], new SerializeAsUnit)
/** * AdaptiveVector is IndexedSeq, which picks up the chill IndexedSeq serializer * (which is its own bug), force using the fields serializer here */ newK.register(classOf[com.twitter.algebird.DenseVector[_]],

13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
See the License for the specific language governing permissions and limitations under the License. */ package com.twitter.scalding.typed
import java.io.Serializable
import cascading.flow.FlowDef import cascading.pipe.Pipe import cascading.tuple.{ Fields, Tuple => CTuple }
import com.twitter.algebird.mutable.PriorityQueueMonoid import com.twitter.algebird.Semigroup import com.twitter.scalding.TupleConverter.tuple2Converter import com.twitter.scalding.TupleSetter.tup2Setter
import com.twitter.scalding._ import com.twitter.scalding.serialization.{ Boxed, BoxedOrderedSerialization, CascadingBinaryComparator, EquivSerialization, OrderedSerialization, WrappedSerialization }
import cascading.flow.FlowDef import cascading.pipe.Pipe import cascading.property.ConfigDef import cascading.tuple.{ Fields, Tuple => CTuple } import java.util.Comparator
import java.io.Serializable
import scala.collection.JavaConverters._
import scala.util.Try import scala.collection.immutable.Queue
import Dsl._ /** * This encodes the rules that
...
50 51 52 53 54 55 56 57 58 59 60 43 44 45 46 47 48 49 50 51 52 53
* 3) unsorted Groups can be CoGrouped or HashJoined * * This may appear a complex type, but it makes * sure that code won't compile if it breaks the rule */
trait Grouped[K, +V]
sealed trait Grouped[K, +V]
extends KeyedListLike[K, V, UnsortedGrouped] with HashJoinable[K, V] with Sortable[V, ({ type t[+x] = SortedGrouped[K, x] with Reversable[SortedGrouped[K, x]] })#t] with WithReducers[Grouped[K, V]] with WithDescription[Grouped[K, V]]
...
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
* .sortBy(_._2).reverse * for instance * * Once we have sorted, we cannot do a HashJoin or a CoGrouping */
trait SortedGrouped[K, +V]
sealed trait SortedGrouped[K, +V]
extends KeyedListLike[K, V, SortedGrouped] with WithReducers[SortedGrouped[K, V]] with WithDescription[SortedGrouped[K, V]] /** * This is the state after we have done some reducing. It is * not possible to sort at this phase, but it is possible to * do a CoGrouping or a HashJoin. */
trait UnsortedGrouped[K, +V]
sealed trait UnsortedGrouped[K, +V]
extends KeyedListLike[K, V, UnsortedGrouped] with HashJoinable[K, V] with WithReducers[UnsortedGrouped[K, V]] with WithDescription[UnsortedGrouped[K, V]]
...
111 112 113 114 115 116 117 118 119 120 104 105 106 107 108 109 110 111 112 113 114
} }) (boxfn, boxordSer) }
// TODO move this to CascadingBackend when we refactor joins
private[scalding] def maybeBox[K, V](ord: Ordering[K], flowDef: FlowDef)(op: (TupleSetter[(K, V)], Fields) => Pipe): Pipe = ord match { case ordser: OrderedSerialization[K] => val (boxfn, boxordSer) = getBoxFnAndOrder[K](ordser, flowDef)
...
167 168 169 170 171 172 173 174 175 176 177 161 162 163 164 165 166 167 168 169 170 171
/** * All sorting methods defined here trigger Hadoop secondary sort on key + value. * Hadoop secondary sort is external sorting. i.e. it won't materialize all values * of each key in memory on the reducer. */
trait Sortable[+T, +Sorted[+_]] {
sealed trait Sortable[+T, +Sorted[+_]] {
def withSortOrdering[U >: T](so: Ordering[U]): Sorted[T] def sortBy[B: Ordering](fn: (T) => B): Sorted[T] = withSortOrdering(Ordering.by(fn))
...
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
def sortWith(lt: (T, T) => Boolean): Sorted[T] = withSortOrdering(Ordering.fromLessThan(lt)) } // Represents something that when we call reverse changes type to R
trait Reversable[+R] {
sealed trait Reversable[+R] {
def reverse: R } /** * This is a class that models the logical portion of the reduce step. * details like where this occurs, the number of reducers, etc... are * left in the Grouped class */
sealed trait ReduceStep[K, V1] extends KeyedPipe[K] {
sealed trait ReduceStep[K, V1, V2] extends KeyedPipe[K] {
/** * Note, this satisfies KeyedPipe.mapped: TypedPipe[(K, Any)] */ def mapped: TypedPipe[(K, V1)]
// make the pipe and group it, only here because it is common protected def groupOp[V2](gb: GroupBuilder => GroupBuilder): TypedPipe[(K, V2)] = groupOpWithValueSort[V2](None)(gb)
protected def groupOpWithValueSort[V2](valueSort: Option[Ordering[_ >: V1]])(gb: GroupBuilder => GroupBuilder): TypedPipe[(K, V2)] = TypedPipe.ReduceStepPipe[K, V1, V2](this, valueSort, gb)
def toTypedPipe: TypedPipe[(K, V2)] = TypedPipe.ReduceStepPipe(this)
} case class IdentityReduce[K, V1]( override val keyOrdering: Ordering[K], override val mapped: TypedPipe[(K, V1)], override val reducers: Option[Int], override val descriptions: Seq[String])
extends ReduceStep[K, V1]
extends ReduceStep[K, V1, V1]
with Grouped[K, V1] { /* * Because after mapValues, take, filter, we can no-longer sort, * we commonly convert to UnsortedIdentityReduce first, then
...
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
// there is no sort, mapValueStream or force to reducers: val upipe: TypedPipe[(K, U)] = mapped // use covariance to set the type UnsortedIdentityReduce(keyOrdering, upipe.sumByLocalKeys, reducers, descriptions).sumLeft }
override lazy val toTypedPipe = reducers match { case None => mapped // free case case Some(reds) => // This is weird, but it is sometimes used to force a partition groupOp { _.reducers(reds).setDescriptions(descriptions) } }
/** This is just an identity that casts the result to V1 */ override def joinFunction = CoGroupable.castingJoinFunction[V1] } case class UnsortedIdentityReduce[K, V1]( override val keyOrdering: Ordering[K], override val mapped: TypedPipe[(K, V1)], override val reducers: Option[Int], override val descriptions: Seq[String])
extends ReduceStep[K, V1]
extends ReduceStep[K, V1, V1]
with UnsortedGrouped[K, V1] { /** * This does the partial heap sort followed by take in memory on the mappers * before sending to the reducers. This is a big help if there are relatively
...
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
// there is no sort, mapValueStream or force to reducers: val upipe: TypedPipe[(K, U)] = mapped // use covariance to set the type UnsortedIdentityReduce(keyOrdering, upipe.sumByLocalKeys, reducers, descriptions).sumLeft }
override lazy val toTypedPipe = reducers match { case None => mapped // free case case Some(reds) => // This is weird, but it is sometimes used to force a partition groupOp { _.reducers(reds).setDescriptions(descriptions) } }
/** This is just an identity that casts the result to V1 */ override def joinFunction = CoGroupable.castingJoinFunction[V1] } case class IdentityValueSortedReduce[K, V1]( override val keyOrdering: Ordering[K], override val mapped: TypedPipe[(K, V1)], valueSort: Ordering[_ >: V1], override val reducers: Option[Int],
override val descriptions: Seq[String]) extends ReduceStep[K, V1]
override val descriptions: Seq[String]) extends ReduceStep[K, V1, V1]
with SortedGrouped[K, V1] with Reversable[IdentityValueSortedReduce[K, V1]] { override def reverse: IdentityValueSortedReduce[K, V1] = IdentityValueSortedReduce[K, V1](keyOrdering, mapped, valueSort.reverse, reducers, descriptions)
...
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
* Otherwise, we send all the values to the reducers */ override def take(n: Int) = if (n <= 1) bufferedTake(n) else mapValueStream(_.take(n))
override lazy val toTypedPipe = groupOpWithValueSort[V1](valueSort = Some(valueSort)) { gb => // If its an ordered serialization we need to unbox val mappedGB = if (valueSort.isInstanceOf[OrderedSerialization[_]]) gb.mapStream[Boxed[V1], V1](Grouped.valueField -> Grouped.valueField) { it: Iterator[Boxed[V1]] => it.map(_.get) } else gb mappedGB .reducers(reducers.getOrElse(-1)) .setDescriptions(descriptions) }
} case class ValueSortedReduce[K, V1, V2]( override val keyOrdering: Ordering[K], override val mapped: TypedPipe[(K, V1)], valueSort: Ordering[_ >: V1], reduceFn: (K, Iterator[V1]) => Iterator[V2], override val reducers: Option[Int], override val descriptions: Seq[String])
extends ReduceStep[K, V1] with SortedGrouped[K, V2] {
extends ReduceStep[K, V1, V2] with SortedGrouped[K, V2] {
/** * After sorting, then reducing, there is no chance * to operate in the mappers. Just call take. */
...
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
Grouped.addEmptyGuard(fn)(k, step1) } ValueSortedReduce[K, V1, V3]( keyOrdering, mapped, valueSort, newReduce, reducers, descriptions) }
override lazy val toTypedPipe = { val optVOrdering = Some(valueSort) groupOpWithValueSort(optVOrdering) { // If its an ordered serialization we need to unbox // the value before handing it to the users operation _.every(new cascading.pipe.Every(_, Grouped.valueField, new TypedBufferOp[K, V1, V2](Grouped.keyConverter(keyOrdering), Grouped.valueConverter(optVOrdering), reduceFn, Grouped.valueField), Fields.REPLACE)) .reducers(reducers.getOrElse(-1)) .setDescriptions(descriptions) } }
} case class IteratorMappedReduce[K, V1, V2]( override val keyOrdering: Ordering[K], override val mapped: TypedPipe[(K, V1)], reduceFn: (K, Iterator[V1]) => Iterator[V2], override val reducers: Option[Int], override val descriptions: Seq[String])
extends ReduceStep[K, V1] with UnsortedGrouped[K, V2] {
extends ReduceStep[K, V1, V2] with UnsortedGrouped[K, V2] {
/** * After reducing, we are always * operating in memory. Just call take. */
...
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 453 454 455 456 457 458 459 460 461 462
// Only pass non-Empty iterators to subsequent functions Grouped.addEmptyGuard(fn)(k, step1) } copy(reduceFn = newReduce) }
override lazy val toTypedPipe = groupOp { _.every(new cascading.pipe.Every(_, Grouped.valueField, new TypedBufferOp(Grouped.keyConverter(keyOrdering), TupleConverter.singleConverter[V1], reduceFn, Grouped.valueField), Fields.REPLACE)) .reducers(reducers.getOrElse(-1)) .setDescriptions(descriptions) }
override def joinFunction = { // don't make a closure val localRed = reduceFn; { (k, iter, empties) =>

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 153 154 155 156 157 158 159 160 161 162 163
case class HashCoGroup[K, V, W, R](left: TypedPipe[(K, V)], right: HashJoinable[K, W], joiner: (K, V, Iterable[W]) => Iterator[R]) extends TypedPipe[(K, R)] case class CoGroupedPipe[K, V](cogrouped: CoGrouped[K, V]) extends TypedPipe[(K, V)]
// TODO: ReduceStepPipe is still tightly bound to cascading case class ReduceStepPipe[K, V1, V2]( reduce: ReduceStep[K, V1], valueOrd: Option[Ordering[_ >: V1]], op: GroupBuilder => GroupBuilder) extends TypedPipe[(K, V2)]
case class ReduceStepPipe[K, V1, V2](reduce: ReduceStep[K, V1, V2]) extends TypedPipe[(K, V2)]
} /** * Think of a TypedPipe as a distributed unordered list that may or may not yet * have been materialized in memory or disk.

3 4 5 6 7 8 9 10 11 12 13 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import cascading.flow.FlowDef import cascading.pipe.{ Each, Pipe } import cascading.tuple.{ Fields, TupleEntry } import com.twitter.scalding.TupleConverter.{ singleConverter, tuple2Converter } import com.twitter.scalding.TupleSetter.{ singleSetter, tup2Setter }
import com.twitter.scalding.{ CleanupIdentityFunction, Dsl, LineNumber, IterableSource, MapsideReduce, Mode, RichPipe, TupleConverter, TupleSetter, Write }
import com.twitter.scalding.{ CleanupIdentityFunction, Dsl, GroupBuilder, LineNumber, IterableSource, MapsideReduce, Mode, RichPipe, TupleConverter, TupleSetter, TypedBufferOp, Write }
import com.twitter.scalding.typed._ import com.twitter.scalding.serialization.{ CascadingBinaryComparator, OrderedSerialization, Boxed } import scala.collection.mutable.{ Map => MMap } import java.util.WeakHashMap
...
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
} loop(cp, rest, descriptions) } go(cgp)
case r@ReduceStepPipe(_, _, _) => def go[K, V1, V2](rsp: ReduceStepPipe[K, V1, V2]): Pipe = { // TODO we can push up filterKeys on both the left and right // and mapValues/flatMapValues on the result def pipe(flowDef: FlowDef) = Grouped.maybeBox[K, V1](rsp.reduce.keyOrdering, flowDef) { (tupleSetter, fields) => val (sortOpt, ts) = rsp.valueOrd.map { case ordser: OrderedSerialization[V1] => // We get in here when we do a secondary sort // and that sort is an ordered serialization // We now need a boxed serializer for this type // Then we set the comparator on the field, and finally we box the value with our tupleSetter val (boxfn, boxordSer) = Grouped.getBoxFnAndOrder[V1](ordser, flowDef) val valueF = new Fields("value") valueF.setComparator("value", new CascadingBinaryComparator(boxordSer)) val ts2 = tupleSetter.asInstanceOf[TupleSetter[(K, Boxed[V1])]].contraMap { kv1: (K, V1) => (kv1._1, boxfn(kv1._2)) } (Some(valueF), ts2) case vs => (Some(Grouped.valueSorting(vs)), tupleSetter) }.getOrElse((None, tupleSetter)) val p = rsp.reduce.mapped.toPipe(Grouped.kvFields)(flowDef, mode, TupleSetter.asSubSetter(ts)) RichPipe(p).groupBy(fields) { inGb => val withSort = sortOpt.fold(inGb)(inGb.sortBy) rsp.op(withSort) } } val cp = cacheGet(rsp, mode) { implicit fd => val tupConv = Grouped.tuple2Conv[K, V2](rsp.reduce.keyOrdering) CascadingPipe(pipe(fd), kvfields, fd, mode, tupConv) } loop(cp, rest, descriptions) } go(r)
case r@ReduceStepPipe(_) => loop(planReduceStep(r, mode), rest, descriptions)
} RichPipe(loop(p, FlatMappedFn.identity[U], Nil)).applyFlowConfigProperties(flowDef) }
private def planReduceStep[K, V1, V2](rsp: ReduceStepPipe[K, V1, V2], mode: Mode): TypedPipe[(K, V2)] = { val rs = rsp.reduce def groupOp(gb: GroupBuilder => GroupBuilder): TypedPipe[(K, V2)] = groupOpWithValueSort(None)(gb) def groupOpWithValueSort(valueSort: Option[Ordering[_ >: V1]])(gb: GroupBuilder => GroupBuilder): TypedPipe[(K, V2)] = { def pipe(flowDef: FlowDef) = Grouped.maybeBox[K, V1](rs.keyOrdering, flowDef) { (tupleSetter, fields) => val (sortOpt, ts) = valueSort.map { case ordser: OrderedSerialization[V1] => // We get in here when we do a secondary sort // and that sort is an ordered serialization // We now need a boxed serializer for this type // Then we set the comparator on the field, and finally we box the value with our tupleSetter val (boxfn, boxordSer) = Grouped.getBoxFnAndOrder[V1](ordser, flowDef) val valueF = new Fields("value") valueF.setComparator("value", new CascadingBinaryComparator(boxordSer)) val ts2 = tupleSetter.asInstanceOf[TupleSetter[(K, Boxed[V1])]].contraMap { kv1: (K, V1) => (kv1._1, boxfn(kv1._2)) } (Some(valueF), ts2) case vs => (Some(Grouped.valueSorting(vs)), tupleSetter) }.getOrElse((None, tupleSetter)) val p = rs.mapped.toPipe(Grouped.kvFields)(flowDef, mode, TupleSetter.asSubSetter(ts)) RichPipe(p).groupBy(fields) { inGb => val withSort = sortOpt.fold(inGb)(inGb.sortBy) gb(withSort) } } pipeCache.cacheGet(rsp, mode) { implicit fd => val tupConv = Grouped.tuple2Conv[K, V2](rs.keyOrdering) CascadingPipe(pipe(fd), Grouped.kvFields, fd, mode, tupConv) } } rs match { case IdentityReduce(_, inp, None, descriptions) => // Not doing anything descriptions.foldLeft(inp)(_.withDescription(_)) case IdentityReduce(_, _, Some(reds), descriptions) => groupOp { _.reducers(reds).setDescriptions(descriptions) } case UnsortedIdentityReduce(_, inp, None, descriptions) => // Not doing anything descriptions.foldLeft(inp)(_.withDescription(_)) case UnsortedIdentityReduce(_, _, Some(reds), descriptions) => // This is weird, but it is sometimes used to force a partition groupOp { _.reducers(reds).setDescriptions(descriptions) } case ivsr@IdentityValueSortedReduce(_, _, _, _, _) => // in this case we know that V1 =:= V2 groupOpWithValueSort(Some(ivsr.valueSort.asInstanceOf[Ordering[_ >: V1]])) { gb => // If its an ordered serialization we need to unbox val mappedGB = if (ivsr.valueSort.isInstanceOf[OrderedSerialization[_]]) gb.mapStream[Boxed[V1], V1](Grouped.valueField -> Grouped.valueField) { it: Iterator[Boxed[V1]] => it.map(_.get) } else gb mappedGB .reducers(ivsr.reducers.getOrElse(-1)) .setDescriptions(ivsr.descriptions) } case vsr@ValueSortedReduce(_, _, _, _, _, _) => val optVOrdering = Some(vsr.valueSort) groupOpWithValueSort(optVOrdering) { // If its an ordered serialization we need to unbox // the value before handing it to the users operation _.every(new cascading.pipe.Every(_, Grouped.valueField, new TypedBufferOp[K, V1, V2](Grouped.keyConverter(vsr.keyOrdering), Grouped.valueConverter(optVOrdering), vsr.reduceFn, Grouped.valueField), Fields.REPLACE)) .reducers(vsr.reducers.getOrElse(-1)) .setDescriptions(vsr.descriptions) } case imr@IteratorMappedReduce(_, _, _, _, _) => groupOp { _.every(new cascading.pipe.Every(_, Grouped.valueField, new TypedBufferOp(Grouped.keyConverter(imr.keyOrdering), TupleConverter.singleConverter[V1], imr.reduceFn, Grouped.valueField), Fields.REPLACE)) .reducers(imr.reducers.getOrElse(-1)) .setDescriptions(imr.descriptions) } } }
}
About FluentSend Feedback