# Buggy code
def _register_internal_trigger_type(trigger_definition):
    try:
        trigger_type_db = create_trigger_type_db(trigger_type=trigger_definition)
    except (NotUniqueError, StackStormDBObjectConflictError):
        # We ignore conflict error since this operation is idempotent and race is not an issue
        LOG.debug(
            'Internal trigger type "%s" already exists, ignoring...'
            % (trigger_definition["name"]),
            exc_info=True,
        )

        ref = ResourceReference.to_string_reference(
            name=trigger_definition["name"], pack=trigger_definition["pack"]
        )
        trigger_type_db = get_trigger_type_db(ref)

    if trigger_type_db:
        LOG.debug("Registered internal trigger: %s.", trigger_definition["name"])

    # trigger types with parameters do no require a shadow trigger.
    if trigger_type_db and not trigger_type_db.parameters_schema:
        try:
            trigger_db = create_shadow_trigger(trigger_type_db)

            extra = {"trigger_db": trigger_db}
            LOG.audit(
                "Trigger created for parameter-less internal TriggerType. Trigger.id=%s"
                % (trigger_db.id),
                extra=extra,
            )
        except StackStormDBObjectConflictError:
            LOG.debug(
                'Shadow trigger "%s" already exists. Ignoring.',
                trigger_type_db.get_reference().ref,
                exc_info=True,
            )

        except (ValidationError, ValueError):
            LOG.exception(
                "Validation failed in shadow trigger. TriggerType=%s.",
                trigger_type_db.get_reference().ref,
            )
            raise

    return trigger_type_db


# Traceback (NotUniqueError)
Registering content...[flags = --config-file /etc/st2/st2.conf --register-all]
2017-11-10 16:04:14,401 INFO [-] Connecting to database "st2" @ "127.0.0.1:27017" as user "stackstorm".
2017-11-10 16:04:20,355 ERROR [-] Conflict while trying to save in DB.
Traceback (most recent call last):
File "/opt/stackstorm/st2/local/lib/python2.7/site-packages/st2common/persistence/base.py", line 173, in add_or_update
model_object = cls._get_impl().add_or_update(model_object)
File "/opt/stackstorm/st2/local/lib/python2.7/site-packages/st2common/models/db/__init__.py", line 336, in add_or_update
instance.save()
File "/opt/stackstorm/st2/local/lib/python2.7/site-packages/mongoengine/document.py", line 364, in save
raise NotUniqueError(message % six.text_type(err))
NotUniqueError: Tried to save duplicate unique keys (E11000 duplicate key error collection: st2.trigger_type_d_b index: uid_1 dup key: { : "trigger_type:core:st2.key_value_pair.update" })
2017-11-10 16:04:20,432 ERROR [-] Conflict while trying to save in DB.
Traceback (most recent call last):
File "/opt/stackstorm/st2/local/lib/python2.7/site-packages/st2common/persistence/base.py", line 173, in add_or_update
model_object = cls._get_impl().add_or_update(model_object)
File "/opt/stackstorm/st2/local/lib/python2.7/site-packages/st2common/models/db/__init__.py", line 336, in add_or_update
instance.save()
File "/opt/stackstorm/st2/local/lib/python2.7/site-packages/mongoengine/document.py", line 364, in save
raise NotUniqueError(message % six.text_type(err))
NotUniqueError: Tried to save duplicate unique keys (E11000 duplicate key error collection: st2.trigger_d_b index: uid_1 dup key: { : "trigger:core:st2.key_value_pair.value_change:99914b932bd37a50b983c5e7c90ae93b" })
2017-11-10 16:04:20,451 ERROR [-] Conflict while trying to save in DB.
Traceback (most recent call last):
File "/opt/stackstorm/st2/local/lib/python2.7/site-packages/st2common/persistence/base.py", line 173, in add_or_update
model_object = cls._get_impl().add_or_update(model_object)
File "/opt/stackstorm/st2/local/lib/python2.7/site-packages/st2common/models/db/__init__.py", line 336, in add_or_update
instance.save()
File "/opt/stackstorm/st2/local/lib/python2.7/site-packages/mongoengine/document.py", line 364, in save
raise NotUniqueError(message % six.text_type(err))
NotUniqueError: Tried to save duplicate unique keys (E11000 duplicate key error collection: st2.trigger_type_d_b index: uid_1 dup key: { : "trigger_type:core:st2.key_value_pair.delete" })
2017-11-10 16:04:20,567 INFO [-] =========================================================
2017-11-10 16:04:20,568 INFO [-] ############## Registering triggers #####################
2017-11-10 16:04:20,568 INFO [-] =========================================================
2017-11-10 16:04:20,673 INFO [-] Registered 0 triggers.

# Fixed code
def _register_internal_trigger_type(trigger_definition):
    try:
        trigger_type_db = create_trigger_type_db(
            trigger_type=trigger_definition, log_not_unique_error_as_debug=True
        )
    except (NotUniqueError, StackStormDBObjectConflictError):
        # We ignore conflict error since this operation is idempotent and race is not an issue
        LOG.debug(
            'Internal trigger type "%s" already exists, ignoring error...'
            % (trigger_definition["name"])
        )

        ref = ResourceReference.to_string_reference(
            name=trigger_definition["name"], pack=trigger_definition["pack"]
        )
        trigger_type_db = get_trigger_type_db(ref)

    if trigger_type_db:
        LOG.debug("Registered internal trigger: %s.", trigger_definition["name"])

    # trigger types with parameters do no require a shadow trigger.
    if trigger_type_db and not trigger_type_db.parameters_schema:
        try:
            trigger_db = create_shadow_trigger(
                trigger_type_db, log_not_unique_error_as_debug=True
            )

            extra = {"trigger_db": trigger_db}
            LOG.audit(
                "Trigger created for parameter-less internal TriggerType. Trigger.id=%s"
                % (trigger_db.id),
                extra=extra,
            )
        except (NotUniqueError, StackStormDBObjectConflictError):
            LOG.debug(
                'Shadow trigger "%s" already exists. Ignoring.',
                trigger_type_db.get_reference().ref,
                exc_info=True,
            )

        except (ValidationError, ValueError):
            LOG.exception(
                "Validation failed in shadow trigger. TriggerType=%s.",
                trigger_type_db.get_reference().ref,
            )
            raise

    return trigger_type_db