Skip to content

some additional code snippet added - #4

Merged
mintesin merged 1 commit into
mainfrom
mybranch
Aug 3, 2025
Merged

mintesin merged 1 commit into
mainfrom
mybranch

Conversation

@mintesin

@mintesin mintesin commented Aug 3, 2025 •

Copy link
Copy Markdown
Owner

Summary by Sourcery

Implement a distributed search worker node framework using ZooKeeper for coordination and TF-IDF for document ranking

New Features:

  • Add Application entry point to manage ZooKeeper connection, leader election, and service lifecycle
  • Introduce LeaderElection and ServiceRegistry classes for ZooKeeper-based leader election and service discovery
  • Add OnElectionCallback interface and OnElectionAction to handle leader vs worker behavior
  • Implement TF-IDF module and SearchWorker for processing search tasks and computing document scores
  • Provide Aggregator for asynchronously dispatching tasks to worker nodes
  • Add DocumentData and Result models to store term frequencies and search results

@sourcery-ai

sourcery-ai Bot commented Aug 3, 2025 •

Copy link
Copy Markdown

Reviewer's Guide

This PR implements a complete distributed search worker node by introducing an Application entry point that coordinates ZooKeeper connectivity, leader election, and service lifecycle; adds Kazoo-based leader election and service registry modules; defines election callback actions; provides a TF-IDF-driven search worker; and includes supporting data models and an asynchronous task aggregator.

Sequence diagram for leader election and service registration on application startup

sequenceDiagram
    participant App as Application
    participant ZK as KazooClient
    participant SR as ServiceRegistry
    participant OEA as OnElectionAction
    participant LE as LeaderElection
    App->>ZK: connect_to_zookeeper()
    ZK-->>App: connection established
    App->>SR: ServiceRegistry(zk, WORKERS_REGISTRY_ZNODE)
    App->>OEA: OnElectionAction(service_registry, port)
    App->>LE: LeaderElection(zk, on_election_action)
    LE->>ZK: volunteer_for_leadership() (create ephemeral sequential znode)
    LE->>ZK: reelect_leader() (get children, determine leader)
    alt If leader
        LE->>OEA: on_elected_to_be_leader()
        OEA->>SR: unregister_from_cluster()
        OEA->>SR: register_for_updates()
    else If worker
        LE->>OEA: on_worker()
        OEA->>SR: register_to_cluster(current_server_address)
    end
Loading

Entity relationship diagram for ZooKeeper znodes used in leader election and service registry

erDiagram
    ZOOKEEPER ||--o{ ELECTION : contains
    ZOOKEEPER ||--o{ WORKERS_SERVICE_REGISTRY : contains
    ZOOKEEPER ||--o{ COORDINATORS_SERVICE_REGISTRY : contains
    ELECTION {
        string c_* "Ephemeral sequential znodes for candidates"
    }
    WORKERS_SERVICE_REGISTRY {
        string n_* "Ephemeral sequential znodes for workers"
    }
    COORDINATORS_SERVICE_REGISTRY {
        string n_* "Ephemeral sequential znodes for coordinators"
    }
Loading

Class diagram for distributed search worker node core components

classDiagram
    class Application {
        - ZOOKEEPER_ADDRESS
        - SESSION_TIMEOUT
        - current_server_port
        - zk
        - leader_election
        - service_registry
        - on_election_action
        - connected_event
        + __init__(port)
        + connect_to_zookeeper()
        + zk_listener(state)
        + run()
        + close()
        + main()
    }
    class LeaderElection {
        - ELECTION_NAMESPACE
        - zk
        - on_election_callback
        - current_znode_name
        - lock
        + __init__(zk, on_election_callback)
        + volunteer_for_leadership()
        + reelect_leader()
        + process(event)
    }
    class OnElectionAction {
        - service_registry
        - port
        - web_server
        + __init__(service_registry, port)
        + on_elected_to_be_leader()
        + on_worker()
    }
    class ServiceRegistry {
        - WORKERS_REGISTRY_ZNODE
        - COORDINATORS_REGISTRY_ZNODE
        - zk
        - service_registry_znode
        - all_service_addresses
        - current_znode
        - lock
        + __init__(zk, service_registry_znode)
        + create_service_registry_node()
        + register_to_cluster(metadata)
        + unregister_from_cluster()
        + register_for_updates()
        + get_all_service_addresses()
        + update_addresses()
        + process(event)
    }
    class SearchWorker {
        - ENDPOINT
        + handle_request(request_payload)
        + create_result(task)
        + parse_words_from_document(document)
        + get_endpoint()
    }
    class Aggregator {
        - web_client
        + __init__()
        + init()
        + send_tasks_to_workers(worker_addresses, tasks)
        + close()
    }
    class OnElectionCallback {
        <<abstract>>
        + on_elected_to_be_leader()
        + on_worker()
    }
    class DocumentData {
        - term_to_frequency
        + __init__()
        + put_term_frequency(term, frequency)
        + get_frequency(term)
    }
    class Result {
        - document_data
        + __init__()
        + add_document_data(document, data)
        + get_document_data(document)
        + get_all_results()
    }
    Application --> LeaderElection
    Application --> ServiceRegistry
    Application --> OnElectionAction
    LeaderElection --> OnElectionCallback
    OnElectionAction --> ServiceRegistry
    OnElectionAction --> SearchWorker
    ServiceRegistry --> KazooClient
    SearchWorker --> DocumentData
    SearchWorker --> Result
    Aggregator --> WebClient
    Result --> DocumentData
    OnElectionAction ..|> OnElectionCallback
Loading

Class diagram for TF-IDF calculation and document data model

classDiagram
    class TFIDF {
        + calculate_term_frequency(words, term)
        + create_document_data(words, terms)
        + get_documents_scores(terms, document_results)
        + calculate_document_score(terms, document_data, term_to_idf)
        + get_inverse_document_frequency(term, document_results)
        + get_term_to_inverse_document_frequency_map(terms, document_results)
        + get_words_from_document(lines)
        + get_words_from_line(line)
    }
    class DocumentData {
        - term_to_frequency
        + __init__()
        + put_term_frequency(term, frequency)
        + get_frequency(term)
    }
    TFIDF --> DocumentData
Loading

File-Level Changes

Change Details Files
New Application entry point orchestrating the worker node lifecycle
  • Documented module purpose, imports KazooClient and modules
  • Implemented Application class with connect, listener, run loop, close, and main startup sequence
  • Parsed optional port argument and wired up service registry and election
Application.py
Kazoo-based leader election utilities
  • Introduced ElectionLeader class with ephemeral sequential znode creation and CLI
  • Added LeaderElection class integrating election callbacks, predecessor watching, and re-election
leaderElection.py
leader_election.py
ServiceRegistry for dynamic service discovery
  • Created ServiceRegistry class to create registry znode
  • Implemented ephemeral sequential registration, unregistration, and update watching
  • Synchronized address updates with a lock
service_registry.py
OnElectionAction callbacks for role-based behavior
  • Implemented on_elected_to_be_leader to unregister and watch cluster
  • Implemented on_worker to start web server and register worker address
on_election_action.py
SearchWorker and TF-IDF text-analysis pipeline
  • Added TFIDF module with term frequency, IDF, scoring, and word parsing functions
  • Implemented SearchWorker to deserialize tasks, compute TF-IDF per document, and serialize results
  • Corrected imports and file parsing logic
tfidf.py
search/search_worker.py
Supporting data models, interface, and async aggregator
  • Added DocumentData and Result classes to store frequencies and results
  • Defined OnElectionCallback interface
  • Introduced Aggregator for asyncio-based task dispatch via WebClient
model/document_data.py
model/result.py
on_election_callback.py
aggregator.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@mintesin
mintesin merged commit 92bb5bf into main Aug 3, 2025

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @mintesin - I've reviewed your changes - here's some feedback:

Blocking issues:

  • time.sleep() call; did you mean to leave this in? (link)
  • time.sleep() call; did you mean to leave this in? (link)
  • function watch_node is defined inside a function but never used (link)

General comments:

  • There are two distinct leader election modules (leaderElection.py and leader_election.py); please consolidate them into a single implementation to avoid duplication and confusion.
  • The ZooKeeper listener in Application compares state to raw strings; it should use the KazooState enum values for more reliable state handling.
  • The TF‐IDF tokenizer can emit empty strings (e.g. from consecutive delimiters); consider filtering out blank tokens when splitting lines.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- There are two distinct leader election modules (leaderElection.py and leader_election.py); please consolidate them into a single implementation to avoid duplication and confusion.
- The ZooKeeper listener in Application compares state to raw strings; it should use the KazooState enum values for more reliable state handling.
- The TF‐IDF tokenizer can emit empty strings (e.g. from consecutive delimiters); consider filtering out blank tokens when splitting lines.

## Individual Comments

### Comment 1
<location> `search/search_worker.py:9` </location>
<code_context>
+import pickle
+from model.document_data import DocumentData
+from model.result import Result
+from tfidf import TFIDF  # Corrected import for TFIDF
+
+
</code_context>

<issue_to_address>
The TFIDF import does not match the defined functions in tfidf.py.

tfidf.py provides functions, not a TFIDF class, so this import will fail. Import the module instead and call its functions directly, e.g., 'import tfidf' and use 'tfidf.create_document_data(...)'.
</issue_to_address>

### Comment 2
<location> `search/search_worker.py:34` </location>
<code_context>
+        return result
+
+    def parse_words_from_document(self, document: str):
+        if not os.path.exists(document):
+            return []
+        with open(document, 'r', encoding='utf-8') as f:
+            lines = f.readlines()
+        words = TFIDF.get_words_from_document(lines)
</code_context>

<issue_to_address>
No error or warning is logged if a document does not exist.

Consider logging a warning or error when a document path does not exist to aid debugging.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
    def parse_words_from_document(self, document: str):
        if not os.path.exists(document):
            return []
        with open(document, 'r', encoding='utf-8') as f:
            lines = f.readlines()
        words = TFIDF.get_words_from_document(lines)
        return words
=======
    def parse_words_from_document(self, document: str):
        if not os.path.exists(document):
            import logging
            logging.warning(f"Document path does not exist: {document}")
            return []
        with open(document, 'r', encoding='utf-8') as f:
            lines = f.readlines()
        words = TFIDF.get_words_from_document(lines)
        return words
>>>>>>> REPLACE

</suggested_fix>

### Comment 3
<location> `model/document_data.py:9` </location>
<code_context>
+class DocumentData:
+    def __init__(self):
+        self.term_to_frequency = {}
+    # aggretagting the key -value ssyteml of words to the their tf
+    def put_term_frequency(self, term, frequency):
+        self.term_to_frequency[term] = frequency
</code_context>

<issue_to_address>
Typo in comment: 'aggretagting the key -value ssyteml of words to the their tf'.

Please correct the comment for clarity.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
    # aggretagting the key -value ssyteml of words to the their tf
=======
    # Aggregates the key-value system of words to their term frequency (tf)
>>>>>>> REPLACE

</suggested_fix>

### Comment 4
<location> `on_election_callback.py:9` </location>
<code_context>
+from abc import ABC, abstractmethod
+
+
+class OnElectionCallback(ABC):
+
+    @abstractmethod
</code_context>

<issue_to_address>
Consider removing the unused OnElectionCallback stub until it is actually needed.

The new `OnElectionCallback` stub isn’t used anywhere today, so it’s just extra surface area. I’d recommend deleting it until you actually need it. For example:

```bash
# remove the unused stub
git rm path/to/on_election_callback.py
```

If you later introduce an election callback interface, you can re-add it at that time.
</issue_to_address>

## Security Issues

### Issue 1
<location> `Application.py:78` </location>

<issue_to_address>
**security (python.lang.best-practice.arbitrary-sleep):** time.sleep() call; did you mean to leave this in?

*Source: opengrep*
</issue_to_address>

### Issue 2
<location> `leaderElection.py:105` </location>

<issue_to_address>
**security (python.lang.best-practice.arbitrary-sleep):** time.sleep() call; did you mean to leave this in?

*Source: opengrep*
</issue_to_address>

### Issue 3
<location> `leader_election.py:63` </location>

<issue_to_address>
**security (python.lang.maintainability.useless-inner-function):** function `watch_node` is defined inside a function but never used

*Source: opengrep*
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread search/search_worker.py
import pickle
from model.document_data import DocumentData
from model.result import Result
from tfidf import TFIDF # Corrected import for TFIDF

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): The TFIDF import does not match the defined functions in tfidf.py.

tfidf.py provides functions, not a TFIDF class, so this import will fail. Import the module instead and call its functions directly, e.g., 'import tfidf' and use 'tfidf.create_document_data(...)'.

Comment thread search/search_worker.py
Comment on lines +33 to +39
def parse_words_from_document(self, document: str):
if not os.path.exists(document):
return []
with open(document, 'r', encoding='utf-8') as f:
lines = f.readlines()
words = TFIDF.get_words_from_document(lines)
return words

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: No error or warning is logged if a document does not exist.

Consider logging a warning or error when a document path does not exist to aid debugging.

Suggested change
def parse_words_from_document(self, document: str):
if not os.path.exists(document):
return []
with open(document, 'r', encoding='utf-8') as f:
lines = f.readlines()
words = TFIDF.get_words_from_document(lines)
return words
def parse_words_from_document(self, document: str):
if not os.path.exists(document):
import logging
logging.warning(f"Document path does not exist: {document}")
return []
with open(document, 'r', encoding='utf-8') as f:
lines = f.readlines()
words = TFIDF.get_words_from_document(lines)
return words

Comment thread model/document_data.py
class DocumentData:
def __init__(self):
self.term_to_frequency = {}
# aggretagting the key -value ssyteml of words to the their tf

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick (typo): Typo in comment: 'aggretagting the key -value ssyteml of words to the their tf'.

Please correct the comment for clarity.

Suggested change
# aggretagting the key -value ssyteml of words to the their tf
# Aggregates the key-value system of words to their term frequency (tf)

Comment thread on_election_callback.py
from abc import ABC, abstractmethod


class OnElectionCallback(ABC):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (complexity): Consider removing the unused OnElectionCallback stub until it is actually needed.

The new OnElectionCallback stub isn’t used anywhere today, so it’s just extra surface area. I’d recommend deleting it until you actually need it. For example:

# remove the unused stub
git rm path/to/on_election_callback.py

If you later introduce an election callback interface, you can re-add it at that time.

Comment thread Application.py
"""
try:
while True:
time.sleep(1)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security (python.lang.best-practice.arbitrary-sleep): time.sleep() call; did you mean to leave this in?

Source: opengrep

Comment thread search/search_worker.py
Comment on lines +38 to +39
words = TFIDF.get_words_from_document(lines)
return words

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (code-quality): Inline variable that is immediately returned (inline-immediately-returned-variable)

Suggested change
words = TFIDF.get_words_from_document(lines)
return words
return TFIDF.get_words_from_document(lines)

Comment thread service_registry.py
print("Already registered to service registry")
return
self.current_znode = self.zk.create(
self.service_registry_znode + "/n_",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (code-quality): Use f-string instead of string concatenation (use-fstring-for-concatenation)

Suggested change
self.service_registry_znode + "/n_",
f"{self.service_registry_znode}/n_",

Comment thread service_registry.py
children = self.zk.get_children(self.service_registry_znode, watch=self.process)
addresses = []
for child in children:
service_full_path = self.service_registry_znode + "/" + child

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (code-quality): Use f-string instead of string concatenation [×2] (use-fstring-for-concatenation)

Suggested change
service_full_path = self.service_registry_znode + "/" + child
service_full_path = f"{self.service_registry_znode}/{child}"

Comment thread tfidf.py
Comment on lines +12 to +13
term_frequency = count / len(words) if words else 0
return term_frequency

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (code-quality): Inline variable that is immediately returned (inline-immediately-returned-variable)

Suggested change
term_frequency = count / len(words) if words else 0
return term_frequency
return count / len(words) if words else 0

Comment thread tfidf.py
Comment on lines +47 to +49
if n == 0:
return 0
return math.log10(len(document_results) / n)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (code-quality): We've found these issues:

Suggested change
if n == 0:
return 0
return math.log10(len(document_results) / n)
return 0 if n == 0 else math.log10(len(document_results) / n)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant