You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@samza.apache.org by xi...@apache.org on 2017/06/07 19:42:22 UTC

[4/4] samza git commit: SAMZA-1221, SAMZA-1101: Internal cleanup for High-Level API implementation.

SAMZA-1221, SAMZA-1101: Internal cleanup for High-Level API implementation.

SAMZA-1221: Separated the OperatorSpec and MessageStream DAGs so that they're now duals of each other. Users interact with and construct the MessageStream DAG; we create and use the OperatorSpec DAG internally.
Moved common OperatorSpec functionality (getId, getOpCode, getOpName etc.) to the OperatorSpec abstract base class.
Added a new JoinOperatorSpec and PartialJoinOperatorImpls which are created from JoinOperatorSpec in OperatorGraphImpl.
Added a new InputOperatorSpec and InputOperatorImpl (previously RootOperatorImpl). InputOperatorSpec is created when StreamGraph#getInputStream is called.
SAMZA-1101: Added a new OutputOperatorSpec and OutputOperatorImpl for partitionBy and sendTo. These are Separate from SinkOperatorSpec for and SinkOperatorImpl for sink. We don't need to create a sinkFn for partitionBy and sendTo anymore.
Updated most unit tests to use the new classes and avoid reflection.

Author: Prateek Maheshwari <pm...@linkedin.com>

Reviewers: Jagadish V <vj...@apache.org>

Closes #194 from prateekm/internal-cleanup


Project: http://git-wip-us.apache.org/repos/asf/samza/repo
Commit: http://git-wip-us.apache.org/repos/asf/samza/commit/c1c4289c
Tree: http://git-wip-us.apache.org/repos/asf/samza/tree/c1c4289c
Diff: http://git-wip-us.apache.org/repos/asf/samza/diff/c1c4289c

Branch: refs/heads/master
Commit: c1c4289c8586457ae35c01f1ccb28fa59697dcb1
Parents: 29cf374
Author: Prateek Maheshwari <pm...@linkedin.com>
Authored: Wed Jun 7 12:42:11 2017 -0700
Committer: Xinyu Liu <xi...@xiliu-ld.linkedin.biz>
Committed: Wed Jun 7 12:42:11 2017 -0700

----------------------------------------------------------------------
 .gitignore                                      |   1 +
 .../samza/execution/ExecutionPlanner.java       |  67 +--
 .../samza/execution/JobGraphJsonGenerator.java  |  83 +--
 .../org/apache/samza/execution/JobNode.java     |   4 +-
 .../samza/operators/MessageStreamImpl.java      | 190 ++-----
 .../apache/samza/operators/StreamGraphImpl.java |  88 ++--
 .../org/apache/samza/operators/WindowState.java |  49 --
 .../samza/operators/impl/InputOperatorImpl.java |  66 +++
 .../samza/operators/impl/OperatorImpl.java      |  27 +-
 .../samza/operators/impl/OperatorImplGraph.java | 242 +++++----
 .../operators/impl/OutputOperatorImpl.java      |  72 +++
 .../operators/impl/PartialJoinOperatorImpl.java |  50 +-
 .../samza/operators/impl/RootOperatorImpl.java  |  76 ---
 .../samza/operators/impl/SinkOperatorImpl.java  |   9 +-
 .../operators/impl/StreamOperatorImpl.java      |   9 +-
 .../operators/impl/WindowOperatorImpl.java      |   3 +-
 .../samza/operators/impl/WindowState.java       |  49 ++
 .../samza/operators/spec/InputOperatorSpec.java |  52 ++
 .../samza/operators/spec/JoinOperatorSpec.java  |  73 +++
 .../samza/operators/spec/OperatorSpec.java      |  72 ++-
 .../samza/operators/spec/OperatorSpecs.java     |  89 ++--
 .../operators/spec/OutputOperatorSpec.java      |  55 ++
 .../samza/operators/spec/OutputStreamImpl.java  |  50 ++
 .../operators/spec/PartialJoinOperatorSpec.java |  97 ----
 .../samza/operators/spec/SinkOperatorSpec.java  |  85 +--
 .../operators/spec/StreamOperatorSpec.java      |  43 +-
 .../operators/spec/WindowOperatorSpec.java      |  36 +-
 .../operators/stream/InputStreamInternal.java   |  39 --
 .../stream/InputStreamInternalImpl.java         |  45 --
 .../stream/IntermediateMessageStreamImpl.java   |  58 +++
 .../stream/IntermediateStreamInternalImpl.java  |  61 ---
 .../operators/stream/OutputStreamInternal.java  |  43 --
 .../stream/OutputStreamInternalImpl.java        |  52 --
 .../samza/operators/util/OperatorJsonUtils.java |  89 ----
 .../apache/samza/task/StreamOperatorTask.java   |  42 +-
 .../samza/execution/TestExecutionPlanner.java   |  10 +-
 .../execution/TestJobGraphJsonGenerator.java    |  37 +-
 .../samza/operators/TestJoinOperator.java       |   6 +-
 .../samza/operators/TestMessageStreamImpl.java  | 522 ++++++++++---------
 .../operators/TestMessageStreamImplUtil.java    |  26 -
 .../samza/operators/TestStreamGraphImpl.java    | 243 ++++-----
 .../samza/operators/data/MessageType.java       |  37 --
 .../data/TestExtOutputMessageEnvelope.java      |  29 --
 .../data/TestInputMessageEnvelope.java          |  32 --
 .../operators/data/TestMessageEnvelope.java     |  10 +-
 .../samza/operators/impl/TestOperatorImpl.java  |  30 +-
 .../operators/impl/TestOperatorImplGraph.java   | 200 +++++--
 .../samza/operators/impl/TestOperatorImpls.java | 236 ---------
 .../operators/impl/TestStreamOperatorImpl.java  |  11 +-
 .../samza/operators/spec/TestOperatorSpecs.java | 192 -------
 .../operators/spec/TestWindowOperatorSpec.java  |   8 +-
 .../src/main/visualizer/js/planToDagre.js       |  12 +-
 52 files changed, 1576 insertions(+), 2231 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/samza/blob/c1c4289c/.gitignore
----------------------------------------------------------------------
diff --git a/.gitignore b/.gitignore
index a8de1b5..d4dcaa1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -28,3 +28,4 @@ docs/learn/documentation/*/rest/javadocs
 out/
 *.patch
 **.pyc
+samza-shell/src/main/visualizer/plan.json

http://git-wip-us.apache.org/repos/asf/samza/blob/c1c4289c/samza-core/src/main/java/org/apache/samza/execution/ExecutionPlanner.java
----------------------------------------------------------------------
diff --git a/samza-core/src/main/java/org/apache/samza/execution/ExecutionPlanner.java b/samza-core/src/main/java/org/apache/samza/execution/ExecutionPlanner.java
index d763d84..00f4ad4 100644
--- a/samza-core/src/main/java/org/apache/samza/execution/ExecutionPlanner.java
+++ b/samza-core/src/main/java/org/apache/samza/execution/ExecutionPlanner.java
@@ -31,11 +31,9 @@ import java.util.Set;
 import org.apache.samza.SamzaException;
 import org.apache.samza.config.Config;
 import org.apache.samza.config.JobConfig;
-import org.apache.samza.operators.MessageStream;
-import org.apache.samza.operators.MessageStreamImpl;
 import org.apache.samza.operators.StreamGraphImpl;
+import org.apache.samza.operators.spec.JoinOperatorSpec;
 import org.apache.samza.operators.spec.OperatorSpec;
-import org.apache.samza.operators.spec.PartialJoinOperatorSpec;
 import org.apache.samza.system.StreamSpec;
 import org.apache.samza.system.SystemStream;
 import org.slf4j.Logger;
@@ -77,7 +75,7 @@ public class ExecutionPlanner {
    */
   /* package private */ JobGraph createJobGraph(StreamGraphImpl streamGraph) {
     JobGraph jobGraph = new JobGraph(config);
-    Set<StreamSpec> sourceStreams = new HashSet<>(streamGraph.getInputStreams().keySet());
+    Set<StreamSpec> sourceStreams = new HashSet<>(streamGraph.getInputOperators().keySet());
     Set<StreamSpec> sinkStreams = new HashSet<>(streamGraph.getOutputStreams().keySet());
     Set<StreamSpec> intStreams = new HashSet<>(sourceStreams);
     intStreams.retainAll(sinkStreams);
@@ -120,7 +118,7 @@ public class ExecutionPlanner {
   /**
    * Fetch the partitions of source/sink streams and update the StreamEdges.
    * @param jobGraph {@link JobGraph}
-   * @param streamManager the {@StreamManager} to interface with the streams.
+   * @param streamManager the {@link StreamManager} to interface with the streams.
    */
   /* package private */ static void updateExistingPartitions(JobGraph jobGraph, StreamManager streamManager) {
     Set<StreamEdge> existingStreams = new HashSet<>();
@@ -157,20 +155,16 @@ public class ExecutionPlanner {
     Multimap<OperatorSpec, StreamEdge> joinSpecToStreamEdges = HashMultimap.create();
     // reverse mapping of the above
     Multimap<StreamEdge, OperatorSpec> streamEdgeToJoinSpecs = HashMultimap.create();
-    // Mapping from the output stream to the join spec. Since StreamGraph creates two partial join operators for a join and they
-    // will have the same output stream, this mapping is used to choose one of them as the unique join spec representing this join
-    // (who register first in the map wins).
-    Map<MessageStream, OperatorSpec> outputStreamToJoinSpec = new HashMap<>();
     // A queue of joins with known input partitions
     Queue<OperatorSpec> joinQ = new LinkedList<>();
     // The visited set keeps track of the join specs that have been already inserted in the queue before
     Set<OperatorSpec> visited = new HashSet<>();
 
-    streamGraph.getInputStreams().entrySet().forEach(entry -> {
+    streamGraph.getInputOperators().entrySet().forEach(entry -> {
         StreamEdge streamEdge = jobGraph.getOrCreateStreamEdge(entry.getKey());
         // Traverses the StreamGraph to find and update mappings for all Joins reachable from this input StreamEdge
         findReachableJoins(entry.getValue(), streamEdge, joinSpecToStreamEdges, streamEdgeToJoinSpecs,
-            outputStreamToJoinSpec, joinQ, visited);
+            joinQ, visited);
       });
 
     // At this point, joinQ contains joinSpecs where at least one of the input stream edge partitions is known.
@@ -209,44 +203,33 @@ public class ExecutionPlanner {
   }
 
   /**
-   * This function traverses the StreamGraph to find and update mappings for all Joins reachable from this input StreamEdge
-   * @param inputMessageStream next input MessageStream to traverse {@link MessageStream}
+   * This function traverses the {@link OperatorSpec} graph to find and update mappings for all Joins reachable
+   * from this input {@link StreamEdge}.
+   * @param operatorSpec the {@link OperatorSpec} to traverse
    * @param sourceStreamEdge source {@link StreamEdge}
    * @param joinSpecToStreamEdges mapping from join spec to its source {@link StreamEdge}s
    * @param streamEdgeToJoinSpecs mapping from source {@link StreamEdge} to the join specs that consumes it
-   * @param outputStreamToJoinSpec mapping from the output stream to the join spec
    * @param joinQ queue that contains joinSpecs where at least one of the input stream edge partitions is known.
    */
-  private static void findReachableJoins(MessageStream inputMessageStream, StreamEdge sourceStreamEdge,
-      Multimap<OperatorSpec, StreamEdge> joinSpecToStreamEdges, Multimap<StreamEdge, OperatorSpec> streamEdgeToJoinSpecs,
-      Map<MessageStream, OperatorSpec> outputStreamToJoinSpec, Queue<OperatorSpec> joinQ, Set<OperatorSpec> visited) {
-    Collection<OperatorSpec> specs = ((MessageStreamImpl) inputMessageStream).getRegisteredOperatorSpecs();
-    for (OperatorSpec spec : specs) {
-      if (spec instanceof PartialJoinOperatorSpec) {
-        // every join will have two partial join operators
-        // we will choose one of them in order to consolidate the inputs
-        // the first one who registered with the outputStreamToJoinSpec will win
-        MessageStream output = spec.getNextStream();
-        OperatorSpec joinSpec = outputStreamToJoinSpec.get(output);
-        if (joinSpec == null) {
-          joinSpec = spec;
-          outputStreamToJoinSpec.put(output, joinSpec);
-        }
-
-        joinSpecToStreamEdges.put(joinSpec, sourceStreamEdge);
-        streamEdgeToJoinSpecs.put(sourceStreamEdge, joinSpec);
-
-        if (!visited.contains(joinSpec) && sourceStreamEdge.getPartitionCount() > 0) {
-          // put the joins with known input partitions into the queue
-          joinQ.add(joinSpec);
-          visited.add(joinSpec);
-        }
+  private static void findReachableJoins(OperatorSpec operatorSpec, StreamEdge sourceStreamEdge,
+      Multimap<OperatorSpec, StreamEdge> joinSpecToStreamEdges,
+      Multimap<StreamEdge, OperatorSpec> streamEdgeToJoinSpecs,
+      Queue<OperatorSpec> joinQ, Set<OperatorSpec> visited) {
+    if (operatorSpec instanceof JoinOperatorSpec) {
+      joinSpecToStreamEdges.put(operatorSpec, sourceStreamEdge);
+      streamEdgeToJoinSpecs.put(sourceStreamEdge, operatorSpec);
+
+      if (!visited.contains(operatorSpec) && sourceStreamEdge.getPartitionCount() > 0) {
+        // put the joins with known input partitions into the queue and mark as visited
+        joinQ.add(operatorSpec);
+        visited.add(operatorSpec);
       }
+    }
 
-      if (spec.getNextStream() != null) {
-        findReachableJoins(spec.getNextStream(), sourceStreamEdge, joinSpecToStreamEdges, streamEdgeToJoinSpecs, outputStreamToJoinSpec, joinQ,
-            visited);
-      }
+    Collection<OperatorSpec> registeredOperatorSpecs = operatorSpec.getRegisteredOperatorSpecs();
+    for (OperatorSpec registeredOpSpec : registeredOperatorSpecs) {
+      findReachableJoins(registeredOpSpec, sourceStreamEdge, joinSpecToStreamEdges, streamEdgeToJoinSpecs, joinQ,
+          visited);
     }
   }
 

http://git-wip-us.apache.org/repos/asf/samza/blob/c1c4289c/samza-core/src/main/java/org/apache/samza/execution/JobGraphJsonGenerator.java
----------------------------------------------------------------------
diff --git a/samza-core/src/main/java/org/apache/samza/execution/JobGraphJsonGenerator.java b/samza-core/src/main/java/org/apache/samza/execution/JobGraphJsonGenerator.java
index 96c0538..23c9d89 100644
--- a/samza-core/src/main/java/org/apache/samza/execution/JobGraphJsonGenerator.java
+++ b/samza-core/src/main/java/org/apache/samza/execution/JobGraphJsonGenerator.java
@@ -19,13 +19,9 @@
 
 package org.apache.samza.execution;
 
-import com.google.common.base.Joiner;
-import com.google.common.collect.HashMultimap;
-import com.google.common.collect.Multimap;
 import java.io.ByteArrayOutputStream;
 import java.util.ArrayList;
 import java.util.Collection;
-import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
@@ -33,10 +29,11 @@ import java.util.Map;
 import java.util.Set;
 import java.util.stream.Collectors;
 import org.apache.samza.config.ApplicationConfig;
-import org.apache.samza.operators.MessageStream;
-import org.apache.samza.operators.MessageStreamImpl;
+import org.apache.samza.operators.spec.JoinOperatorSpec;
 import org.apache.samza.operators.spec.OperatorSpec;
-import org.apache.samza.operators.util.OperatorJsonUtils;
+import org.apache.samza.operators.spec.OperatorSpec.OpCode;
+import org.apache.samza.operators.spec.OutputOperatorSpec;
+import org.apache.samza.operators.spec.OutputStreamImpl;
 import org.codehaus.jackson.annotate.JsonProperty;
 import org.codehaus.jackson.map.ObjectMapper;
 
@@ -73,8 +70,6 @@ import org.codehaus.jackson.map.ObjectMapper;
     List<StreamJson> outputStreams;
     @JsonProperty("operators")
     Map<Integer, Map<String, Object>> operators = new HashMap<>();
-    @JsonProperty("canonicalOpIds")
-    Map<Integer, String> canonicalOpIds = new HashMap<>();
   }
 
   static final class StreamJson {
@@ -108,11 +103,6 @@ import org.codehaus.jackson.map.ObjectMapper;
     String applicationId;
   }
 
-  // Mapping from the output stream to the ids.
-  // Logically they belong to the same operator, but in code we generate one operator for each input.
-  // This is to associate the operators that output to the same MessageStream.
-  Multimap<MessageStream, Integer> outputStreamToOpIds = HashMultimap.create();
-
   /**
    * Returns the JSON representation of a {@link JobGraph}
    * @param jobGraph {@link JobGraph}
@@ -157,28 +147,21 @@ import org.codehaus.jackson.map.ObjectMapper;
   }
 
   /**
-   * Traverse the {@StreamGraph} and build the operator graph JSON POJO.
+   * Traverse the {@link OperatorSpec} graph and build the operator graph JSON POJO.
    * @param jobNode job node in the {@link JobGraph}
    * @return {@link org.apache.samza.execution.JobGraphJsonGenerator.OperatorGraphJson}
    */
   private OperatorGraphJson buildOperatorGraphJson(JobNode jobNode) {
     OperatorGraphJson opGraph = new OperatorGraphJson();
     opGraph.inputStreams = new ArrayList<>();
-    jobNode.getStreamGraph().getInputStreams().forEach((streamSpec, stream) -> {
+    jobNode.getStreamGraph().getInputOperators().forEach((streamSpec, operatorSpec) -> {
         StreamJson inputJson = new StreamJson();
         opGraph.inputStreams.add(inputJson);
         inputJson.streamId = streamSpec.getId();
-        Collection<OperatorSpec> specs = ((MessageStreamImpl) stream).getRegisteredOperatorSpecs();
+        Collection<OperatorSpec> specs = operatorSpec.getRegisteredOperatorSpecs();
         inputJson.nextOperatorIds = specs.stream().map(OperatorSpec::getOpId).collect(Collectors.toSet());
 
-        updateOperatorGraphJson((MessageStreamImpl) stream, opGraph);
-
-        for (Map.Entry<MessageStream, Collection<Integer>> entry : outputStreamToOpIds.asMap().entrySet()) {
-          List<Integer> sortedIds = new ArrayList<>(entry.getValue());
-          Collections.sort(sortedIds);
-          String canonicalId = Joiner.on(',').join(sortedIds);
-          sortedIds.stream().forEach(id -> opGraph.canonicalOpIds.put(id, canonicalId));
-        }
+        updateOperatorGraphJson(operatorSpec, opGraph);
       });
 
     opGraph.outputStreams = new ArrayList<>();
@@ -191,23 +174,43 @@ import org.codehaus.jackson.map.ObjectMapper;
   }
 
   /**
-   * Traverse the {@StreamGraph} recursively and update the operator graph JSON POJO.
-   * @param messageStream input
+   * Traverse the {@link OperatorSpec} graph recursively and update the operator graph JSON POJO.
+   * @param operatorSpec input
    * @param opGraph operator graph to build
    */
-  private void updateOperatorGraphJson(MessageStreamImpl messageStream, OperatorGraphJson opGraph) {
-    Collection<OperatorSpec> specs = messageStream.getRegisteredOperatorSpecs();
-    specs.forEach(opSpec -> {
-        opGraph.operators.put(opSpec.getOpId(), OperatorJsonUtils.operatorToMap(opSpec));
-
-        if (opSpec.getOpCode() == OperatorSpec.OpCode.JOIN || opSpec.getOpCode() == OperatorSpec.OpCode.MERGE) {
-          outputStreamToOpIds.put(opSpec.getNextStream(), opSpec.getOpId());
-        }
-
-        if (opSpec.getNextStream() != null) {
-          updateOperatorGraphJson(opSpec.getNextStream(), opGraph);
-        }
-      });
+  private void updateOperatorGraphJson(OperatorSpec operatorSpec, OperatorGraphJson opGraph) {
+    // TODO xiliu: render input operators instead of input streams
+    if (operatorSpec.getOpCode() != OpCode.INPUT) {
+      opGraph.operators.put(operatorSpec.getOpId(), operatorToMap(operatorSpec));
+    }
+    Collection<OperatorSpec> specs = operatorSpec.getRegisteredOperatorSpecs();
+    specs.forEach(opSpec -> updateOperatorGraphJson(opSpec, opGraph));
+  }
+
+  /**
+   * Format the operator properties into a map
+   * @param spec a {@link OperatorSpec} instance
+   * @return map of the operator properties
+   */
+  private Map<String, Object> operatorToMap(OperatorSpec spec) {
+    Map<String, Object> map = new HashMap<>();
+    map.put("opCode", spec.getOpCode().name());
+    map.put("opId", spec.getOpId());
+    map.put("sourceLocation", spec.getSourceLocation());
+
+    Collection<OperatorSpec> nextOperators = spec.getRegisteredOperatorSpecs();
+    map.put("nextOperatorIds", nextOperators.stream().map(OperatorSpec::getOpId).collect(Collectors.toSet()));
+
+    if (spec instanceof OutputOperatorSpec) {
+      OutputStreamImpl outputStream = ((OutputOperatorSpec) spec).getOutputStream();
+      map.put("outputStreamId", outputStream.getStreamSpec().getId());
+    }
+
+    if (spec instanceof JoinOperatorSpec) {
+      map.put("ttlMs", ((JoinOperatorSpec) spec).getTtlMs());
+    }
+
+    return map;
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/samza/blob/c1c4289c/samza-core/src/main/java/org/apache/samza/execution/JobNode.java
----------------------------------------------------------------------
diff --git a/samza-core/src/main/java/org/apache/samza/execution/JobNode.java b/samza-core/src/main/java/org/apache/samza/execution/JobNode.java
index fbad520..c42e1cc 100644
--- a/samza-core/src/main/java/org/apache/samza/execution/JobNode.java
+++ b/samza-core/src/main/java/org/apache/samza/execution/JobNode.java
@@ -31,8 +31,8 @@ import org.apache.samza.config.JobConfig;
 import org.apache.samza.config.MapConfig;
 import org.apache.samza.config.TaskConfig;
 import org.apache.samza.operators.StreamGraphImpl;
+import org.apache.samza.operators.spec.JoinOperatorSpec;
 import org.apache.samza.operators.spec.OperatorSpec;
-import org.apache.samza.operators.spec.PartialJoinOperatorSpec;
 import org.apache.samza.operators.spec.WindowOperatorSpec;
 import org.apache.samza.operators.util.MathUtils;
 import org.apache.samza.util.Util;
@@ -145,7 +145,7 @@ public class JobNode {
     // Filter out the join operators, and obtain a list of their ttl values
     List<Long> joinTtlIntervals = operatorSpecs.stream()
         .filter(spec -> spec.getOpCode() == OperatorSpec.OpCode.JOIN)
-        .map(spec -> ((PartialJoinOperatorSpec) spec).getTtlMs())
+        .map(spec -> ((JoinOperatorSpec) spec).getTtlMs())
         .collect(Collectors.toList());
 
     // Combine both the above lists

http://git-wip-us.apache.org/repos/asf/samza/blob/c1c4289c/samza-core/src/main/java/org/apache/samza/operators/MessageStreamImpl.java
----------------------------------------------------------------------
diff --git a/samza-core/src/main/java/org/apache/samza/operators/MessageStreamImpl.java b/samza-core/src/main/java/org/apache/samza/operators/MessageStreamImpl.java
index 9912f95..db6fd5a 100644
--- a/samza-core/src/main/java/org/apache/samza/operators/MessageStreamImpl.java
+++ b/samza-core/src/main/java/org/apache/samza/operators/MessageStreamImpl.java
@@ -19,37 +19,35 @@
 
 package org.apache.samza.operators;
 
-import org.apache.samza.config.Config;
 import org.apache.samza.operators.functions.FilterFunction;
 import org.apache.samza.operators.functions.FlatMapFunction;
 import org.apache.samza.operators.functions.JoinFunction;
 import org.apache.samza.operators.functions.MapFunction;
-import org.apache.samza.operators.functions.PartialJoinFunction;
 import org.apache.samza.operators.functions.SinkFunction;
+import org.apache.samza.operators.spec.JoinOperatorSpec;
 import org.apache.samza.operators.spec.OperatorSpec;
 import org.apache.samza.operators.spec.OperatorSpecs;
+import org.apache.samza.operators.spec.OutputOperatorSpec;
+import org.apache.samza.operators.spec.OutputStreamImpl;
+import org.apache.samza.operators.spec.StreamOperatorSpec;
 import org.apache.samza.operators.spec.SinkOperatorSpec;
-import org.apache.samza.operators.stream.OutputStreamInternal;
-import org.apache.samza.operators.util.InternalInMemoryStore;
+import org.apache.samza.operators.stream.IntermediateMessageStreamImpl;
 import org.apache.samza.operators.windows.Window;
 import org.apache.samza.operators.windows.WindowPane;
 import org.apache.samza.operators.windows.internal.WindowInternal;
-import org.apache.samza.storage.kv.KeyValueStore;
-import org.apache.samza.task.TaskContext;
 
 import java.time.Duration;
-import java.util.ArrayList;
 import java.util.Collection;
-import java.util.Collections;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Set;
 import java.util.function.Function;
 
 
 /**
- * The implementation for input/output {@link MessageStream}s to/from the operators.
- * Users use the {@link MessageStream} API methods to describe and chain the operators specs.
+ * The {@link MessageStream} implementation that lets users describe their logical DAG.
+ * Users can obtain an instance by calling {@link StreamGraph#getInputStream}.
+ * <p>
+ * Each {@link MessageStreamImpl} is associated with a single {@link OperatorSpec} in the DAG and allows
+ * users to chain further operators on its {@link OperatorSpec}. In other words, a {@link MessageStreamImpl}
+ * presents an "edge-centric" (streams) view of the "node-centric" (specs) logical DAG for the users.
  *
  * @param <M>  type of messages in this {@link MessageStream}
  */
@@ -60,171 +58,97 @@ public class MessageStreamImpl<M> implements MessageStream<M> {
   private final StreamGraphImpl graph;
 
   /**
-   * The set of operators that consume the messages in this {@link MessageStream}
-   *
-   * Use a LinkedHashSet since we need deterministic ordering in initializing/closing operators.
+   * The {@link OperatorSpec} associated with this {@link MessageStreamImpl}
    */
-  private final Set<OperatorSpec> registeredOperatorSpecs = new LinkedHashSet<>();
+  private final OperatorSpec operatorSpec;
 
-  /**
-   * Default constructor
-   *
-   * @param graph the {@link StreamGraphImpl} object that this stream belongs to
-   */
-  public MessageStreamImpl(StreamGraphImpl graph) {
+  public MessageStreamImpl(StreamGraphImpl graph, OperatorSpec<?, M> operatorSpec) {
     this.graph = graph;
+    this.operatorSpec = operatorSpec;
   }
 
   @Override
   public <TM> MessageStream<TM> map(MapFunction<? super M, ? extends TM> mapFn) {
-    OperatorSpec<TM> op = OperatorSpecs.createMapOperatorSpec(
-        mapFn, new MessageStreamImpl<>(this.graph), this.graph.getNextOpId());
-    this.registeredOperatorSpecs.add(op);
-    return op.getNextStream();
+    OperatorSpec<M, TM> op = OperatorSpecs.createMapOperatorSpec(mapFn, this.graph.getNextOpId());
+    this.operatorSpec.registerNextOperatorSpec(op);
+    return new MessageStreamImpl<>(this.graph, op);
   }
 
   @Override
   public MessageStream<M> filter(FilterFunction<? super M> filterFn) {
-    OperatorSpec<M> op = OperatorSpecs.createFilterOperatorSpec(filterFn, new MessageStreamImpl<>(this.graph),
-        this.graph.getNextOpId());
-    this.registeredOperatorSpecs.add(op);
-    return op.getNextStream();
+    OperatorSpec<M, M> op = OperatorSpecs.createFilterOperatorSpec(filterFn, this.graph.getNextOpId());
+    this.operatorSpec.registerNextOperatorSpec(op);
+    return new MessageStreamImpl<>(this.graph, op);
   }
 
   @Override
   public <TM> MessageStream<TM> flatMap(FlatMapFunction<? super M, ? extends TM> flatMapFn) {
-    OperatorSpec<TM> op = OperatorSpecs.createStreamOperatorSpec(flatMapFn, new MessageStreamImpl<>(this.graph),
-        this.graph.getNextOpId());
-    this.registeredOperatorSpecs.add(op);
-    return op.getNextStream();
+    OperatorSpec<M, TM> op = OperatorSpecs.createFlatMapOperatorSpec(flatMapFn, this.graph.getNextOpId());
+    this.operatorSpec.registerNextOperatorSpec(op);
+    return new MessageStreamImpl<>(this.graph, op);
   }
 
   @Override
   public void sink(SinkFunction<? super M> sinkFn) {
     SinkOperatorSpec<M> op = OperatorSpecs.createSinkOperatorSpec(sinkFn, this.graph.getNextOpId());
-    this.registeredOperatorSpecs.add(op);
+    this.operatorSpec.registerNextOperatorSpec(op);
   }
 
   @Override
   public <K, V> void sendTo(OutputStream<K, V, M> outputStream) {
-    SinkOperatorSpec<M> op = OperatorSpecs.createSendToOperatorSpec((OutputStreamInternal<K, V, M>) outputStream,
-        this.graph.getNextOpId());
-    this.registeredOperatorSpecs.add(op);
+    OutputOperatorSpec<M> op = OperatorSpecs.createSendToOperatorSpec(
+        (OutputStreamImpl<K, V, M>) outputStream, this.graph.getNextOpId());
+    this.operatorSpec.registerNextOperatorSpec(op);
   }
 
   @Override
   public <K, WV> MessageStream<WindowPane<K, WV>> window(Window<M, K, WV> window) {
-    OperatorSpec<WindowPane<K, WV>> wndOp = OperatorSpecs.createWindowOperatorSpec((WindowInternal<M, K, WV>) window,
-        new MessageStreamImpl<>(this.graph), this.graph.getNextOpId());
-    this.registeredOperatorSpecs.add(wndOp);
-    return wndOp.getNextStream();
+    OperatorSpec<M, WindowPane<K, WV>> op = OperatorSpecs.createWindowOperatorSpec(
+        (WindowInternal<M, K, WV>) window, this.graph.getNextOpId());
+    this.operatorSpec.registerNextOperatorSpec(op);
+    return new MessageStreamImpl<>(this.graph, op);
   }
 
   @Override
-  public <K, OM, TM> MessageStream<TM> join(
-      MessageStream<OM> otherStream, JoinFunction<? extends K, ? super M, ? super OM, ? extends TM> joinFn, Duration ttl) {
-    MessageStreamImpl<TM> nextStream = new MessageStreamImpl<>(this.graph);
-
-    PartialJoinFunction<K, M, OM, TM> thisPartialJoinFn = new PartialJoinFunction<K, M, OM, TM>() {
-      private KeyValueStore<K, PartialJoinFunction.PartialJoinMessage<M>> thisStreamState;
-
-      @Override
-      public TM apply(M m, OM jm) {
-        return joinFn.apply(m, jm);
-      }
-
-      @Override
-      public K getKey(M message) {
-        return joinFn.getFirstKey(message);
-      }
-
-      @Override
-      public KeyValueStore<K, PartialJoinMessage<M>> getState() {
-        return thisStreamState;
-      }
-
-      @Override
-      public void init(Config config, TaskContext context) {
-        // joinFn#init() must only be called once, so we do it in this partial join function's #init.
-        joinFn.init(config, context);
-
-        thisStreamState = new InternalInMemoryStore<>();
-      }
-
-      @Override
-      public void close() {
-        // joinFn#close() must only be called once, so we do it in this partial join function's #close.
-        joinFn.close();
-      }
-    };
-
-    PartialJoinFunction<K, OM, M, TM> otherPartialJoinFn = new PartialJoinFunction<K, OM, M, TM>() {
-      private KeyValueStore<K, PartialJoinMessage<OM>> otherStreamState;
-
-      @Override
-      public TM apply(OM om, M m) {
-        return joinFn.apply(m, om);
-      }
-
-      @Override
-      public K getKey(OM message) {
-        return joinFn.getSecondKey(message);
-      }
-
-      @Override
-      public KeyValueStore<K, PartialJoinMessage<OM>> getState() {
-        return otherStreamState;
-      }
-
-      @Override
-      public void init(Config config, TaskContext taskContext) {
-        otherStreamState = new InternalInMemoryStore<>();
-      }
-    };
-
-    this.registeredOperatorSpecs.add(OperatorSpecs.createPartialJoinOperatorSpec(
-        thisPartialJoinFn, otherPartialJoinFn, ttl.toMillis(), nextStream, this.graph.getNextOpId()));
-
-    ((MessageStreamImpl<OM>) otherStream).registeredOperatorSpecs.add(OperatorSpecs
-        .createPartialJoinOperatorSpec(otherPartialJoinFn, thisPartialJoinFn, ttl.toMillis(), nextStream,
-            this.graph.getNextOpId()));
-
-    return nextStream;
+  public <K, JM, TM> MessageStream<TM> join(MessageStream<JM> otherStream,
+      JoinFunction<? extends K, ? super M, ? super JM, ? extends TM> joinFn, Duration ttl) {
+    OperatorSpec<?, JM> otherOpSpec = ((MessageStreamImpl<JM>) otherStream).getOperatorSpec();
+    JoinOperatorSpec<K, M, JM, TM> joinOpSpec =
+        OperatorSpecs.createJoinOperatorSpec(this.operatorSpec, otherOpSpec,
+            (JoinFunction<K, M, JM, TM>) joinFn, ttl.toMillis(), this.graph.getNextOpId());
+
+    this.operatorSpec.registerNextOperatorSpec(joinOpSpec);
+    otherOpSpec.registerNextOperatorSpec((OperatorSpec<JM, ?>) joinOpSpec);
+
+    return new MessageStreamImpl<>(this.graph, joinOpSpec);
   }
 
   @Override
   public MessageStream<M> merge(Collection<? extends MessageStream<? extends M>> otherStreams) {
-    MessageStreamImpl<M> nextStream = new MessageStreamImpl<>(this.graph);
-    List<MessageStream<M>> streamsToMerge = new ArrayList<>((Collection<MessageStream<M>>) otherStreams);
-    streamsToMerge.add(this);
-    
-    streamsToMerge.forEach(stream -> {
-        OperatorSpec mergeOperatorSpec =
-            OperatorSpecs.createMergeOperatorSpec(nextStream, this.graph.getNextOpId());
-        ((MessageStreamImpl<M>) stream).registeredOperatorSpecs.add(mergeOperatorSpec);
-      });
-    return nextStream;
+    StreamOperatorSpec<M, M> opSpec = OperatorSpecs.createMergeOperatorSpec(this.graph.getNextOpId());
+    this.operatorSpec.registerNextOperatorSpec(opSpec);
+    otherStreams.forEach(other ->
+        ((MessageStreamImpl<M>) other).getOperatorSpec().registerNextOperatorSpec(opSpec));
+    return new MessageStreamImpl<>(this.graph, opSpec);
   }
 
   @Override
   public <K> MessageStream<M> partitionBy(Function<? super M, ? extends K> keyExtractor) {
     int opId = this.graph.getNextOpId();
     String opName = String.format("%s-%s", OperatorSpec.OpCode.PARTITION_BY.name().toLowerCase(), opId);
-    MessageStreamImpl<M> intermediateStream =
-        this.graph.<K, M, M>getIntermediateStream(opName, keyExtractor, m -> m, (k, m) -> m);
-    SinkOperatorSpec<M> partitionByOperatorSpec = OperatorSpecs.createPartitionByOperatorSpec(
-        (OutputStreamInternal<K, M, M>) intermediateStream, opId);
-    this.registeredOperatorSpecs.add(partitionByOperatorSpec);
+    IntermediateMessageStreamImpl<K, M, M> intermediateStream =
+        this.graph.getIntermediateStream(opName, keyExtractor, m -> m, (k, m) -> m);
+    OutputOperatorSpec<M> partitionByOperatorSpec = OperatorSpecs.createPartitionByOperatorSpec(
+        intermediateStream.getOutputStream(), opId);
+    this.operatorSpec.registerNextOperatorSpec(partitionByOperatorSpec);
     return intermediateStream;
   }
 
   /**
-   * Gets the operator specs registered to consume the output of this {@link MessageStream}. This is an internal API and
-   * should not be exposed to users.
-   *
-   * @return  a collection containing all {@link OperatorSpec}s that are registered with this {@link MessageStream}.
+   * Get the {@link OperatorSpec} associated with this {@link MessageStreamImpl}.
+   * @return the {@link OperatorSpec} associated with this {@link MessageStreamImpl}.
    */
-  public Collection<OperatorSpec> getRegisteredOperatorSpecs() {
-    return Collections.unmodifiableSet(this.registeredOperatorSpecs);
+  protected OperatorSpec<?, M> getOperatorSpec() {
+    return this.operatorSpec;
   }
 }

http://git-wip-us.apache.org/repos/asf/samza/blob/c1c4289c/samza-core/src/main/java/org/apache/samza/operators/StreamGraphImpl.java
----------------------------------------------------------------------
diff --git a/samza-core/src/main/java/org/apache/samza/operators/StreamGraphImpl.java b/samza-core/src/main/java/org/apache/samza/operators/StreamGraphImpl.java
index fcce5eb..c0da1b2 100644
--- a/samza-core/src/main/java/org/apache/samza/operators/StreamGraphImpl.java
+++ b/samza-core/src/main/java/org/apache/samza/operators/StreamGraphImpl.java
@@ -20,12 +20,10 @@ package org.apache.samza.operators;
 
 import org.apache.samza.config.Config;
 import org.apache.samza.config.JobConfig;
+import org.apache.samza.operators.spec.InputOperatorSpec;
+import org.apache.samza.operators.spec.OutputStreamImpl;
+import org.apache.samza.operators.stream.IntermediateMessageStreamImpl;
 import org.apache.samza.operators.spec.OperatorSpec;
-import org.apache.samza.operators.stream.InputStreamInternal;
-import org.apache.samza.operators.stream.InputStreamInternalImpl;
-import org.apache.samza.operators.stream.IntermediateStreamInternalImpl;
-import org.apache.samza.operators.stream.OutputStreamInternal;
-import org.apache.samza.operators.stream.OutputStreamInternalImpl;
 import org.apache.samza.runtime.ApplicationRunner;
 import org.apache.samza.system.StreamSpec;
 
@@ -51,9 +49,9 @@ public class StreamGraphImpl implements StreamGraph {
    */
   private int opId = 0;
 
-  // Using LHM for deterministic order in initializing and closing operators.
-  private final Map<StreamSpec, InputStreamInternal> inStreams = new LinkedHashMap<>();
-  private final Map<StreamSpec, OutputStreamInternal> outStreams = new LinkedHashMap<>();
+  // We use a LHM for deterministic order in initializing and closing operators.
+  private final Map<StreamSpec, InputOperatorSpec> inputOperators = new LinkedHashMap<>();
+  private final Map<StreamSpec, OutputStreamImpl> outputStreams = new LinkedHashMap<>();
   private final ApplicationRunner runner;
   private final Config config;
 
@@ -67,17 +65,21 @@ public class StreamGraphImpl implements StreamGraph {
   }
 
   @Override
-  public <K, V, M> MessageStream<M> getInputStream(String streamId, BiFunction<? super K, ? super V, ? extends M> msgBuilder) {
+  public <K, V, M> MessageStream<M> getInputStream(String streamId,
+      BiFunction<? super K, ? super V, ? extends M> msgBuilder) {
     if (msgBuilder == null) {
       throw new IllegalArgumentException("msgBuilder can't be null for an input stream");
     }
 
-    if (inStreams.containsKey(runner.getStreamSpec(streamId))) {
-      throw new IllegalStateException("Cannot invoke getInputStream() multiple times with the same streamId: " + streamId);
+    if (inputOperators.containsKey(runner.getStreamSpec(streamId))) {
+      throw new IllegalStateException("getInputStream() invoked multiple times "
+          + "with the same streamId: " + streamId);
     }
 
-    return inStreams.computeIfAbsent(runner.getStreamSpec(streamId),
-        streamSpec -> new InputStreamInternalImpl<>(this, streamSpec, (BiFunction<K, V, M>) msgBuilder));
+    StreamSpec streamSpec = runner.getStreamSpec(streamId);
+    inputOperators.put(streamSpec,
+        new InputOperatorSpec<>(streamSpec, (BiFunction<K, V, M>) msgBuilder, this.getNextOpId()));
+    return new MessageStreamImpl<>(this, inputOperators.get(streamSpec));
   }
 
   @Override
@@ -91,12 +93,15 @@ public class StreamGraphImpl implements StreamGraph {
       throw new IllegalArgumentException("msgExtractor can't be null for an output stream.");
     }
 
-    if (outStreams.containsKey(runner.getStreamSpec(streamId))) {
-      throw new IllegalStateException("Cannot invoke getOutputStream() multiple times with the same streamId: " + streamId);
+    if (outputStreams.containsKey(runner.getStreamSpec(streamId))) {
+      throw new IllegalStateException("getOutputStream() invoked multiple times "
+          + "with the same streamId: " + streamId);
     }
 
-    return outStreams.computeIfAbsent(runner.getStreamSpec(streamId),
-        streamSpec -> new OutputStreamInternalImpl<>(this, streamSpec, (Function<M, K>) keyExtractor, (Function<M, V>) msgExtractor));
+    StreamSpec streamSpec = runner.getStreamSpec(streamId);
+    outputStreams.put(streamSpec,
+        new OutputStreamImpl<>(streamSpec, (Function<M, K>) keyExtractor, (Function<M, V>) msgExtractor));
+    return outputStreams.get(streamSpec);
   }
 
   @Override
@@ -120,8 +125,9 @@ public class StreamGraphImpl implements StreamGraph {
    * @param <M> the type of messages in the intermediate {@link MessageStream}
    * @return  the intermediate {@link MessageStreamImpl}
    */
-  <K, V, M> MessageStreamImpl<M> getIntermediateStream(String streamName,
-      Function<? super M, ? extends K> keyExtractor, Function<? super M, ? extends V> msgExtractor, BiFunction<? super K, ? super V, ? extends M> msgBuilder) {
+  <K, V, M> IntermediateMessageStreamImpl<K, V, M> getIntermediateStream(String streamName,
+      Function<? super M, ? extends K> keyExtractor, Function<? super M, ? extends V> msgExtractor,
+      BiFunction<? super K, ? super V, ? extends M> msgBuilder) {
     String streamId = String.format("%s-%s-%s",
         config.get(JobConfig.JOB_NAME()),
         config.get(JobConfig.JOB_ID(), "1"),
@@ -129,30 +135,28 @@ public class StreamGraphImpl implements StreamGraph {
     if (msgBuilder == null) {
       throw new IllegalArgumentException("msgBuilder cannot be null for an intermediate stream");
     }
-
     if (keyExtractor == null) {
       throw new IllegalArgumentException("keyExtractor can't be null for an output stream.");
     }
     if (msgExtractor == null) {
       throw new IllegalArgumentException("msgExtractor can't be null for an output stream.");
     }
-
     StreamSpec streamSpec = runner.getStreamSpec(streamId);
-    IntermediateStreamInternalImpl<K, V, M> intStream =
-        (IntermediateStreamInternalImpl<K, V, M>) inStreams
-            .computeIfAbsent(streamSpec,
-                k -> new IntermediateStreamInternalImpl<>(this, streamSpec, (Function<M, K>) keyExtractor,
-                    (Function<M, V>) msgExtractor, (BiFunction<K, V, M>) msgBuilder));
-    outStreams.putIfAbsent(streamSpec, intStream);
-    return intStream;
+    if (inputOperators.containsKey(streamSpec) || outputStreams.containsKey(streamSpec)) {
+      throw new IllegalStateException("getIntermediateStream() invoked multiple times "
+          + "with the same streamId: " + streamId);
+    }
+    inputOperators.put(streamSpec, new InputOperatorSpec(streamSpec, msgBuilder, this.getNextOpId()));
+    outputStreams.put(streamSpec, new OutputStreamImpl(streamSpec, keyExtractor, msgExtractor));
+    return new IntermediateMessageStreamImpl<>(this, inputOperators.get(streamSpec), outputStreams.get(streamSpec));
   }
 
-  public Map<StreamSpec, InputStreamInternal> getInputStreams() {
-    return Collections.unmodifiableMap(inStreams);
+  public Map<StreamSpec, InputOperatorSpec> getInputOperators() {
+    return Collections.unmodifiableMap(inputOperators);
   }
 
-  public Map<StreamSpec, OutputStreamInternal> getOutputStreams() {
-    return Collections.unmodifiableMap(outStreams);
+  public Map<StreamSpec, OutputStreamImpl> getOutputStreams() {
+    return Collections.unmodifiableMap(outputStreams);
   }
 
   public ContextManager getContextManager() {
@@ -169,24 +173,20 @@ public class StreamGraphImpl implements StreamGraph {
    * @return  a set of all available {@link OperatorSpec}s
    */
   public Collection<OperatorSpec> getAllOperatorSpecs() {
-    Collection<InputStreamInternal> inputStreams = inStreams.values();
+    Collection<InputOperatorSpec> inputOperatorSpecs = inputOperators.values();
     Set<OperatorSpec> operatorSpecs = new HashSet<>();
 
-    for (InputStreamInternal stream : inputStreams) {
-      doGetOperatorSpecs((MessageStreamImpl) stream, operatorSpecs);
+    for (InputOperatorSpec inputOperatorSpec: inputOperatorSpecs) {
+      doGetOperatorSpecs(inputOperatorSpec, operatorSpecs);
     }
     return operatorSpecs;
   }
 
-  private void doGetOperatorSpecs(MessageStreamImpl stream, Set<OperatorSpec> specs) {
-    Collection<OperatorSpec> registeredOperatorSpecs = stream.getRegisteredOperatorSpecs();
-    for (OperatorSpec spec : registeredOperatorSpecs) {
-      specs.add(spec);
-      MessageStreamImpl nextStream = spec.getNextStream();
-      if (nextStream != null) {
-        //Recursively traverse and obtain all reachable operators
-        doGetOperatorSpecs(nextStream, specs);
-      }
+  private void doGetOperatorSpecs(OperatorSpec operatorSpec, Set<OperatorSpec> specs) {
+    Collection<OperatorSpec> registeredOperatorSpecs = operatorSpec.getRegisteredOperatorSpecs();
+    for (OperatorSpec registeredOperatorSpec: registeredOperatorSpecs) {
+      specs.add(registeredOperatorSpec);
+      doGetOperatorSpecs(registeredOperatorSpec, specs);
     }
   }
 

http://git-wip-us.apache.org/repos/asf/samza/blob/c1c4289c/samza-core/src/main/java/org/apache/samza/operators/WindowState.java
----------------------------------------------------------------------
diff --git a/samza-core/src/main/java/org/apache/samza/operators/WindowState.java b/samza-core/src/main/java/org/apache/samza/operators/WindowState.java
deleted file mode 100644
index 801044b..0000000
--- a/samza-core/src/main/java/org/apache/samza/operators/WindowState.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.samza.operators;
-
-/**
- * Wraps the value stored for a particular {@link org.apache.samza.operators.windows.WindowKey} with additional metadata.
- */
-public class WindowState<WV> {
-
-  final WV wv;
-  /**
-   * Time of the first message in the window
-   */
-  final long earliestRecvTime;
-
-  public WindowState(WV wv, long earliestRecvTime) {
-    this.wv = wv;
-    this.earliestRecvTime = earliestRecvTime;
-  }
-
-  public WV getWindowValue() {
-    return wv;
-  }
-
-  public long getEarliestTimestamp() {
-    return earliestRecvTime;
-  }
-
-  @Override
-  public String toString() {
-    return String.format("WindowState: {time=%d, value=%s}", earliestRecvTime, wv);
-  }
-}

http://git-wip-us.apache.org/repos/asf/samza/blob/c1c4289c/samza-core/src/main/java/org/apache/samza/operators/impl/InputOperatorImpl.java
----------------------------------------------------------------------
diff --git a/samza-core/src/main/java/org/apache/samza/operators/impl/InputOperatorImpl.java b/samza-core/src/main/java/org/apache/samza/operators/impl/InputOperatorImpl.java
new file mode 100644
index 0000000..0545af1
--- /dev/null
+++ b/samza-core/src/main/java/org/apache/samza/operators/impl/InputOperatorImpl.java
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.samza.operators.impl;
+
+import org.apache.commons.lang3.tuple.Pair;
+import org.apache.samza.config.Config;
+import org.apache.samza.operators.spec.InputOperatorSpec;
+import org.apache.samza.operators.spec.OperatorSpec;
+import org.apache.samza.task.MessageCollector;
+import org.apache.samza.task.TaskContext;
+import org.apache.samza.task.TaskCoordinator;
+
+import java.util.Collection;
+import java.util.Collections;
+
+
+/**
+ * An operator that builds the input message from the incoming message.
+ *
+ * @param <K> the type of key in the incoming message
+ * @param <V> the type of message in the incoming message
+ * @param <M> the type of input message
+ */
+public final class InputOperatorImpl<K, V, M> extends OperatorImpl<Pair<K, V>, M> {
+
+  private final InputOperatorSpec<K, V, M> inputOpSpec;
+
+  InputOperatorImpl(InputOperatorSpec<K, V, M> inputOpSpec) {
+    this.inputOpSpec = inputOpSpec;
+  }
+
+  @Override
+  protected void handleInit(Config config, TaskContext context) {
+  }
+
+  @Override
+  public Collection<M> handleMessage(Pair<K, V> pair, MessageCollector collector, TaskCoordinator coordinator) {
+    // TODO: SAMZA-1148 - Cast to appropriate input (key, msg) types based on the serde before applying the msgBuilder.
+    M message = this.inputOpSpec.getMsgBuilder().apply(pair.getKey(), pair.getValue());
+    return Collections.singletonList(message);
+  }
+
+  @Override
+  protected void handleClose() {
+  }
+
+  protected OperatorSpec<Pair<K, V>, M> getOperatorSpec() {
+    return this.inputOpSpec;
+  }
+}

http://git-wip-us.apache.org/repos/asf/samza/blob/c1c4289c/samza-core/src/main/java/org/apache/samza/operators/impl/OperatorImpl.java
----------------------------------------------------------------------
diff --git a/samza-core/src/main/java/org/apache/samza/operators/impl/OperatorImpl.java b/samza-core/src/main/java/org/apache/samza/operators/impl/OperatorImpl.java
index 23c31ac..73bb83d 100644
--- a/samza-core/src/main/java/org/apache/samza/operators/impl/OperatorImpl.java
+++ b/samza-core/src/main/java/org/apache/samza/operators/impl/OperatorImpl.java
@@ -43,12 +43,13 @@ public abstract class OperatorImpl<M, RM> {
 
   private boolean initialized;
   private boolean closed;
-  private Set<OperatorImpl<RM, ?>> registeredOperators;
   private HighResolutionClock highResClock;
   private Counter numMessage;
   private Timer handleMessageNs;
   private Timer handleTimerNs;
 
+  Set<OperatorImpl<RM, ?>> registeredOperators;
+
   /**
    * Initialize this {@link OperatorImpl} and its user-defined functions.
    *
@@ -56,7 +57,7 @@ public abstract class OperatorImpl<M, RM> {
    * @param context  the {@link TaskContext} for the task
    */
   public final void init(Config config, TaskContext context) {
-    String opName = getOperatorSpec().getOpName();
+    String opName = getOperatorName();
 
     if (initialized) {
       throw new IllegalStateException(String.format("Attempted to initialize Operator %s more than once.", opName));
@@ -95,7 +96,7 @@ public abstract class OperatorImpl<M, RM> {
     if (!initialized) {
       throw new IllegalStateException(
           String.format("Attempted to register next operator before initializing operator %s.",
-              getOperatorSpec().getOpName()));
+              getOperatorName()));
     }
     this.registeredOperators.add(nextOperator);
   }
@@ -167,10 +168,9 @@ public abstract class OperatorImpl<M, RM> {
   }
 
   public void close() {
-    String opName = getOperatorSpec().getOpName();
-
     if (closed) {
-      throw new IllegalStateException(String.format("Attempted to close Operator %s more than once.", opName));
+      throw new IllegalStateException(
+          String.format("Attempted to close Operator %s more than once.", getOperatorSpec().getOpName()));
     }
     handleClose();
     closed = true;
@@ -183,7 +183,20 @@ public abstract class OperatorImpl<M, RM> {
    *
    * @return the {@link OperatorSpec} for this {@link OperatorImpl}
    */
-  protected abstract OperatorSpec<RM> getOperatorSpec();
+  protected abstract OperatorSpec<M, RM> getOperatorSpec();
+
+  /**
+   * Get the name for this {@link OperatorImpl}.
+   *
+   * Some {@link OperatorImpl}s don't have a 1:1 mapping with their {@link OperatorSpec}. E.g., there are
+   * 2 PartialJoinOperatorImpls for a JoinOperatorSpec. Overriding this method allows them to provide an
+   * implementation specific name, e.g., for use in metrics.
+   *
+   * @return the operator name
+   */
+  protected String getOperatorName() {
+    return getOperatorSpec().getOpName();
+  }
 
   private HighResolutionClock createHighResClock(Config config) {
     if (new MetricsConfig(config).getMetricsTimerEnabled()) {

http://git-wip-us.apache.org/repos/asf/samza/blob/c1c4289c/samza-core/src/main/java/org/apache/samza/operators/impl/OperatorImplGraph.java
----------------------------------------------------------------------
diff --git a/samza-core/src/main/java/org/apache/samza/operators/impl/OperatorImplGraph.java b/samza-core/src/main/java/org/apache/samza/operators/impl/OperatorImplGraph.java
index e99b3ee..e5fce13 100644
--- a/samza-core/src/main/java/org/apache/samza/operators/impl/OperatorImplGraph.java
+++ b/samza-core/src/main/java/org/apache/samza/operators/impl/OperatorImplGraph.java
@@ -19,18 +19,23 @@
 package org.apache.samza.operators.impl;
 
 import com.google.common.collect.Lists;
+import org.apache.commons.lang3.tuple.Pair;
 import org.apache.samza.config.Config;
-import org.apache.samza.operators.MessageStreamImpl;
 import org.apache.samza.operators.StreamGraphImpl;
+import org.apache.samza.operators.functions.JoinFunction;
+import org.apache.samza.operators.functions.PartialJoinFunction;
+import org.apache.samza.operators.spec.InputOperatorSpec;
+import org.apache.samza.operators.spec.JoinOperatorSpec;
 import org.apache.samza.operators.spec.OperatorSpec;
-import org.apache.samza.operators.spec.SinkOperatorSpec;
-import org.apache.samza.operators.spec.PartialJoinOperatorSpec;
+import org.apache.samza.operators.spec.OutputOperatorSpec;
 import org.apache.samza.operators.spec.StreamOperatorSpec;
+import org.apache.samza.operators.spec.SinkOperatorSpec;
 import org.apache.samza.operators.spec.WindowOperatorSpec;
+import org.apache.samza.operators.util.InternalInMemoryStore;
+import org.apache.samza.storage.kv.KeyValueStore;
 import org.apache.samza.system.SystemStream;
 import org.apache.samza.task.TaskContext;
 import org.apache.samza.util.Clock;
-import org.apache.samza.util.SystemClock;
 
 import java.util.ArrayList;
 import java.util.Collection;
@@ -42,67 +47,59 @@ import java.util.Map;
 
 
 /**
- * Instantiates the DAG of {@link OperatorImpl}s corresponding to the {@link OperatorSpec}s for the input
- * {@link MessageStreamImpl}s.
+ * The DAG of {@link OperatorImpl}s corresponding to the DAG of {@link OperatorSpec}s.
  */
 public class OperatorImplGraph {
 
   /**
-   * A mapping from {@link OperatorSpec}s to their {@link OperatorImpl}s in this graph. Used to avoid creating
-   * multiple {@link OperatorImpl}s for an {@link OperatorSpec}, e.g., when it's reached from different
-   * input {@link MessageStreamImpl}s.
-   *
-   * Using LHM for deterministic ordering in initializing and closing operators.
+   * A mapping from operator names to their {@link OperatorImpl}s in this graph. Used to avoid creating
+   * multiple {@link OperatorImpl}s for an {@link OperatorSpec} when it's reached from different
+   * {@link OperatorSpec}s during DAG traversals (e.g., for the merge operator).
+   * We use a LHM for deterministic ordering in initializing and closing operators.
    */
-  private final Map<OperatorSpec, OperatorImpl> operatorImpls = new LinkedHashMap<>();
+  private final Map<String, OperatorImpl> operatorImpls = new LinkedHashMap<>();
 
   /**
-   * A mapping from input {@link SystemStream}s to their {@link OperatorImpl} sub-DAG in this graph.
+   * A mapping from input {@link SystemStream}s to their {@link InputOperatorImpl} sub-DAG in this graph.
    */
-  private final Map<SystemStream, RootOperatorImpl> rootOperators = new HashMap<>();
+  private final Map<SystemStream, InputOperatorImpl> inputOperators = new HashMap<>();
 
-  private final Clock clock;
-
-  public OperatorImplGraph(Clock clock) {
-    this.clock = clock;
-  }
+  /**
+   * A mapping from {@link JoinOperatorSpec}s to their two {@link PartialJoinFunction}s. Used to associate
+   * the two {@link PartialJoinOperatorImpl}s for a {@link JoinOperatorSpec} with each other since they're
+   * reached from different {@link OperatorSpec} during DAG traversals.
+   */
+  private final Map<Integer, Pair<PartialJoinFunction, PartialJoinFunction>> joinFunctions = new HashMap<>();
 
-  /* package private */ OperatorImplGraph() {
-    this(SystemClock.instance());
-  }
+  private final Clock clock;
 
   /**
-   * Initialize the DAG of {@link OperatorImpl}s for the input {@link MessageStreamImpl} in the provided
-   * {@link StreamGraphImpl}.
+   * Constructs the DAG of {@link OperatorImpl}s corresponding to the the DAG of {@link OperatorSpec}s
+   * in the {@code streamGraph}.
    *
-   * @param streamGraph  the logical {@link StreamGraphImpl}
+   * @param streamGraph  the {@link StreamGraphImpl} containing the logical {@link OperatorSpec} DAG
    * @param config  the {@link Config} required to instantiate operators
    * @param context  the {@link TaskContext} required to instantiate operators
+   * @param clock  the {@link Clock} to get current time
    */
-  public void init(StreamGraphImpl streamGraph, Config config, TaskContext context) {
-    streamGraph.getInputStreams().forEach((streamSpec, inputStream) -> {
+  public OperatorImplGraph(StreamGraphImpl streamGraph, Config config, TaskContext context, Clock clock) {
+    this.clock = clock;
+    streamGraph.getInputOperators().forEach((streamSpec, inputOpSpec) -> {
         SystemStream systemStream = new SystemStream(streamSpec.getSystemName(), streamSpec.getPhysicalName());
-        this.rootOperators.put(systemStream, this.createOperatorImpls((MessageStreamImpl) inputStream, config, context));
+        InputOperatorImpl inputOperatorImpl =
+            (InputOperatorImpl) createAndRegisterOperatorImpl(null, inputOpSpec, config, context);
+        this.inputOperators.put(systemStream, inputOperatorImpl);
       });
   }
 
   /**
-   * Get the {@link RootOperatorImpl} corresponding to the provided input {@code systemStream}.
+   * Get the {@link InputOperatorImpl} corresponding to the provided input {@code systemStream}.
    *
    * @param systemStream  input {@link SystemStream}
-   * @return  the {@link RootOperatorImpl} that starts processing the input message
+   * @return  the {@link InputOperatorImpl} that starts processing the input message
    */
-  public RootOperatorImpl getRootOperator(SystemStream systemStream) {
-    return this.rootOperators.get(systemStream);
-  }
-
-  /**
-   * Get all {@link RootOperatorImpl}s for the graph.
-   *
-   * @return  an unmodifiable view of all {@link RootOperatorImpl}s for the graph
-   */
-  public Collection<RootOperatorImpl> getAllRootOperators() {
-    return Collections.unmodifiableCollection(this.rootOperators.values());
+  public InputOperatorImpl getInputOperator(SystemStream systemStream) {
+    return this.inputOperators.get(systemStream);
   }
 
   public void close() {
@@ -112,65 +109,44 @@ public class OperatorImplGraph {
   }
 
   /**
-   * Traverses the DAG of {@link OperatorSpec}s starting from the provided {@link MessageStreamImpl},
-   * creates the corresponding DAG of {@link OperatorImpl}s, and returns its root {@link RootOperatorImpl} node.
+   * Get all {@link InputOperatorImpl}s for the graph.
    *
-   * @param source  the input {@link MessageStreamImpl} to instantiate {@link OperatorImpl}s for
-   * @param config  the {@link Config} required to instantiate operators
-   * @param context  the {@link TaskContext} required to instantiate operators
-   * @param <M>  the type of messages in the {@code source} {@link MessageStreamImpl}
-   * @return  root node for the {@link OperatorImpl} DAG
+   * @return  an unmodifiable view of all {@link InputOperatorImpl}s for the graph
    */
-  private <M> RootOperatorImpl<M> createOperatorImpls(MessageStreamImpl<M> source,
-      Config config, TaskContext context) {
-    // since the source message stream might have multiple operator specs registered on it,
-    // create a new root node as a single point of entry for the DAG.
-    RootOperatorImpl<M> rootOperator = new RootOperatorImpl<>();
-    rootOperator.init(config, context);
-    // create the pipeline/topology starting from the source
-    source.getRegisteredOperatorSpecs().forEach(registeredOperator -> {
-        // pass in the context so that operator implementations can initialize their functions
-        OperatorImpl<M, ?> operatorImpl =
-            createAndRegisterOperatorImpl(registeredOperator, config, context);
-        rootOperator.registerNextOperator(operatorImpl);
-      });
-    return rootOperator;
+  public Collection<InputOperatorImpl> getAllInputOperators() {
+    return Collections.unmodifiableCollection(this.inputOperators.values());
   }
 
   /**
-   * Helper method to recursively traverse the {@link OperatorSpec} DAG and instantiate and link the corresponding
-   * {@link OperatorImpl}s.
+   * Traverses the DAG of {@link OperatorSpec}s starting from the provided {@link OperatorSpec},
+   * creates the corresponding DAG of {@link OperatorImpl}s, and returns the root {@link OperatorImpl} node.
    *
+   * @param prevOperatorSpec  the parent of the current {@code operatorSpec} in the traversal
    * @param operatorSpec  the operatorSpec to create the {@link OperatorImpl} for
    * @param config  the {@link Config} required to instantiate operators
    * @param context  the {@link TaskContext} required to instantiate operators
-   * @param <M>  type of input message
    * @return  the operator implementation for the operatorSpec
    */
-  private <M> OperatorImpl<M, ?> createAndRegisterOperatorImpl(OperatorSpec operatorSpec,
+  OperatorImpl createAndRegisterOperatorImpl(OperatorSpec prevOperatorSpec, OperatorSpec operatorSpec,
       Config config, TaskContext context) {
-    if (!operatorImpls.containsKey(operatorSpec)) {
-      OperatorImpl<M, ?> operatorImpl = createOperatorImpl(operatorSpec, config, context);
-      if (operatorImpls.putIfAbsent(operatorSpec, operatorImpl) == null) {
-        // this is the first time we've added the operatorImpl corresponding to the operatorSpec,
-        // so traverse and initialize and register the rest of the DAG.
-        // initialize the corresponding operator function
-        operatorImpl.init(config, context);
-        MessageStreamImpl nextStream = operatorSpec.getNextStream();
-        if (nextStream != null) {
-          Collection<OperatorSpec> registeredSpecs = nextStream.getRegisteredOperatorSpecs();
-          registeredSpecs.forEach(registeredSpec -> {
-              OperatorImpl subImpl = createAndRegisterOperatorImpl(registeredSpec, config, context);
-              operatorImpl.registerNextOperator(subImpl);
-            });
-        }
-        return operatorImpl;
-      }
+    if (!operatorImpls.containsKey(operatorSpec) || operatorSpec instanceof JoinOperatorSpec) {
+      // Either this is the first time we've seen this operatorSpec, or this is a join operator spec
+      // and we need to create 2 partial join operator impls for it. Initialize and register the sub-DAG.
+      OperatorImpl operatorImpl = createOperatorImpl(prevOperatorSpec, operatorSpec, config, context);
+      operatorImpl.init(config, context);
+      operatorImpls.put(operatorImpl.getOperatorName(), operatorImpl);
+
+      Collection<OperatorSpec> registeredSpecs = operatorSpec.getRegisteredOperatorSpecs();
+      registeredSpecs.forEach(registeredSpec -> {
+          OperatorImpl nextImpl = createAndRegisterOperatorImpl(operatorSpec, registeredSpec, config, context);
+          operatorImpl.registerNextOperator(nextImpl);
+        });
+      return operatorImpl;
+    } else {
+      // the implementation corresponding to operatorSpec has already been instantiated
+      // and registered, so we do not need to traverse the DAG further.
+      return operatorImpls.get(operatorSpec);
     }
-
-    // the implementation corresponding to operatorSpec has already been instantiated
-    // and registered, so we do not need to traverse the DAG further.
-    return operatorImpls.get(operatorSpec);
   }
 
   /**
@@ -179,20 +155,96 @@ public class OperatorImplGraph {
    * @param operatorSpec  the immutable {@link OperatorSpec} definition.
    * @param config  the {@link Config} required to instantiate operators
    * @param context  the {@link TaskContext} required to instantiate operators
-   * @param <M>  type of input message
    * @return  the {@link OperatorImpl} implementation instance
    */
-  private <M> OperatorImpl<M, ?> createOperatorImpl(OperatorSpec operatorSpec, Config config, TaskContext context) {
-    if (operatorSpec instanceof StreamOperatorSpec) {
-      return new StreamOperatorImpl<>((StreamOperatorSpec<M, ?>) operatorSpec, config, context);
+  OperatorImpl createOperatorImpl(OperatorSpec prevOperatorSpec, OperatorSpec operatorSpec,
+      Config config, TaskContext context) {
+    if (operatorSpec instanceof InputOperatorSpec) {
+      return new InputOperatorImpl((InputOperatorSpec) operatorSpec);
+    } else if (operatorSpec instanceof StreamOperatorSpec) {
+      return new StreamOperatorImpl((StreamOperatorSpec) operatorSpec, config, context);
     } else if (operatorSpec instanceof SinkOperatorSpec) {
-      return new SinkOperatorImpl<>((SinkOperatorSpec<M>) operatorSpec, config, context);
+      return new SinkOperatorImpl((SinkOperatorSpec) operatorSpec, config, context);
+    } else if (operatorSpec instanceof OutputOperatorSpec) {
+      return new OutputOperatorImpl((OutputOperatorSpec) operatorSpec, config, context);
     } else if (operatorSpec instanceof WindowOperatorSpec) {
-      return new WindowOperatorImpl((WindowOperatorSpec<M, ?, ?>) operatorSpec, clock);
-    } else if (operatorSpec instanceof PartialJoinOperatorSpec) {
-      return new PartialJoinOperatorImpl<>((PartialJoinOperatorSpec) operatorSpec, config, context, clock);
+      return new WindowOperatorImpl((WindowOperatorSpec) operatorSpec, clock);
+    } else if (operatorSpec instanceof JoinOperatorSpec) {
+      return createPartialJoinOperatorImpl(prevOperatorSpec, (JoinOperatorSpec) operatorSpec, config, context, clock);
     }
     throw new IllegalArgumentException(
         String.format("Unsupported OperatorSpec: %s", operatorSpec.getClass().getName()));
   }
+
+  private PartialJoinOperatorImpl createPartialJoinOperatorImpl(OperatorSpec prevOperatorSpec,
+      JoinOperatorSpec joinOpSpec, Config config, TaskContext context, Clock clock) {
+    Pair<PartialJoinFunction, PartialJoinFunction> partialJoinFunctions = getOrCreatePartialJoinFunctions(joinOpSpec);
+
+    if (joinOpSpec.getLeftInputOpSpec().equals(prevOperatorSpec)) { // we got here from the left side of the join
+      return new PartialJoinOperatorImpl(joinOpSpec, /* isLeftSide */ true,
+          partialJoinFunctions.getLeft(), partialJoinFunctions.getRight(), config, context, clock);
+    } else { // we got here from the right side of the join
+      return new PartialJoinOperatorImpl(joinOpSpec, /* isLeftSide */ false,
+          partialJoinFunctions.getRight(), partialJoinFunctions.getLeft(), config, context, clock);
+    }
+  }
+
+  private Pair<PartialJoinFunction, PartialJoinFunction> getOrCreatePartialJoinFunctions(JoinOperatorSpec joinOpSpec) {
+    return joinFunctions.computeIfAbsent(joinOpSpec.getOpId(),
+        joinOpId -> Pair.of(createLeftJoinFn(joinOpSpec.getJoinFn()), createRightJoinFn(joinOpSpec.getJoinFn())));
+  }
+
+  private PartialJoinFunction<Object, Object, Object, Object> createLeftJoinFn(JoinFunction joinFn) {
+    return new PartialJoinFunction<Object, Object, Object, Object>() {
+      private KeyValueStore<Object, PartialJoinMessage<Object>> leftStreamState = new InternalInMemoryStore<>();
+
+      @Override
+      public Object apply(Object m, Object jm) {
+        return joinFn.apply(m, jm);
+      }
+
+      @Override
+      public Object getKey(Object message) {
+        return joinFn.getFirstKey(message);
+      }
+
+      @Override
+      public KeyValueStore<Object, PartialJoinMessage<Object>> getState() {
+        return leftStreamState;
+      }
+
+      @Override
+      public void init(Config config, TaskContext context) {
+        // user-defined joinFn should only be initialized once, so we do it only in left partial join function.
+        joinFn.init(config, context);
+      }
+
+      @Override
+      public void close() {
+        // joinFn#close() must only be called once, so we do it it only in left partial join function.
+        joinFn.close();
+      }
+    };
+  }
+
+  private PartialJoinFunction<Object, Object, Object, Object> createRightJoinFn(JoinFunction joinFn) {
+    return new PartialJoinFunction<Object, Object, Object, Object>() {
+      private KeyValueStore<Object, PartialJoinMessage<Object>> rightStreamState = new InternalInMemoryStore<>();
+
+      @Override
+      public Object apply(Object m, Object jm) {
+        return joinFn.apply(jm, m);
+      }
+
+      @Override
+      public Object getKey(Object message) {
+        return joinFn.getSecondKey(message);
+      }
+
+      @Override
+      public KeyValueStore<Object, PartialJoinMessage<Object>> getState() {
+        return rightStreamState;
+      }
+    };
+  }
 }

http://git-wip-us.apache.org/repos/asf/samza/blob/c1c4289c/samza-core/src/main/java/org/apache/samza/operators/impl/OutputOperatorImpl.java
----------------------------------------------------------------------
diff --git a/samza-core/src/main/java/org/apache/samza/operators/impl/OutputOperatorImpl.java b/samza-core/src/main/java/org/apache/samza/operators/impl/OutputOperatorImpl.java
new file mode 100644
index 0000000..fe59b74
--- /dev/null
+++ b/samza-core/src/main/java/org/apache/samza/operators/impl/OutputOperatorImpl.java
@@ -0,0 +1,72 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.samza.operators.impl;
+
+import org.apache.samza.config.Config;
+import org.apache.samza.operators.spec.OperatorSpec;
+import org.apache.samza.operators.spec.OutputOperatorSpec;
+import org.apache.samza.operators.spec.OutputStreamImpl;
+import org.apache.samza.system.OutgoingMessageEnvelope;
+import org.apache.samza.system.SystemStream;
+import org.apache.samza.task.MessageCollector;
+import org.apache.samza.task.TaskContext;
+import org.apache.samza.task.TaskCoordinator;
+
+import java.util.Collection;
+import java.util.Collections;
+
+
+/**
+ * An operator that sends incoming messages to an output {@link SystemStream}.
+ */
+class OutputOperatorImpl<M> extends OperatorImpl<M, Void> {
+
+  private final OutputOperatorSpec<M> outputOpSpec;
+  private final OutputStreamImpl<?, ?, M> outputStream;
+
+  OutputOperatorImpl(OutputOperatorSpec<M> outputOpSpec, Config config, TaskContext context) {
+    this.outputOpSpec = outputOpSpec;
+    this.outputStream = outputOpSpec.getOutputStream();
+  }
+
+  @Override
+  protected void handleInit(Config config, TaskContext context) {
+  }
+
+  @Override
+  public Collection<Void> handleMessage(M message, MessageCollector collector,
+      TaskCoordinator coordinator) {
+    // TODO: SAMZA-1148 - need to find a way to directly pass in the serde class names
+    SystemStream systemStream = new SystemStream(outputStream.getStreamSpec().getSystemName(),
+        outputStream.getStreamSpec().getPhysicalName());
+    Object key = outputStream.getKeyExtractor().apply(message);
+    Object msg = outputStream.getMsgExtractor().apply(message);
+    collector.send(new OutgoingMessageEnvelope(systemStream, key, msg));
+    return Collections.emptyList();
+  }
+
+  @Override
+  protected void handleClose() {
+  }
+
+  @Override
+  protected OperatorSpec<M, Void> getOperatorSpec() {
+    return outputOpSpec;
+  }
+}

http://git-wip-us.apache.org/repos/asf/samza/blob/c1c4289c/samza-core/src/main/java/org/apache/samza/operators/impl/PartialJoinOperatorImpl.java
----------------------------------------------------------------------
diff --git a/samza-core/src/main/java/org/apache/samza/operators/impl/PartialJoinOperatorImpl.java b/samza-core/src/main/java/org/apache/samza/operators/impl/PartialJoinOperatorImpl.java
index b00a2e9..ad66962 100644
--- a/samza-core/src/main/java/org/apache/samza/operators/impl/PartialJoinOperatorImpl.java
+++ b/samza-core/src/main/java/org/apache/samza/operators/impl/PartialJoinOperatorImpl.java
@@ -22,8 +22,8 @@ import org.apache.samza.config.Config;
 import org.apache.samza.metrics.Counter;
 import org.apache.samza.operators.functions.PartialJoinFunction;
 import org.apache.samza.operators.functions.PartialJoinFunction.PartialJoinMessage;
+import org.apache.samza.operators.spec.JoinOperatorSpec;
 import org.apache.samza.operators.spec.OperatorSpec;
-import org.apache.samza.operators.spec.PartialJoinOperatorSpec;
 import org.apache.samza.storage.kv.Entry;
 import org.apache.samza.storage.kv.KeyValueIterator;
 import org.apache.samza.storage.kv.KeyValueStore;
@@ -31,8 +31,6 @@ import org.apache.samza.task.MessageCollector;
 import org.apache.samza.task.TaskContext;
 import org.apache.samza.task.TaskCoordinator;
 import org.apache.samza.util.Clock;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
 import java.util.ArrayList;
 import java.util.Collection;
@@ -40,18 +38,18 @@ import java.util.Collections;
 import java.util.List;
 
 /**
- * Implementation of a {@link PartialJoinOperatorSpec} that joins messages of type {@code M} in this stream
- * with buffered messages of type {@code JM} in the other stream.
+ * Implementation of one side of a {@link JoinOperatorSpec} that buffers and joins its input messages of
+ * type {@code M} with buffered input messages of type {@code JM} in the paired {@link PartialJoinOperatorImpl}.
  *
- * @param <M>  type of messages in the input stream
- * @param <JM>  type of messages in the stream to join with
- * @param <RM>  type of messages in the joined stream
+ * @param <K> the type of join key
+ * @param <M> the type of input messages on this side of the join
+ * @param <JM> the type of input message on the other side of the join
+ * @param <RM> the type of join result
  */
 class PartialJoinOperatorImpl<K, M, JM, RM> extends OperatorImpl<M, RM> {
 
-  private static final Logger LOGGER = LoggerFactory.getLogger(PartialJoinOperatorImpl.class);
-
-  private final PartialJoinOperatorSpec<K, M, JM, RM> partialJoinOpSpec;
+  private final JoinOperatorSpec<K, M, JM, RM> joinOpSpec;
+  private final boolean isLeftSide; // whether this operator impl is for the left side of the join
   private final PartialJoinFunction<K, M, JM, RM> thisPartialJoinFn;
   private final PartialJoinFunction<K, JM, M, RM> otherPartialJoinFn;
   private final long ttlMs;
@@ -59,19 +57,22 @@ class PartialJoinOperatorImpl<K, M, JM, RM> extends OperatorImpl<M, RM> {
 
   private Counter keysRemoved;
 
-  PartialJoinOperatorImpl(PartialJoinOperatorSpec<K, M, JM, RM> partialJoinOpSpec,
+  PartialJoinOperatorImpl(JoinOperatorSpec<K, M, JM, RM> joinOpSpec, boolean isLeftSide,
+      PartialJoinFunction<K, M, JM, RM> thisPartialJoinFn,
+      PartialJoinFunction<K, JM, M, RM> otherPartialJoinFn,
       Config config, TaskContext context, Clock clock) {
-    this.partialJoinOpSpec = partialJoinOpSpec;
-    this.thisPartialJoinFn = partialJoinOpSpec.getThisPartialJoinFn();
-    this.otherPartialJoinFn = partialJoinOpSpec.getOtherPartialJoinFn();
-    this.ttlMs = partialJoinOpSpec.getTtlMs();
+    this.joinOpSpec = joinOpSpec;
+    this.isLeftSide = isLeftSide;
+    this.thisPartialJoinFn = thisPartialJoinFn;
+    this.otherPartialJoinFn = otherPartialJoinFn;
+    this.ttlMs = joinOpSpec.getTtlMs();
     this.clock = clock;
   }
 
   @Override
   protected void handleInit(Config config, TaskContext context) {
     keysRemoved = context.getMetricsRegistry()
-        .newCounter(OperatorImpl.class.getName(), this.partialJoinOpSpec.getOpName() + "-keys-removed");
+        .newCounter(OperatorImpl.class.getName(), getOperatorName() + "-keys-removed");
     this.thisPartialJoinFn.init(config, context);
   }
 
@@ -116,8 +117,19 @@ class PartialJoinOperatorImpl<K, M, JM, RM> extends OperatorImpl<M, RM> {
     this.thisPartialJoinFn.close();
   }
 
+  protected OperatorSpec<M, RM> getOperatorSpec() {
+    return (OperatorSpec<M, RM>) joinOpSpec;
+  }
+
+  /**
+   * The name for this {@link PartialJoinOperatorImpl} that includes information about which
+   * side of the join it is for.
+   *
+   * @return the {@link PartialJoinOperatorImpl} name.
+   */
   @Override
-  protected OperatorSpec<RM> getOperatorSpec() {
-    return partialJoinOpSpec;
+  protected String getOperatorName() {
+    String side = isLeftSide ? "L" : "R";
+    return this.joinOpSpec.getOpName() + "-" + side;
   }
 }

http://git-wip-us.apache.org/repos/asf/samza/blob/c1c4289c/samza-core/src/main/java/org/apache/samza/operators/impl/RootOperatorImpl.java
----------------------------------------------------------------------
diff --git a/samza-core/src/main/java/org/apache/samza/operators/impl/RootOperatorImpl.java b/samza-core/src/main/java/org/apache/samza/operators/impl/RootOperatorImpl.java
deleted file mode 100644
index 45cb941..0000000
--- a/samza-core/src/main/java/org/apache/samza/operators/impl/RootOperatorImpl.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.samza.operators.impl;
-
-import org.apache.samza.config.Config;
-import org.apache.samza.operators.MessageStreamImpl;
-import org.apache.samza.operators.spec.OperatorSpec;
-import org.apache.samza.task.MessageCollector;
-import org.apache.samza.task.TaskContext;
-import org.apache.samza.task.TaskCoordinator;
-
-import java.util.Collection;
-import java.util.Collections;
-
-
-/**
- * A no-op operator implementation that forwards incoming messages to all of its subscribers.
- * @param <M>  type of incoming messages
- */
-public final class RootOperatorImpl<M> extends OperatorImpl<M, M> {
-
-  @Override
-  protected void handleInit(Config config, TaskContext context) {
-  }
-
-  @Override
-  public Collection<M> handleMessage(M message, MessageCollector collector, TaskCoordinator coordinator) {
-    return Collections.singletonList(message);
-  }
-
-  @Override
-  protected void handleClose() {
-  }
-
-  // TODO: SAMZA-1221 - Change to InputOperatorSpec that also builds the message
-  @Override
-  protected OperatorSpec<M> getOperatorSpec() {
-    return new OperatorSpec<M>() {
-      @Override
-      public MessageStreamImpl<M> getNextStream() {
-        return null;
-      }
-
-      @Override
-      public OpCode getOpCode() {
-        return OpCode.INPUT;
-      }
-
-      @Override
-      public int getOpId() {
-        return -1;
-      }
-
-      @Override
-      public String getSourceLocation() {
-        return "";
-      }
-    };
-  }
-}

http://git-wip-us.apache.org/repos/asf/samza/blob/c1c4289c/samza-core/src/main/java/org/apache/samza/operators/impl/SinkOperatorImpl.java
----------------------------------------------------------------------
diff --git a/samza-core/src/main/java/org/apache/samza/operators/impl/SinkOperatorImpl.java b/samza-core/src/main/java/org/apache/samza/operators/impl/SinkOperatorImpl.java
index 4f698f8..5dbe27f 100644
--- a/samza-core/src/main/java/org/apache/samza/operators/impl/SinkOperatorImpl.java
+++ b/samza-core/src/main/java/org/apache/samza/operators/impl/SinkOperatorImpl.java
@@ -31,9 +31,9 @@ import java.util.Collections;
 
 
 /**
- * Implementation for {@link SinkOperatorSpec}
+ * An operator that sends incoming messages to an arbitrary output system using the provided {@link SinkFunction}.
  */
-class SinkOperatorImpl<M> extends OperatorImpl<M, M> {
+class SinkOperatorImpl<M> extends OperatorImpl<M, Void> {
 
   private final SinkOperatorSpec<M> sinkOpSpec;
   private final SinkFunction<M> sinkFn;
@@ -49,7 +49,7 @@ class SinkOperatorImpl<M> extends OperatorImpl<M, M> {
   }
 
   @Override
-  public Collection<M> handleMessage(M message, MessageCollector collector,
+  public Collection<Void> handleMessage(M message, MessageCollector collector,
       TaskCoordinator coordinator) {
     this.sinkFn.apply(message, collector, coordinator);
     // there should be no further chained operators since this is a terminal operator.
@@ -61,8 +61,7 @@ class SinkOperatorImpl<M> extends OperatorImpl<M, M> {
     this.sinkFn.close();
   }
 
-  @Override
-  protected OperatorSpec<M> getOperatorSpec() {
+  protected OperatorSpec<M, Void> getOperatorSpec() {
     return sinkOpSpec;
   }
 }

http://git-wip-us.apache.org/repos/asf/samza/blob/c1c4289c/samza-core/src/main/java/org/apache/samza/operators/impl/StreamOperatorImpl.java
----------------------------------------------------------------------
diff --git a/samza-core/src/main/java/org/apache/samza/operators/impl/StreamOperatorImpl.java b/samza-core/src/main/java/org/apache/samza/operators/impl/StreamOperatorImpl.java
index e720803..a51d5e6 100644
--- a/samza-core/src/main/java/org/apache/samza/operators/impl/StreamOperatorImpl.java
+++ b/samza-core/src/main/java/org/apache/samza/operators/impl/StreamOperatorImpl.java
@@ -30,10 +30,10 @@ import java.util.Collection;
 
 
 /**
- * A StreamOperator that accepts a 1:n transform function and applies it to each incoming message.
+ * A simple operator that accepts a 1:n transform function and applies it to each incoming message.
  *
- * @param <M>  type of message in the input stream
- * @param <RM>  type of message in the output stream
+ * @param <M>  the type of input message
+ * @param <RM>  the type of result
  */
 class StreamOperatorImpl<M, RM> extends OperatorImpl<M, RM> {
 
@@ -62,8 +62,7 @@ class StreamOperatorImpl<M, RM> extends OperatorImpl<M, RM> {
     this.transformFn.close();
   }
 
-  @Override
-  protected OperatorSpec<RM> getOperatorSpec() {
+  protected OperatorSpec<M, RM> getOperatorSpec() {
     return streamOpSpec;
   }
 }

http://git-wip-us.apache.org/repos/asf/samza/blob/c1c4289c/samza-core/src/main/java/org/apache/samza/operators/impl/WindowOperatorImpl.java
----------------------------------------------------------------------
diff --git a/samza-core/src/main/java/org/apache/samza/operators/impl/WindowOperatorImpl.java b/samza-core/src/main/java/org/apache/samza/operators/impl/WindowOperatorImpl.java
index b258042..f9485f7 100644
--- a/samza-core/src/main/java/org/apache/samza/operators/impl/WindowOperatorImpl.java
+++ b/samza-core/src/main/java/org/apache/samza/operators/impl/WindowOperatorImpl.java
@@ -21,7 +21,6 @@
 package org.apache.samza.operators.impl;
 
 import org.apache.samza.config.Config;
-import org.apache.samza.operators.WindowState;
 import org.apache.samza.operators.spec.OperatorSpec;
 import org.apache.samza.operators.spec.WindowOperatorSpec;
 import org.apache.samza.operators.triggers.FiringType;
@@ -154,7 +153,7 @@ public class WindowOperatorImpl<M, WK, WV> extends OperatorImpl<M, WindowPane<WK
   }
 
   @Override
-  protected OperatorSpec<WindowPane<WK, WV>> getOperatorSpec() {
+  protected OperatorSpec<M, WindowPane<WK, WV>> getOperatorSpec() {
     return windowOpSpec;
   }
 

http://git-wip-us.apache.org/repos/asf/samza/blob/c1c4289c/samza-core/src/main/java/org/apache/samza/operators/impl/WindowState.java
----------------------------------------------------------------------
diff --git a/samza-core/src/main/java/org/apache/samza/operators/impl/WindowState.java b/samza-core/src/main/java/org/apache/samza/operators/impl/WindowState.java
new file mode 100644
index 0000000..4577a5c
--- /dev/null
+++ b/samza-core/src/main/java/org/apache/samza/operators/impl/WindowState.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.samza.operators.impl;
+
+/**
+ * Wraps the value stored for a particular {@link org.apache.samza.operators.windows.WindowKey} with additional metadata.
+ */
+class WindowState<WV> {
+
+  private final WV wv;
+  /**
+   * Time of the first message in the window
+   */
+  private final long earliestRecvTime;
+
+  WindowState(WV wv, long earliestRecvTime) {
+    this.wv = wv;
+    this.earliestRecvTime = earliestRecvTime;
+  }
+
+  WV getWindowValue() {
+    return wv;
+  }
+
+  long getEarliestTimestamp() {
+    return earliestRecvTime;
+  }
+
+  @Override
+  public String toString() {
+    return String.format("WindowState: {time=%d, value=%s}", earliestRecvTime, wv);
+  }
+}

http://git-wip-us.apache.org/repos/asf/samza/blob/c1c4289c/samza-core/src/main/java/org/apache/samza/operators/spec/InputOperatorSpec.java
----------------------------------------------------------------------
diff --git a/samza-core/src/main/java/org/apache/samza/operators/spec/InputOperatorSpec.java b/samza-core/src/main/java/org/apache/samza/operators/spec/InputOperatorSpec.java
new file mode 100644
index 0000000..6fbc3c1
--- /dev/null
+++ b/samza-core/src/main/java/org/apache/samza/operators/spec/InputOperatorSpec.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.samza.operators.spec;
+
+import org.apache.commons.lang3.tuple.Pair;
+import org.apache.samza.system.StreamSpec;
+
+import java.util.function.BiFunction;
+
+/**
+ * The spec for an operator that receives incoming messages from an input stream
+ * and converts them to the input message.
+ *
+ * @param <K> the type of key in the incoming message
+ * @param <V> the type of message in the incoming message
+ * @param <M> the type of input message
+ */
+public class InputOperatorSpec<K, V, M> extends OperatorSpec<Pair<K, V>, M> {
+
+  private final StreamSpec streamSpec;
+  private final BiFunction<K, V, M> msgBuilder;
+
+  public InputOperatorSpec(StreamSpec streamSpec, BiFunction<K, V, M> msgBuilder, int opId) {
+    super(OpCode.INPUT, opId);
+    this.streamSpec = streamSpec;
+    this.msgBuilder = msgBuilder;
+  }
+
+  public StreamSpec getStreamSpec() {
+    return this.streamSpec;
+  }
+
+  public BiFunction<K, V, M> getMsgBuilder() {
+    return this.msgBuilder;
+  }
+}