Repository navigation
Conversation
Reviewer's GuideIntroduced worker modules to handle data serialization, Spark session management, HDFS interactions, and compute pipelines: DataSerializer orchestrates CSV-to-parquet conversion and storage in HDFS, HadoopManager wraps HDFS read/write operations, SparkManager manages SparkSession lifecycle, and Compute performs average aggregation and writes results back to HDFS. Sequence diagram for data serialization and storage to HDFSsequenceDiagram
participant User
participant DataSerializer
participant SparkManager
participant HadoopManager
User->>DataSerializer: read_data_to_hdfs()
DataSerializer->>SparkManager: create_spark_session()
DataSerializer->>SparkManager: read CSV(s)
DataSerializer->>DataSerializer: combine DataFrames
DataSerializer->>DataSerializer: serialize_to_parquet(combined_data)
DataSerializer->>HadoopManager: save_as_hdfs(parquet_data)
HadoopManager->>HadoopManager: write_to_hdfs()
HadoopManager->>HDFS: upload parquet file
Sequence diagram for compute average and write result to HDFSsequenceDiagram
participant User
participant Compute
participant SparkManager
participant HadoopManager
User->>Compute: compute_average()
Compute->>SparkManager: create_spark_session()
Compute->>SparkManager: read parquet from HDFS
Compute->>Compute: aggregate (average) numeric columns
Compute->>HadoopManager: write_to_hdfs(means, DATA_OUTPUT_PATH)
HadoopManager->>HDFS: upload result
Class diagram for new worker modules (DataSerializer, HadoopManager, SparkManager, Compute)classDiagram
class DataSerializer {
- data_paths: list
- combined_data
- spark
+ __init__(data_paths: list)
+ read_data_to_hdfs() DataFrame
+ serialize_to_parquet(data: str)
+ save_as_hdfs(data)
}
class HadoopManager {
- hadoop_client
- spark
+ __init__()
+ write_to_hdfs()
+ read_from_hdfs()
}
class SparkManager {
- NAME_MASTER_NODE: str
- APP_NAME: str
+ __init__(NAME_MASTER_NODE: str, APP_NAME: str)
+ create_spark_session() object
+ stop_spark_session()
}
class Compute {
- DATA_PATH: str
- DATA_OUTPUT_PATH
- spark
+ __init__(DATA_PATH: str)
+ compute_average()
}
DataSerializer --> SparkManager : uses
DataSerializer --> HadoopManager : uses
HadoopManager --> SparkManager : uses
Compute --> SparkManager : uses
Compute --> HadoopManager : uses
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey @mintesin - I've reviewed your changes and found some issues that need to be addressed.
Blocking issues:
- Missing 'path' parameter in 'write_to_hdfs' method. (link)
- Undefined attribute 'HADOOP_OUTPUT_PATH' in 'read_from_hdfs'. (link)
- DATA_OUTPUT_PATH is used but not defined or passed to init. (link)
- Reference to undefined variable 'df' and incorrect attribute 'Schema'. (link)
- Typo in method name: 'alais' should be 'alias'. (link)
- Incorrect dictionary comprehension syntax for 'means'. (link)
- Incorrect usage of 'write_to_hdfs' as a class method. (link)
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location> `worker/DataSerializer.py:35` </location>
<code_context>
+ print(f"There has been an error in reading and combining {self.combined_data}: {e}")
+
+ # Saving the data aas a paquet file and finally returning parquet temporary file
+ def serialize_to_parquet(self, data: str):
+ try:
+ if self.combined_data is not None:
</code_context>
<issue_to_address>
The 'data' parameter type should be DataFrame, not str.
Update the type annotation to 'DataFrame' to match the expected input and avoid confusion.
Suggested implementation:
```python
def serialize_to_parquet(self, data: DataFrame):
```
You may need to import `DataFrame` at the top of your file if it is not already imported:
```python
from pyspark.sql import DataFrame
```
</issue_to_address>
### Comment 2
<location> `worker/DataSerializer.py:41` </location>
<code_context>
+ with tempfile.TemporaryDirectory() as tempdir:
+ print(f"Writing to temp path: {tempdir}")
+ data.write.mode('overwrite').parquet(tempdir)
+ parquet_data = self.spark.parquet(tempdir)
+ self.save_as_hdfs(parquet_data)
+
</code_context>
<issue_to_address>
Incorrect method usage: 'self.spark.parquet' is not a valid SparkSession method.
Use 'self.spark.read.parquet(tempdir)' instead to read the Parquet file; the current code will raise an AttributeError.
</issue_to_address>
### Comment 3
<location> `worker/HadoopManager.py:32` </location>
<code_context>
+ self.spark = SparkManager.create_spark_session()
+
+ # writing temporarly saved parquet data to hadoop
+ def write_to_hdfs(self):
+ try:
+ parquet_data = self.spark.read.parquet(path)
</code_context>
<issue_to_address>
Missing 'path' parameter in 'write_to_hdfs' method.
'path' is used in the method but is neither defined nor passed in, which will cause a NameError. Please add 'path' as a parameter to the method.
</issue_to_address>
### Comment 4
<location> `worker/HadoopManager.py:43` </location>
<code_context>
+ #reading parquet data from hadoop
+ def read_from_hdfs(self):
+ try:
+ data = self.spark.read.parquet(self.HADOOP_OUTPUT_PATH)
+ return data
+ except Exception as e:
</code_context>
<issue_to_address>
Undefined attribute 'HADOOP_OUTPUT_PATH' in 'read_from_hdfs'.
Referencing 'self.HADOOP_OUTPUT_PATH' without defining it will raise an AttributeError. Please define this attribute or ensure it is set before use.
</issue_to_address>
### Comment 5
<location> `worker/Compute.py:14` </location>
<code_context>
+import json, pathlib
+
+class Compute:
+ def __init__(self,DATA_PATH:str):
+ self.DATA_PATH = DATA_PATH
+ self.DATA_OUTPUT_PATH = DATA_OUTPUT_PATH
+ self.spark = SparkManager.create_spark_session()
</code_context>
<issue_to_address>
DATA_OUTPUT_PATH is used but not defined or passed to __init__.
'DATA_OUTPUT_PATH' is not defined or passed to '__init__', which will cause a NameError. Please add it as a parameter to the constructor.
</issue_to_address>
### Comment 6
<location> `worker/Compute.py:23` </location>
<code_context>
+ try:
+ data_frame = self.spark.read.parquet(self.DATA_PATH)
+ if data_frame is not None:
+ numeric_cols = [f.name for f in df.Schema.fields
+ if f.dataType.typeName() in {"double", "float", "long", "integer"}
+ ]
</code_context>
<issue_to_address>
Reference to undefined variable 'df' and incorrect attribute 'Schema'.
Use 'data_frame.schema.fields' instead of 'df.Schema.fields' to reference the correct variable and attribute.
</issue_to_address>
### Comment 7
<location> `worker/Compute.py:26` </location>
<code_context>
+ numeric_cols = [f.name for f in df.Schema.fields
+ if f.dataType.typeName() in {"double", "float", "long", "integer"}
+ ]
+ aggregate_row = data_frame.agg(*[F.avg(c).alais(c) for c in numeric_cols]).first()
+ means = {c:float(aggregate_row[c] for c in numeric_cols)}
+ json_data = json.dumps(means)
</code_context>
<issue_to_address>
Typo in method name: 'alais' should be 'alias'.
Using 'alais' instead of 'alias' will result in an AttributeError at runtime.
</issue_to_address>
<suggested_fix>
<<<<<<< SEARCH
aggregate_row = data_frame.agg(*[F.avg(c).alais(c) for c in numeric_cols]).first()
=======
aggregate_row = data_frame.agg(*[F.avg(c).alias(c) for c in numeric_cols]).first()
>>>>>>> REPLACE
</suggested_fix>
### Comment 8
<location> `worker/Compute.py:27` </location>
<code_context>
+ if f.dataType.typeName() in {"double", "float", "long", "integer"}
+ ]
+ aggregate_row = data_frame.agg(*[F.avg(c).alais(c) for c in numeric_cols]).first()
+ means = {c:float(aggregate_row[c] for c in numeric_cols)}
+ json_data = json.dumps(means)
+ HadoopManager.write_to_hdfs(means, self.DATA_OUTPUT_PATH)
</code_context>
<issue_to_address>
Incorrect dictionary comprehension syntax for 'means'.
The current syntax will cause a SyntaxError. Use '{c: float(aggregate_row[c]) for c in numeric_cols}' instead.
</issue_to_address>
### Comment 9
<location> `worker/Compute.py:29` </location>
<code_context>
+ aggregate_row = data_frame.agg(*[F.avg(c).alais(c) for c in numeric_cols]).first()
+ means = {c:float(aggregate_row[c] for c in numeric_cols)}
+ json_data = json.dumps(means)
+ HadoopManager.write_to_hdfs(means, self.DATA_OUTPUT_PATH)
+ print(f"Data aggreagtion has been successfully done and saved to {self.DATA_OUTPUT_PATH}")
+ else:
</code_context>
<issue_to_address>
Incorrect usage of 'write_to_hdfs' as a class method.
Instantiate HadoopManager and call 'write_to_hdfs' on the instance instead of the class.
</issue_to_address>
### Comment 10
<location> `worker/SparkManager.py:11` </location>
<code_context>
+from pyspark.sql import SparkSession
+
+class SparkManager:
+ def __init__(self,NAME_MASTER_NODE: str, APP_NAME: str):
+ self.NAME_MASTER_NODE = 'bigdatamaster'
+ self.APP_NAME = 'bigdataproject'
+ # Creating spark session with master node names as bigdataproject
+ def create_spark_session(self)-> object:
</code_context>
<issue_to_address>
Constructor parameters are ignored and hardcoded values are used.
The __init__ method should use the provided parameters instead of hardcoded values to maintain flexibility and avoid redundancy.
</issue_to_address>
<suggested_fix>
<<<<<<< SEARCH
def __init__(self,NAME_MASTER_NODE: str, APP_NAME: str):
self.NAME_MASTER_NODE = 'bigdatamaster'
self.APP_NAME = 'bigdataproject'
=======
def __init__(self, NAME_MASTER_NODE: str, APP_NAME: str):
self.NAME_MASTER_NODE = NAME_MASTER_NODE
self.APP_NAME = APP_NAME
>>>>>>> REPLACE
</suggested_fix>
### Comment 11
<location> `worker/SparkManager.py:31` </location>
<code_context>
+ # Stopping the session whith master named as "bigdataproject"
+ def stop_spark_session(self):
+ try:
+ current_spark_session = SparkSession.active()
+ except Exception as e:
+ print(f"There is no active session running with app name {self.APP_NAME}",e)
</code_context>
<issue_to_address>
Potential issue with stopping Spark session if none is active.
Ensure 'current_spark_session.stop()' is only called if a session exists to prevent exceptions.
</issue_to_address>
### Comment 12
<location> `worker/HadoopManager.py:26` </location>
<code_context>
+
+from SparkManager import SparkManager
+
+class HadoopManager:
+ def __init__(self):
+ self.hadoop_client = InsecureClient(hdfs_url,user="root")
</code_context>
<issue_to_address>
Consider refactoring HadoopManager to separate concerns, use explicit method parameters, and inject dependencies via the constructor.
```python
# Split responsibilities & make interfaces explicit:
from hdfs import InsecureClient
from pyspark.sql import DataFrame, SparkSession
class HadoopManager:
def __init__(self, spark: SparkSession, hdfs_url: str, user: str = "root"):
self.spark = spark
self.client = InsecureClient(hdfs_url, user=user)
def write_dataframe(self, df: DataFrame, hdfs_path: str) -> None:
"""
Persist a Spark DataFrame to HDFS via Spark’s native API.
"""
df.write.mode("overwrite").parquet(hdfs_path)
def read_dataframe(self, hdfs_path: str) -> DataFrame:
"""
Load a Spark DataFrame from HDFS.
"""
return self.spark.read.parquet(hdfs_path)
def upload_file(self, local_path: str, hdfs_path: str) -> None:
"""
Upload a single local file to HDFS via the hdfs client.
"""
self.client.upload(hdfs_path, local_path)
```
Actionable steps:
1. Remove parameterless `write_to_hdfs` / `read_from_hdfs` and undefined `path` / `HADOOP_OUTPUT_PATH`.
2. Use `write_dataframe(df, hdfs_path)` and `read_dataframe(hdfs_path)` so callers supply both DataFrame and target path.
3. If you really need raw-file upload, keep `upload_file(local, hdfs)` as a distinct method.
4. Drop juggling Spark reads/writes with client uploads in one method – each method now does a single, well-scoped task.
5. Inject `SparkSession` & `hdfs_url` via constructor to avoid globals and improve testability.
</issue_to_address>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
| print(f"There has been an error in reading and combining {self.combined_data}: {e}") | ||
|
|
||
| # Saving the data aas a paquet file and finally returning parquet temporary file | ||
| def serialize_to_parquet(self, data: str): |
There was a problem hiding this comment.
suggestion: The 'data' parameter type should be DataFrame, not str.
Update the type annotation to 'DataFrame' to match the expected input and avoid confusion.
Suggested implementation:
def serialize_to_parquet(self, data: DataFrame):You may need to import DataFrame at the top of your file if it is not already imported:
from pyspark.sql import DataFrame| with tempfile.TemporaryDirectory() as tempdir: | ||
| print(f"Writing to temp path: {tempdir}") | ||
| data.write.mode('overwrite').parquet(tempdir) | ||
| parquet_data = self.spark.parquet(tempdir) |
There was a problem hiding this comment.
issue (bug_risk): Incorrect method usage: 'self.spark.parquet' is not a valid SparkSession method.
Use 'self.spark.read.parquet(tempdir)' instead to read the Parquet file; the current code will raise an AttributeError.
| self.spark = SparkManager.create_spark_session() | ||
|
|
||
| # writing temporarly saved parquet data to hadoop | ||
| def write_to_hdfs(self): |
There was a problem hiding this comment.
issue (bug_risk): Missing 'path' parameter in 'write_to_hdfs' method.
'path' is used in the method but is neither defined nor passed in, which will cause a NameError. Please add 'path' as a parameter to the method.
| #reading parquet data from hadoop | ||
| def read_from_hdfs(self): | ||
| try: | ||
| data = self.spark.read.parquet(self.HADOOP_OUTPUT_PATH) |
There was a problem hiding this comment.
issue (bug_risk): Undefined attribute 'HADOOP_OUTPUT_PATH' in 'read_from_hdfs'.
Referencing 'self.HADOOP_OUTPUT_PATH' without defining it will raise an AttributeError. Please define this attribute or ensure it is set before use.
| def __init__(self,DATA_PATH:str): | ||
| self.DATA_PATH = DATA_PATH |
There was a problem hiding this comment.
issue (bug_risk): DATA_OUTPUT_PATH is used but not defined or passed to init.
'DATA_OUTPUT_PATH' is not defined or passed to 'init', which will cause a NameError. Please add it as a parameter to the constructor.
|
|
||
| from SparkManager import SparkManager | ||
|
|
||
| class HadoopManager: |
There was a problem hiding this comment.
issue (complexity): Consider refactoring HadoopManager to separate concerns, use explicit method parameters, and inject dependencies via the constructor.
# Split responsibilities & make interfaces explicit:
from hdfs import InsecureClient
from pyspark.sql import DataFrame, SparkSession
class HadoopManager:
def __init__(self, spark: SparkSession, hdfs_url: str, user: str = "root"):
self.spark = spark
self.client = InsecureClient(hdfs_url, user=user)
def write_dataframe(self, df: DataFrame, hdfs_path: str) -> None:
"""
Persist a Spark DataFrame to HDFS via Spark’s native API.
"""
df.write.mode("overwrite").parquet(hdfs_path)
def read_dataframe(self, hdfs_path: str) -> DataFrame:
"""
Load a Spark DataFrame from HDFS.
"""
return self.spark.read.parquet(hdfs_path)
def upload_file(self, local_path: str, hdfs_path: str) -> None:
"""
Upload a single local file to HDFS via the hdfs client.
"""
self.client.upload(hdfs_path, local_path)Actionable steps:
- Remove parameterless
write_to_hdfs/read_from_hdfsand undefinedpath/HADOOP_OUTPUT_PATH. - Use
write_dataframe(df, hdfs_path)andread_dataframe(hdfs_path)so callers supply both DataFrame and target path. - If you really need raw-file upload, keep
upload_file(local, hdfs)as a distinct method. - Drop juggling Spark reads/writes with client uploads in one method – each method now does a single, well-scoped task.
- Inject
SparkSession&hdfs_urlvia constructor to avoid globals and improve testability.
| try: | ||
| data_frame = self.spark.read.parquet(self.DATA_PATH) | ||
| if data_frame is not None: | ||
| numeric_cols = [f.name for f in df.Schema.fields |
There was a problem hiding this comment.
issue (code-quality): We've found these issues:
- Extract code out into method (
extract-method) - Replace f-string with no interpolated values with string [×2] (
remove-redundant-fstring)
| if i == 0: | ||
| self.combined_data = df | ||
| else: | ||
| self.combined_data = self.combined_data.unionByName(df) |
There was a problem hiding this comment.
issue (code-quality): Replace if statement with if expression (assign-if-exp)
|
|
||
| else: | ||
| pass |
There was a problem hiding this comment.
suggestion (code-quality): Remove redundant pass statement (remove-redundant-pass)
| else: | |
| pass |
| data = self.spark.read.parquet(self.HADOOP_OUTPUT_PATH) | ||
| return data |
There was a problem hiding this comment.
suggestion (code-quality): Inline variable that is immediately returned (inline-immediately-returned-variable)
| data = self.spark.read.parquet(self.HADOOP_OUTPUT_PATH) | |
| return data | |
| return self.spark.read.parquet(self.HADOOP_OUTPUT_PATH) |
The logic of Hadoop and Spark connection and connection management is defined. Besides, there is some data serializer logic added.
Summary by Sourcery
Introduce core worker components for Spark and Hadoop integration, including data serialization, HDFS management, and computation workflows
New Features:
Chores: