# Buggy code
def init_spawners(self):
    db = self.db

    user_summaries = [""]

    def _user_summary(user):
        parts = ["{0: >8}".format(user.name)]
        if user.admin:
            parts.append("admin")
        for name, spawner in sorted(user.spawners.items(), key=itemgetter(0)):
            if spawner.server:
                parts.append("%s:%s running at %s" % (user.name, name, spawner.server))
        return " ".join(parts)

    @gen.coroutine
    def user_stopped(user, server_name):
        spawner = user.spawners[server_name]
        status = yield spawner.poll()
        self.log.warning(
            "User %s server stopped with exit code: %s",
            user.name,
            status,
        )
        yield self.proxy.delete_user(user, server_name)
        yield user.stop(server_name)

    for orm_user in db.query(orm.User):
        self.users[orm_user.id] = user = User(orm_user, self.tornado_settings)
        self.log.debug("Loading state for %s from db", user.name)
        for name, spawner in user.spawners.items():
            status = 0
            if spawner.server:
                try:
                    status = yield spawner.poll()
                except Exception:
                    self.log.exception(
                        "Failed to poll spawner for %s, assuming the spawner is not running.",
                        user.name if name else "%s|%s" % (user.name, name),
                    )
                    status = -1

            if status is None:
                self.log.info("%s still running", user.name)
                spawner.add_poll_callback(user_stopped, user, name)
                spawner.start_polling()
            else:
                # user not running. This is expected if server is None,
                # but indicates the user's server died while the Hub wasn't running
                # if spawner.server is defined.
                log = self.log.warning if spawner.server else self.log.debug
                log("%s not running.", user.name)
                # remove all server or servers entry from db related to the user
                if spawner.server:
                    db.delete(spawner.orm_spawner.server)
        db.commit()

        user_summaries.append(_user_summary(user))

    self.log.debug("Loaded users: %s", "\n".join(user_summaries))
    db.commit()


# Traceback (sqlalchemy.exc.IntegrityError)
singleuser.cmd jupyterhub-singleuser
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/jupyterhub/app.py", line 1623, in launch_instance_async
yield self.initialize(argv)
File "/usr/lib/python3.5/types.py", line 179, in throw
return self.__wrapped.throw(tp, *rest)
File "/usr/local/lib/python3.5/dist-packages/jupyterhub/app.py", line 1385, in initialize
yield self.init_spawners()
File "/usr/local/lib/python3.5/dist-packages/jupyterhub/app.py", line 1240, in init_spawners
db.commit()
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/session.py", line 906, in commit
self.transaction.commit()
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/session.py", line 461, in commit
self._prepare_impl()
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/session.py", line 441, in _prepare_impl
self.session.flush()
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/session.py", line 2171, in flush
self._flush(objects)
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/session.py", line 2291, in _flush
transaction.rollback(_capture_exception=True)
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/util/langhelpers.py", line 66, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/util/compat.py", line 187, in reraise
raise value
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/session.py", line 2255, in _flush
flush_context.execute()
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/unitofwork.py", line 389, in execute
rec.execute(self)
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/unitofwork.py", line 577, in execute
uow
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/persistence.py", line 258, in delete_obj
cached_connections, mapper, table, delete)
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/orm/persistence.py", line 931, in _emit_delete_statements
c = connection.execute(statement, del_objects)
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 945, in execute
return meth(self, multiparams, params)
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/sql/elements.py", line 263, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1053, in _execute_clauseelement
compiled_sql, distilled_params
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1189, in _execute_context
context)
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1402, in _handle_dbapi_exception
exc_info
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/util/compat.py", line 186, in reraise
raise value.with_traceback(tb)
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context
context)
File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/default.py", line 470, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) update or delete on table "servers" violates foreign key constraint "spawners_server_id_fkey" on table "spawners"
DETAIL:  Key (id)=(24433) is still referenced from table "spawners".
[SQL: 'DELETE FROM servers WHERE servers.id = %(id)s'] [parameters: {'id': 24433}]

# Fixed code
def init_spawners(self):
    db = self.db

    user_summaries = [""]

    def _user_summary(user):
        parts = ["{0: >8}".format(user.name)]
        if user.admin:
            parts.append("admin")
        for name, spawner in sorted(user.spawners.items(), key=itemgetter(0)):
            if spawner.server:
                parts.append("%s:%s running at %s" % (user.name, name, spawner.server))
        return " ".join(parts)

    @gen.coroutine
    def user_stopped(user, server_name):
        spawner = user.spawners[server_name]
        status = yield spawner.poll()
        self.log.warning(
            "User %s server stopped with exit code: %s",
            user.name,
            status,
        )
        yield self.proxy.delete_user(user, server_name)
        yield user.stop(server_name)

    for orm_user in db.query(orm.User):
        self.users[orm_user.id] = user = User(orm_user, self.tornado_settings)
        self.log.debug("Loading state for %s from db", user.name)
        for name, spawner in user.spawners.items():
            status = 0
            if spawner.server:
                try:
                    status = yield spawner.poll()
                except Exception:
                    self.log.exception(
                        "Failed to poll spawner for %s, assuming the spawner is not running.",
                        spawner._log_name,
                    )
                    status = -1

            if status is None:
                self.log.info("%s still running", user.name)
                spawner.add_poll_callback(user_stopped, user, name)
                spawner.start_polling()
            else:
                # user not running. This is expected if server is None,
                # but indicates the user's server died while the Hub wasn't running
                # if spawner.server is defined.
                if spawner.server:
                    self.log.warning(
                        "%s appears to have stopped while the Hub was down",
                        spawner._log_name,
                    )
                    # remove server entry from db
                    db.delete(spawner.orm_spawner.server)
                    spawner.server = None
                else:
                    self.log.debug("%s not running", spawner._log_name)
        db.commit()

        user_summaries.append(_user_summary(user))

    self.log.debug("Loaded users: %s", "\n".join(user_summaries))
    db.commit()