Skip to content

[Bug] Importing Pinecone is Making Network Calls that Don't Timeout #189

Closed

Description

@jacob-petterle

Is this a new bug in the Pinecone Python client?

  • I believe this is a new bug in the Pinecone Python Client
  • I have searched the existing issues, and I could not find an existing issue for this bug

Current Behavior

When importing the pinecone client in a docker container lambda on aws in a public subnet (not able to connect to the internet), importing the pinecone client stalls the entire initialization of the container.

Expected Behavior

Import without stalling the entire container.

Steps To Reproduce

Steps assume you have aws cdk cli tool installed and account configured

  1. Download zip and unzip
  2. cd into directory
  3. in app.py replace the ACCOUNT_NUMBER & ACCOUNT_NUMBER with appropriate values
  4. run cdk deploy --require-approval never
  5. navigate to the AWS console
  6. Invoke the public lambda with URL in the console (without internet connectivity) and observe that the container stalls
  7. Invoke the private lambda with URL in the console (with internet access in the private subnet) and observe that the import works

Full Test Zip:
test-pinecone.zip

Relevant log output

Public Subnet Lambda (without internet connectivity)

2023-07-08T06:49:52.852-06:00	2023-07-08 12:49:52.852 | INFO | main:<module>:2 - Importing libraries

2023-07-08T06:50:05.122-06:00	2023-07-08 12:50:05.122 | INFO | main:<module>:2 - Importing libraries

2023-07-08T06:51:32.647-06:00	EXTENSION Name: lambda-adapter State: Ready Events: []

2023-07-08T06:51:32.647-06:00	START RequestId: 4bd8c7b9-70ff-4ab1-b98c-cfbd98b7e80f Version: $LATEST

2023-07-08T06:51:32.663-06:00	2023-07-08T12:51:32.663Z 4bd8c7b9-70ff-4ab1-b98c-cfbd98b7e80f Task timed out after 90.11 seconds

2023-07-08T06:51:32.663-06:00	END RequestId: 4bd8c7b9-70ff-4ab1-b98c-cfbd98b7e80f

2023-07-08T06:51:32.663-06:00	REPORT RequestId: 4bd8c7b9-70ff-4ab1-b98c-cfbd98b7e80f Duration: 90106.73 ms Billed Duration: 90000 ms Memory Size: 128 MB Max Memory Used: 24 MB XRAY TraceId: 1-64a95b6f-41ce4c1d62aaa3d621c5dbd2 SegmentId: 60fe0233117e66e3 Sampled: true

2023-07-08T06:51:32.878-06:00	2023-07-08 12:51:32.878 | INFO | main:<module>:2 - Importing libraries

Private subnet lambda with internet access:

2023-07-08T06:49:36.040-06:00	2023-07-08 12:49:36.040 | INFO | main:<module>:2 - Importing libraries

2023-07-08T06:49:43.210-06:00	2023-07-08 12:49:43.210 | INFO | main:create_app:8 - Creating app

2023-07-08T06:49:43.211-06:00	2023-07-08 12:49:43.210 | INFO | main:create_app:10 - App created

2023-07-08T06:49:43.211-06:00	INFO: Started server process [12]

2023-07-08T06:49:43.211-06:00	INFO: Waiting for application startup.

2023-07-08T06:49:43.212-06:00	INFO: Application startup complete.

2023-07-08T06:49:43.212-06:00	INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

2023-07-08T06:49:43.221-06:00	INFO: 127.0.0.1:39946 - "GET / HTTP/1.1" 404 Not Found

2023-07-08T06:49:43.222-06:00	EXTENSION Name: lambda-adapter State: Ready Events: []

2023-07-08T06:49:43.225-06:00	START RequestId: c356ce53-8eff-4e6f-9414-a4ff7d601300 Version: $LATEST

2023-07-08T06:49:43.232-06:00	INFO: 71.195.207.116:0 - "GET / HTTP/1.1" 404 Not Found

2023-07-08T06:49:43.234-06:00	END RequestId: c356ce53-8eff-4e6f-9414-a4ff7d601300

2023-07-08T06:49:43.234-06:00	REPORT RequestId: c356ce53-8eff-4e6f-9414-a4ff7d601300 Duration: 9.26 ms Billed Duration: 7756 ms Memory Size: 128

Environment

- OS: linux
- Python:3.10 (also tested with 3.8)
- pinecone: 2.2.2 (also tested with 2.2.0 & 2.0.3)

Additional Context

I'm pretty sure the issue is coming from this code:

action_api = ActionAPI(host=config.controller_host, api_key=config.api_key)
try:
    whoami_response = action_api.whoami()
except requests.exceptions.RequestException:
    # proceed with default values; reset() may be called later w/ correct values
    whoami_response = WhoAmIResponse()

Which ultimately calls this guy:


import requests
from requests.exceptions import HTTPError


class BaseAPI:
    """Base class for HTTP API calls."""

    def __init__(self, host: str, api_key: str = None):
        self.host = host
        self.api_key = api_key

    @property
    def headers(self):
        return {"api-key": self.api_key}

    def _send_request(self, request_handler, url, **kwargs):
        response = request_handler('{0}{1}'.format(self.host, url), headers=self.headers, **kwargs)
        try:
            response.raise_for_status()
        except HTTPError as e:
            e.args = e.args + (response.text,)
            raise e
        return response.json()

    def get(self, url: str, params: dict = None):
        return self._send_request(requests.get, url, params=params)

    def post(self, url: str, json: dict = None):
        return self._send_request(requests.post, url, json=json)

    def patch(self, url: str, json: dict = None):
        return self._send_request(requests.patch, url, json=json)

    def delete(self, url: str):
        return self._send_request(requests.delete, url)

I tested this on normal docker containers (not with the web adapter that AWS offers, and I still got the same stall). However, I haven't tested with a normal python lambda, but that should be easy to do with a couple modifications to the code I provided.

To be completely honest, this bug was pretty frustrating for three reasons:

  1. Why is the client initiating network connections during import???? That's a NoNo as it is completely unexpected behavior and typically should occur in the init method. This makes unit testing interesting as you should be able to unit test without external connections.
    This atypical behavior made this really hard to debug and made me think that there was a compatibility issue when loading a pinecone dependency(so I spent a majority of my time focusing on checking compatibility (python version, base container image, pinecone version, other imports not playing well) instead of the root cause in the network call) -> this is why it's not a great idea to do this in imports
  2. Even if this is needed in the import (which it shouldn't be), why isn't there a timeout on the BaseAPI? This is a basic safe guard against issues like this.
  3. This was hard to debug because other imports (such as langchain) import pinecone in their code, so it made it appear that langchain was also incompatible.
  4. For applications where speed is important, making network calls in an import is not ideal (especially when there is a second network call in the init method).

I know the above may sound harsh, but please know that I really really love what you guys make and how you are empowering tons of people to get into search. I'm excited to continue using the products you all have developed. 🥳

Preview of files in zip:

app.py

from aws_cdk import (
    aws_lambda as _lambda,
    App,
    aws_ec2 as ec2,
    Stack,
    Environment,
    Duration,
)
from constructs import Construct

app: App = App()

env = Environment(account="ACCOUNT_NUMBER", region="ACCOUNT_NUMBER")

class TestStack(Stack):

    def __init__(self, scope: Construct, id_: str, **kwargs) -> None:
        super().__init__(scope, id_, **kwargs)
        vpc = ec2.Vpc(
            scope=self,
            id="pinecone-test-vpc",
            vpc_name="pinecone-test-vpc",
            max_azs=1,
            nat_gateways=1,
            subnet_configuration=[
                ec2.SubnetConfiguration(
                    name="public",
                    subnet_type=ec2.SubnetType.PUBLIC,
                    cidr_mask=24,
                ),
                ec2.SubnetConfiguration(
                    name="private",
                    subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS,
                    cidr_mask=24,
                )
            ]

        )
        

        func: _lambda.DockerImageFunction = _lambda.DockerImageFunction(
            scope=self,
            id="pinecone-test-pbulic-subnet",
            function_name="pinecone-test-pbulic-subnet",
            tracing=_lambda.Tracing.ACTIVE,
            code=_lambda.DockerImageCode.from_image_asset("."),
            allow_public_subnet=True,
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC),
            timeout=Duration.seconds(90),
        )
        func.add_function_url(
            auth_type=_lambda.FunctionUrlAuthType.NONE,
            cors=_lambda.FunctionUrlCorsOptions(
                allowed_headers=["*"],
                allowed_origins=["*"],
            ),
            invoke_mode=_lambda.InvokeMode.BUFFERED,
        )
        func_2: _lambda.DockerImageFunction = _lambda.DockerImageFunction(
            scope=self,
            id="pinecone-test-private-internet",
            function_name="pinecone-test-private-internet",
            tracing=_lambda.Tracing.ACTIVE,
            code=_lambda.DockerImageCode.from_image_asset("."),
            allow_public_subnet=True,
            vpc=vpc,
            vpc_subnets=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PRIVATE_WITH_EGRESS),
            timeout=Duration.seconds(90),
        )
        func_2.add_function_url(
            auth_type=_lambda.FunctionUrlAuthType.NONE,
            cors=_lambda.FunctionUrlCorsOptions(
                allowed_headers=["*"],
                allowed_origins=["*"],
            ),
            invoke_mode=_lambda.InvokeMode.BUFFERED,
        )
            

stack = TestStack(app, "pinecone-test", env=env)

app.synth()

Dockerfile

FROM public.ecr.aws/docker/library/python:3.10-slim-buster AS build
COPY --from=public.ecr.aws/awsguru/aws-lambda-adapter:0.7.0 /lambda-adapter /opt/extensions/lambda-adapter
WORKDIR /var/task
COPY requirements.txt .
RUN pip install --no-cache-dir pip && pip install -r requirements.txt && find . -name '*.pyc' -delete
RUN pip install uvicorn
FROM build AS add-build-context
ENV PORT=8000
WORKDIR /var/task
COPY . .
CMD exec uvicorn --port $PORT --factory main:create_app

main.py

from loguru import logger
logger.info("Importing libraries")
import pinecone
from fastapi import FastAPI


def create_app():
    logger.info("Creating app")
    app = FastAPI()
    logger.info("App created")
    return app

requirements.txt

fastapi
pinecone-client

Activity

  1. added
    bug
    on Jul 8, 2023
  2. micahjsmith commented on Aug 10, 2023

    @micahjsmith

    +1

    we also found this behavior. making network calls on import is unacceptable for thirdparty code. I was astounded to see that the client had been designed this way. plus there is no way to disable this using environment variables, etc.

  3. daverigby commented on May 3, 2024

    @daverigby
    Contributor

    Pinecone client initialisation has been significantly refactored as of v3.0.0 - global state (including some network activity) has been moved into the Pinecone and Index objects - see the SDK 3 migration guide for details.

    As such, I believe the network calls (and associated lack of timeouts) should be resolved as of SDK 3.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions