prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  Alert notifications fail (sometime) with a SQLAlchemy error
  ### Issue Summary
  
  After migrating to 1.0.1 alerts are notified only sporadically to Slack (I cannot pinpoint exactly the conditions in which it happens).
  
  ### Steps to Reproduce
  
  1. Create a failing alert for an existing query
  2. Add your email and a Slack destination to your alert (the order seems to matter: add first the email destination then the slack destination)
  3. Refresh the query such that the alert would trigger
  4. You will receive an alert email but no slack alert
  5. In the back-end `celery_error.log` you will see an error message like
  ```
  [2017-04-18 13:13:58,184: ERROR/Worker-4] redash.tasks.check_alerts_for_query[fb4fee06-3318-44f7-8aaf-7984d792a793]: Error with processing destination
  Traceback (most recent call last):
    File "/opt/redash/redash.1.0.1.b2833/redash/tasks/alerts.py", line 23, in notify_subscriptions
      subscription.notify(alert, alert.query_rel, subscription.user, new_state, current_app, host)
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/attributes.py", line 237, in __get__
      return self.impl.get(instance_state(instance), dict_)
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/attributes.py", line 584, in get
      value = self.callable_(state, passive)
    File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/strategies.py", line 530, in _load_for_state
      (orm_util.state_str(state), self.key)
  DetachedInstanceError: Parent instance <AlertSubscription at 0x7fcd934f04d0> is not bound to a Session; lazy load operation of attribute 'user' cannot proceed
  ```
  
  I think this error is caused by the `subscription.user` call.
  My guess is that it is eventually caused by [`models.db.session.commit()`](https://github.com/getredash/redash/blob/master/redash/tasks/alerts.py#L51). 
  
  This "might" be connected to #1706 .
  
  ### Technical details:
  
  * Redash Version: 1.0.1+b2833
  * Browser/OS: (not relevant, error is in the backend)
  * How did you install Redash: ec2 from ami (in 2015), recently upgraded from 0.12 to 1.0.1
  
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `redash/tasks/general.py`
  Content:
  ```
  1 import requests
  2 from celery.utils.log import get_task_logger
  3 from flask_mail import Message
  4 from redash.worker import celery
  5 from redash.version_check import run_version_check
  6 from redash import models, mail, settings
  7 
  8 logger = get_task_logger(__name__)
  9 
  10 
  11 @celery.task(name="redash.tasks.record_event")
  12 def record_event(raw_event):
  13     event = models.Event.record(raw_event)
  14     models.db.session.commit()
  15 
  16     for hook in settings.EVENT_REPORTING_WEBHOOKS:
  17         logger.debug("Forwarding event to: %s", hook)
  18         try:
  19             data = {
  20               "schema": "iglu:io.redash.webhooks/event/jsonschema/1-0-0",
  21               "data": event.to_dict()
  22             }
  23             response = requests.post(hook, json=data)
  24             if response.status_code != 200:
  25                 logger.error("Failed posting to %s: %s", hook, response.content)
  26         except Exception:
  27             logger.exception("Failed posting to %s", hook)
  28 
  29 
  30 @celery.task(name="redash.tasks.version_check")
  31 def version_check():
  32     run_version_check()
  33 
  34 
  35 @celery.task(name="redash.tasks.subscribe")
  36 def subscribe(form):
  37     logger.info("Subscribing to: [security notifications=%s], [newsletter=%s]", form['security_notifications'], form['newsletter'])
  38     data = {
  39         'admin_name': form['name'],
  40         'admin_email': form['email'],
  41         'org_name': form['org_name'],
  42         'security_notifications': form['security_notifications'],
  43         'newsletter': form['newsletter']
  44     }
  45     requests.post('https://beacon.redash.io/subscribe', json=data)
  46 
  47 
  48 @celery.task(name="redash.tasks.send_mail")
  49 def send_mail(to, subject, html, text):
  50     from redash.wsgi import app
  51 
  52     try:
  53         with app.app_context():
  54             message = Message(recipients=to,
  55                               subject=subject,
  56                               html=html,
  57                               body=text)
  58 
  59             mail.send(message)
  60     except Exception:
  61         logger.exception('Failed sending message: %s', message.subject)
  62
  ```
  
  Path: `redash/destinations/email.py`
  Content:
  ```
  1 import logging
  2 
  3 from flask_mail import Message
  4 from redash import mail, settings
  5 from redash.destinations import *
  6 
  7 
  8 class Email(BaseDestination):
  9 
  10     @classmethod
  11     def configuration_schema(cls):
  12         return {
  13             "type": "object",
  14             "properties": {
  15                 "addresses": {
  16                     "type": "string"
  17                 },
  18                 "subject_template": {
  19                     "type": "string",
  20                     "default": settings.ALERTS_DEFAULT_MAIL_SUBJECT_TEMPLATE,
  21                     "title": "Subject Template"
  22                 }
  23             },
  24             "required": ["addresses"]
  25         }
  26 
  27     @classmethod
  28     def icon(cls):
  29         return 'fa-envelope'
  30 
  31     def notify(self, alert, query, user, new_state, app, host, options):
  32         recipients = [email for email in options.get('addresses', '').split(',') if email]
  33 
  34         if not recipients:
  35             logging.warning("No emails given. Skipping send.")
  36 
  37         html = """
  38         Check <a href="{host}/alerts/{alert_id}">alert</a> / check <a href="{host}/queries/{query_id}">query</a>.
  39         """.format(host=host, alert_id=alert.id, query_id=query.id)
  40         logging.debug("Notifying: %s", recipients)
  41 
  42         try:
  43             with app.app_context():
  44                 alert_name = alert.name.encode('utf-8', 'ignore')
  45                 state = new_state.upper()
  46                 subject_template = options.get('subject_template', settings.ALERTS_DEFAULT_MAIL_SUBJECT_TEMPLATE)
  47                 message = Message(
  48                     recipients=recipients,
  49                     subject=subject_template.format(alert_name=alert_name, state=state),
  50                     html=html
  51                 )
  52                 mail.send(message)
  53         except Exception:
  54             logging.exception("Mail send error.")
  55 
  56 register(Email)
  57
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/redash/destinations/email.py b/redash/destinations/email.py
  --- a/redash/destinations/email.py
  +++ b/redash/destinations/email.py
  @@ -40,16 +40,15 @@
           logging.debug("Notifying: %s", recipients)
   
           try:
  -            with app.app_context():
  -                alert_name = alert.name.encode('utf-8', 'ignore')
  -                state = new_state.upper()
  -                subject_template = options.get('subject_template', settings.ALERTS_DEFAULT_MAIL_SUBJECT_TEMPLATE)
  -                message = Message(
  -                    recipients=recipients,
  -                    subject=subject_template.format(alert_name=alert_name, state=state),
  -                    html=html
  -                )
  -                mail.send(message)
  +            alert_name = alert.name.encode('utf-8', 'ignore')
  +            state = new_state.upper()
  +            subject_template = options.get('subject_template', settings.ALERTS_DEFAULT_MAIL_SUBJECT_TEMPLATE)
  +            message = Message(
  +                recipients=recipients,
  +                subject=subject_template.format(alert_name=alert_name, state=state),
  +                html=html
  +            )
  +            mail.send(message)
           except Exception:
               logging.exception("Mail send error.")
   
  diff --git a/redash/tasks/general.py b/redash/tasks/general.py
  --- a/redash/tasks/general.py
  +++ b/redash/tasks/general.py
  @@ -1,9 +1,10 @@
   import requests
  +
   from celery.utils.log import get_task_logger
   from flask_mail import Message
  -from redash.worker import celery
  +from redash import mail, models, settings
   from redash.version_check import run_version_check
  -from redash import models, mail, settings
  +from redash.worker import celery
   
   logger = get_task_logger(__name__)
   
  @@ -50,12 +51,11 @@
       from redash.wsgi import app
   
       try:
  -        with app.app_context():
  -            message = Message(recipients=to,
  -                              subject=subject,
  -                              html=html,
  -                              body=text)
  +        message = Message(recipients=to,
  +                          subject=subject,
  +                          html=html,
  +                          body=text)
   
  -            mail.send(message)
  +        mail.send(message)
       except Exception:
           logger.exception('Failed sending message: %s', message.subject)
  
verification_info: {"golden_diff": "diff --git a/redash/destinations/email.py b/redash/destinations/email.py\n--- a/redash/destinations/email.py\n+++ b/redash/destinations/email.py\n@@ -40,16 +40,15 @@\n         logging.debug(\"Notifying: %s\", recipients)\n \n         try:\n-            with app.app_context():\n-                alert_name = alert.name.encode('utf-8', 'ignore')\n-                state = new_state.upper()\n-                subject_template = options.get('subject_template', settings.ALERTS_DEFAULT_MAIL_SUBJECT_TEMPLATE)\n-                message = Message(\n-                    recipients=recipients,\n-                    subject=subject_template.format(alert_name=alert_name, state=state),\n-                    html=html\n-                )\n-                mail.send(message)\n+            alert_name = alert.name.encode('utf-8', 'ignore')\n+            state = new_state.upper()\n+            subject_template = options.get('subject_template', settings.ALERTS_DEFAULT_MAIL_SUBJECT_TEMPLATE)\n+            message = Message(\n+                recipients=recipients,\n+                subject=subject_template.format(alert_name=alert_name, state=state),\n+                html=html\n+            )\n+            mail.send(message)\n         except Exception:\n             logging.exception(\"Mail send error.\")\n \ndiff --git a/redash/tasks/general.py b/redash/tasks/general.py\n--- a/redash/tasks/general.py\n+++ b/redash/tasks/general.py\n@@ -1,9 +1,10 @@\n import requests\n+\n from celery.utils.log import get_task_logger\n from flask_mail import Message\n-from redash.worker import celery\n+from redash import mail, models, settings\n from redash.version_check import run_version_check\n-from redash import models, mail, settings\n+from redash.worker import celery\n \n logger = get_task_logger(__name__)\n \n@@ -50,12 +51,11 @@\n     from redash.wsgi import app\n \n     try:\n-        with app.app_context():\n-            message = Message(recipients=to,\n-                              subject=subject,\n-                              html=html,\n-                              body=text)\n+        message = Message(recipients=to,\n+                          subject=subject,\n+                          html=html,\n+                          body=text)\n \n-            mail.send(message)\n+        mail.send(message)\n     except Exception:\n         logger.exception('Failed sending message: %s', message.subject)\n", "issue": "Alert notifications fail (sometime) with a SQLAlchemy error\n### Issue Summary\r\n\r\nAfter migrating to 1.0.1 alerts are notified only sporadically to Slack (I cannot pinpoint exactly the conditions in which it happens).\r\n\r\n### Steps to Reproduce\r\n\r\n1. Create a failing alert for an existing query\r\n2. Add your email and a Slack destination to your alert (the order seems to matter: add first the email destination then the slack destination)\r\n3. Refresh the query such that the alert would trigger\r\n4. You will receive an alert email but no slack alert\r\n5. In the back-end `celery_error.log` you will see an error message like\r\n```\r\n[2017-04-18 13:13:58,184: ERROR/Worker-4] redash.tasks.check_alerts_for_query[fb4fee06-3318-44f7-8aaf-7984d792a793]: Error with processing destination\r\nTraceback (most recent call last):\r\n  File \"/opt/redash/redash.1.0.1.b2833/redash/tasks/alerts.py\", line 23, in notify_subscriptions\r\n    subscription.notify(alert, alert.query_rel, subscription.user, new_state, current_app, host)\r\n  File \"/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/attributes.py\", line 237, in __get__\r\n    return self.impl.get(instance_state(instance), dict_)\r\n  File \"/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/attributes.py\", line 584, in get\r\n    value = self.callable_(state, passive)\r\n  File \"/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/strategies.py\", line 530, in _load_for_state\r\n    (orm_util.state_str(state), self.key)\r\nDetachedInstanceError: Parent instance <AlertSubscription at 0x7fcd934f04d0> is not bound to a Session; lazy load operation of attribute 'user' cannot proceed\r\n```\r\n\r\nI think this error is caused by the `subscription.user` call.\r\nMy guess is that it is eventually caused by [`models.db.session.commit()`](https://github.com/getredash/redash/blob/master/redash/tasks/alerts.py#L51). \r\n\r\nThis \"might\" be connected to #1706 .\r\n\r\n### Technical details:\r\n\r\n* Redash Version: 1.0.1+b2833\r\n* Browser/OS: (not relevant, error is in the backend)\r\n* How did you install Redash: ec2 from ami (in 2015), recently upgraded from 0.12 to 1.0.1\r\n\n", "before_files": [{"content": "import requests\nfrom celery.utils.log import get_task_logger\nfrom flask_mail import Message\nfrom redash.worker import celery\nfrom redash.version_check import run_version_check\nfrom redash import models, mail, settings\n\nlogger = get_task_logger(__name__)\n\n\n@celery.task(name=\"redash.tasks.record_event\")\ndef record_event(raw_event):\n    event = models.Event.record(raw_event)\n    models.db.session.commit()\n\n    for hook in settings.EVENT_REPORTING_WEBHOOKS:\n        logger.debug(\"Forwarding event to: %s\", hook)\n        try:\n            data = {\n              \"schema\": \"iglu:io.redash.webhooks/event/jsonschema/1-0-0\",\n              \"data\": event.to_dict()\n            }\n            response = requests.post(hook, json=data)\n            if response.status_code != 200:\n                logger.error(\"Failed posting to %s: %s\", hook, response.content)\n        except Exception:\n            logger.exception(\"Failed posting to %s\", hook)\n\n\n@celery.task(name=\"redash.tasks.version_check\")\ndef version_check():\n    run_version_check()\n\n\n@celery.task(name=\"redash.tasks.subscribe\")\ndef subscribe(form):\n    logger.info(\"Subscribing to: [security notifications=%s], [newsletter=%s]\", form['security_notifications'], form['newsletter'])\n    data = {\n        'admin_name': form['name'],\n        'admin_email': form['email'],\n        'org_name': form['org_name'],\n        'security_notifications': form['security_notifications'],\n        'newsletter': form['newsletter']\n    }\n    requests.post('https://beacon.redash.io/subscribe', json=data)\n\n\n@celery.task(name=\"redash.tasks.send_mail\")\ndef send_mail(to, subject, html, text):\n    from redash.wsgi import app\n\n    try:\n        with app.app_context():\n            message = Message(recipients=to,\n                              subject=subject,\n                              html=html,\n                              body=text)\n\n            mail.send(message)\n    except Exception:\n        logger.exception('Failed sending message: %s', message.subject)\n", "path": "redash/tasks/general.py"}, {"content": "import logging\n\nfrom flask_mail import Message\nfrom redash import mail, settings\nfrom redash.destinations import *\n\n\nclass Email(BaseDestination):\n\n    @classmethod\n    def configuration_schema(cls):\n        return {\n            \"type\": \"object\",\n            \"properties\": {\n                \"addresses\": {\n                    \"type\": \"string\"\n                },\n                \"subject_template\": {\n                    \"type\": \"string\",\n                    \"default\": settings.ALERTS_DEFAULT_MAIL_SUBJECT_TEMPLATE,\n                    \"title\": \"Subject Template\"\n                }\n            },\n            \"required\": [\"addresses\"]\n        }\n\n    @classmethod\n    def icon(cls):\n        return 'fa-envelope'\n\n    def notify(self, alert, query, user, new_state, app, host, options):\n        recipients = [email for email in options.get('addresses', '').split(',') if email]\n\n        if not recipients:\n            logging.warning(\"No emails given. Skipping send.\")\n\n        html = \"\"\"\n        Check <a href=\"{host}/alerts/{alert_id}\">alert</a> / check <a href=\"{host}/queries/{query_id}\">query</a>.\n        \"\"\".format(host=host, alert_id=alert.id, query_id=query.id)\n        logging.debug(\"Notifying: %s\", recipients)\n\n        try:\n            with app.app_context():\n                alert_name = alert.name.encode('utf-8', 'ignore')\n                state = new_state.upper()\n                subject_template = options.get('subject_template', settings.ALERTS_DEFAULT_MAIL_SUBJECT_TEMPLATE)\n                message = Message(\n                    recipients=recipients,\n                    subject=subject_template.format(alert_name=alert_name, state=state),\n                    html=html\n                )\n                mail.send(message)\n        except Exception:\n            logging.exception(\"Mail send error.\")\n\nregister(Email)\n", "path": "redash/destinations/email.py"}], "after_files": [{"content": "import requests\n\nfrom celery.utils.log import get_task_logger\nfrom flask_mail import Message\nfrom redash import mail, models, settings\nfrom redash.version_check import run_version_check\nfrom redash.worker import celery\n\nlogger = get_task_logger(__name__)\n\n\n@celery.task(name=\"redash.tasks.record_event\")\ndef record_event(raw_event):\n    event = models.Event.record(raw_event)\n    models.db.session.commit()\n\n    for hook in settings.EVENT_REPORTING_WEBHOOKS:\n        logger.debug(\"Forwarding event to: %s\", hook)\n        try:\n            data = {\n              \"schema\": \"iglu:io.redash.webhooks/event/jsonschema/1-0-0\",\n              \"data\": event.to_dict()\n            }\n            response = requests.post(hook, json=data)\n            if response.status_code != 200:\n                logger.error(\"Failed posting to %s: %s\", hook, response.content)\n        except Exception:\n            logger.exception(\"Failed posting to %s\", hook)\n\n\n@celery.task(name=\"redash.tasks.version_check\")\ndef version_check():\n    run_version_check()\n\n\n@celery.task(name=\"redash.tasks.subscribe\")\ndef subscribe(form):\n    logger.info(\"Subscribing to: [security notifications=%s], [newsletter=%s]\", form['security_notifications'], form['newsletter'])\n    data = {\n        'admin_name': form['name'],\n        'admin_email': form['email'],\n        'org_name': form['org_name'],\n        'security_notifications': form['security_notifications'],\n        'newsletter': form['newsletter']\n    }\n    requests.post('https://beacon.redash.io/subscribe', json=data)\n\n\n@celery.task(name=\"redash.tasks.send_mail\")\ndef send_mail(to, subject, html, text):\n    from redash.wsgi import app\n\n    try:\n        message = Message(recipients=to,\n                          subject=subject,\n                          html=html,\n                          body=text)\n\n        mail.send(message)\n    except Exception:\n        logger.exception('Failed sending message: %s', message.subject)\n", "path": "redash/tasks/general.py"}, {"content": "import logging\n\nfrom flask_mail import Message\nfrom redash import mail, settings\nfrom redash.destinations import *\n\n\nclass Email(BaseDestination):\n\n    @classmethod\n    def configuration_schema(cls):\n        return {\n            \"type\": \"object\",\n            \"properties\": {\n                \"addresses\": {\n                    \"type\": \"string\"\n                },\n                \"subject_template\": {\n                    \"type\": \"string\",\n                    \"default\": settings.ALERTS_DEFAULT_MAIL_SUBJECT_TEMPLATE,\n                    \"title\": \"Subject Template\"\n                }\n            },\n            \"required\": [\"addresses\"]\n        }\n\n    @classmethod\n    def icon(cls):\n        return 'fa-envelope'\n\n    def notify(self, alert, query, user, new_state, app, host, options):\n        recipients = [email for email in options.get('addresses', '').split(',') if email]\n\n        if not recipients:\n            logging.warning(\"No emails given. Skipping send.\")\n\n        html = \"\"\"\n        Check <a href=\"{host}/alerts/{alert_id}\">alert</a> / check <a href=\"{host}/queries/{query_id}\">query</a>.\n        \"\"\".format(host=host, alert_id=alert.id, query_id=query.id)\n        logging.debug(\"Notifying: %s\", recipients)\n\n        try:\n            alert_name = alert.name.encode('utf-8', 'ignore')\n            state = new_state.upper()\n            subject_template = options.get('subject_template', settings.ALERTS_DEFAULT_MAIL_SUBJECT_TEMPLATE)\n            message = Message(\n                recipients=recipients,\n                subject=subject_template.format(alert_name=alert_name, state=state),\n                html=html\n            )\n            mail.send(message)\n        except Exception:\n            logging.exception(\"Mail send error.\")\n\nregister(Email)\n", "path": "redash/destinations/email.py"}]}